diff --git a/central_pane/dtdAbbreviation.json b/central_pane/dtdAbbreviation.json index 6f6b7a3..8717cca 100644 --- a/central_pane/dtdAbbreviation.json +++ b/central_pane/dtdAbbreviation.json @@ -1,12 +1,12 @@ /* -* Copyright © 2016-2017 by IntegrIT S.A. dba Hackolade. All rights reserved. -* -* The copyright to the computer software herein is the property of IntegrIT S.A. -* The software may be used and/or copied only with the written permission of -* IntegrIT S.A. or in accordance with the terms and conditions stipulated in -* the agreement/contract under which the software has been supplied. -* -*/ + * Copyright © 2016-2017 by IntegrIT S.A. dba Hackolade. All rights reserved. + * + * The copyright to the computer software herein is the property of IntegrIT S.A. + * The software may be used and/or copied only with the written permission of + * IntegrIT S.A. or in accordance with the terms and conditions stipulated in + * the agreement/contract under which the software has been supplied. + * + */ { "map": "{...}", "list": "[...]", @@ -15,4 +15,4 @@ "bool": "{0/1}", "bytes": "{BYTES}", "null": "{null}" -} \ No newline at end of file +} diff --git a/forward_engineering/api.js b/forward_engineering/api.js index a9bc6aa..77f4045 100644 --- a/forward_engineering/api.js +++ b/forward_engineering/api.js @@ -1,81 +1,110 @@ -const applyToInstanceHelper = require("./helpers/applyToInstanceHelper"); -const scriptHelper = require("./helpers/scriptHelper"); - -module.exports = { - generateContainerScript(data, logger, callback, app) { - try { - const _ = app.require('lodash'); - const insertSamplesOption = _.get(data, 'options.additionalOptions', []).find(option => option.id === 'INCLUDE_SAMPLES') || {}; - const withSamples = data.options.origin !== 'ui'; - const useDb = scriptHelper.useDbStatement(data.containerData); - let script = useDb + '\n\n' + data.entities.map(entityId => { - const entityData = data.entityData[entityId]; - const script = scriptHelper.getScript({ - entityData, - containerData: data.containerData, - jsonSchema: JSON.parse(data.jsonSchema[entityId]), - definitions: { - internal: JSON.parse(data.internalDefinitions[entityId]), - model: JSON.parse(data.modelDefinitions), - external: JSON.parse(data.externalDefinitions), - }, - }); - - if (entityData?.[0]?.isActivated) { - return script; - } - - return `/*\n${script}\n*/` - }).join('\n\n'); - - const samples = scriptHelper.insertSamples(data); - script += withSamples ? '\n' + samples : ''; - - if (withSamples || !insertSamplesOption.value) { - return callback(null, script); - } - - - return callback(null, [ - { title: 'MongoDB script', script }, - { - title: 'Sample data', - script: samples, - }, - ]); - } catch (e) { - const error = { message: e.message, stack: e.stack }; - logger.log('error', error, 'DocumentDB forward engineering error'); - callback(error); - } - }, - generateScript(data, logger, callback, app) { - try { - const useDb = scriptHelper.useDbStatement(data.containerData); - const script = scriptHelper.getScript({ - containerData: data.containerData, - entityData: data.entityData, - jsonSchema: JSON.parse(data.jsonSchema), - definitions: { - model: JSON.parse(data.modelDefinitions), - internal: JSON.parse(data.internalDefinitions), - external: JSON.parse(data.externalDefinitions), - }, - }); - const samples = scriptHelper.insertSample({ - containerData: data.containerData, - entityData: data.entityData, - sample: data.jsonData, - }); - - return callback(null, [useDb, script, samples].join('\n\n')); - } catch (e) { - const error = { message: e.message, stack: e.stack }; - logger.log('error', error, 'DocumentDB forward engineering error'); - callback(error); - } - }, - applyToInstance: applyToInstanceHelper.applyToInstance, - - testConnection: applyToInstanceHelper.testConnection, -}; +var Pz=Object.defineProperty;var s=(e,t)=>Pz(e,"name",{value:t,configurable:!0});var E=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var dC=E((aa,ec)=>{(function(){var e,t="4.17.21",r=200,n="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",i="Expected a function",a="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,l="__lodash_placeholder__",h=1,m=2,p=4,g=1,w=2,O=1,N=2,A=4,M=8,L=16,I=32,R=64,Y=128,W=256,ee=512,Ee=30,V="...",fe=800,ne=16,J=1,K=2,ue=3,me=1/0,oe=9007199254740991,ae=17976931348623157e292,De=0/0,le=4294967295,Ke=le-1,An=le>>>1,Ft=[["ary",Y],["bind",O],["bindKey",N],["curry",M],["curryRight",L],["flip",ee],["partial",I],["partialRight",R],["rearg",W]],lr="[object Arguments]",Zt="[object Array]",hr="[object AsyncFunction]",sn="[object Boolean]",dr="[object Date]",Hs="[object DOMException]",Cn="[object Error]",st="[object Function]",Fn="[object GeneratorFunction]",bt="[object Map]",$n="[object Number]",Pu="[object Null]",pr="[object Object]",Vs="[object Promise]",Xf="[object Proxy]",$r="[object RegExp]",mr="[object Set]",Ji="[object String]",Yo="[object Symbol]",Jf="[object Undefined]",zn="[object WeakMap]",Lu="[object WeakSet]",Uu="[object ArrayBuffer]",ko="[object DataView]",eg="[object Float32Array]",tg="[object Float64Array]",rg="[object Int8Array]",ng="[object Int16Array]",ig="[object Int32Array]",sg="[object Uint8Array]",og="[object Uint8ClampedArray]",ag="[object Uint16Array]",ug="[object Uint32Array]",nW=/\b__p \+= '';/g,iW=/\b(__p \+=) '' \+/g,sW=/(__e\(.*?\)|\b__t\)) \+\n'';/g,UN=/&(?:amp|lt|gt|quot|#39);/g,jN=/[&<>"']/g,oW=RegExp(UN.source),aW=RegExp(jN.source),uW=/<%-([\s\S]+?)%>/g,cW=/<%([\s\S]+?)%>/g,WN=/<%=([\s\S]+?)%>/g,fW=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,lW=/^\w*$/,hW=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,cg=/[\\^$.*+?()[\]{}|]/g,dW=RegExp(cg.source),fg=/^\s+/,pW=/\s/,mW=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,gW=/\{\n\/\* \[wrapped with (.+)\] \*/,yW=/,? & /,SW=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,_W=/[()=,{}\[\]\/\s]/,wW=/\\(\\)?/g,vW=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,FN=/\w*$/,OW=/^[-+]0x[0-9a-f]+$/i,EW=/^0b[01]+$/i,TW=/^\[object .+?Constructor\]$/,NW=/^0o[0-7]+$/i,bW=/^(?:0|[1-9]\d*)$/,AW=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Zf=/($^)/,CW=/['\n\r\u2028\u2029\\]/g,Qf="\\ud800-\\udfff",IW="\\u0300-\\u036f",BW="\\ufe20-\\ufe2f",RW="\\u20d0-\\u20ff",$N=IW+BW+RW,zN="\\u2700-\\u27bf",HN="a-z\\xdf-\\xf6\\xf8-\\xff",xW="\\xac\\xb1\\xd7\\xf7",MW="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",DW="\\u2000-\\u206f",qW=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",VN="A-Z\\xc0-\\xd6\\xd8-\\xde",YN="\\ufe0e\\ufe0f",kN=xW+MW+DW+qW,lg="['\u2019]",PW="["+Qf+"]",GN="["+kN+"]",el="["+$N+"]",KN="\\d+",LW="["+zN+"]",XN="["+HN+"]",JN="[^"+Qf+kN+KN+zN+HN+VN+"]",hg="\\ud83c[\\udffb-\\udfff]",UW="(?:"+el+"|"+hg+")",ZN="[^"+Qf+"]",dg="(?:\\ud83c[\\udde6-\\uddff]){2}",pg="[\\ud800-\\udbff][\\udc00-\\udfff]",Go="["+VN+"]",QN="\\u200d",eb="(?:"+XN+"|"+JN+")",jW="(?:"+Go+"|"+JN+")",tb="(?:"+lg+"(?:d|ll|m|re|s|t|ve))?",rb="(?:"+lg+"(?:D|LL|M|RE|S|T|VE))?",nb=UW+"?",ib="["+YN+"]?",WW="(?:"+QN+"(?:"+[ZN,dg,pg].join("|")+")"+ib+nb+")*",FW="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",$W="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",sb=ib+nb+WW,zW="(?:"+[LW,dg,pg].join("|")+")"+sb,HW="(?:"+[ZN+el+"?",el,dg,pg,PW].join("|")+")",VW=RegExp(lg,"g"),YW=RegExp(el,"g"),mg=RegExp(hg+"(?="+hg+")|"+HW+sb,"g"),kW=RegExp([Go+"?"+XN+"+"+tb+"(?="+[GN,Go,"$"].join("|")+")",jW+"+"+rb+"(?="+[GN,Go+eb,"$"].join("|")+")",Go+"?"+eb+"+"+tb,Go+"+"+rb,$W,FW,KN,zW].join("|"),"g"),GW=RegExp("["+QN+Qf+$N+YN+"]"),KW=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,XW=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],JW=-1,ft={};ft[eg]=ft[tg]=ft[rg]=ft[ng]=ft[ig]=ft[sg]=ft[og]=ft[ag]=ft[ug]=!0,ft[lr]=ft[Zt]=ft[Uu]=ft[sn]=ft[ko]=ft[dr]=ft[Cn]=ft[st]=ft[bt]=ft[$n]=ft[pr]=ft[$r]=ft[mr]=ft[Ji]=ft[zn]=!1;var ot={};ot[lr]=ot[Zt]=ot[Uu]=ot[ko]=ot[sn]=ot[dr]=ot[eg]=ot[tg]=ot[rg]=ot[ng]=ot[ig]=ot[bt]=ot[$n]=ot[pr]=ot[$r]=ot[mr]=ot[Ji]=ot[Yo]=ot[sg]=ot[og]=ot[ag]=ot[ug]=!0,ot[Cn]=ot[st]=ot[zn]=!1;var ZW={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"Ae",\u00E6:"ae",\u00DE:"Th",\u00FE:"th",\u00DF:"ss",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"IJ",\u0133:"ij",\u0152:"Oe",\u0153:"oe",\u0149:"'n",\u017F:"s"},QW={"&":"&","<":"<",">":">",'"':""","'":"'"},e3={"&":"&","<":"<",">":">",""":'"',"'":"'"},t3={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},r3=parseFloat,n3=parseInt,ob=typeof global=="object"&&global&&global.Object===Object&&global,i3=typeof self=="object"&&self&&self.Object===Object&&self,Lt=ob||i3||Function("return this")(),gg=typeof aa=="object"&&aa&&!aa.nodeType&&aa,Ys=gg&&typeof ec=="object"&&ec&&!ec.nodeType&&ec,ab=Ys&&Ys.exports===gg,yg=ab&&ob.process,on=function(){try{var C=Ys&&Ys.require&&Ys.require("util").types;return C||yg&&yg.binding&&yg.binding("util")}catch{}}(),ub=on&&on.isArrayBuffer,cb=on&&on.isDate,fb=on&&on.isMap,lb=on&&on.isRegExp,hb=on&&on.isSet,db=on&&on.isTypedArray;function zr(C,U,D){switch(D.length){case 0:return C.call(U);case 1:return C.call(U,D[0]);case 2:return C.call(U,D[0],D[1]);case 3:return C.call(U,D[0],D[1],D[2])}return C.apply(U,D)}s(zr,"apply");function s3(C,U,D,te){for(var we=-1,Ye=C==null?0:C.length;++we-1}s(tl,"arrayIncludes");function Sg(C,U,D){for(var te=-1,we=C==null?0:C.length;++te-1;);return D}s(wb,"charsStartIndex");function vb(C,U){for(var D=C.length;D--&&Ko(U,C[D],0)>-1;);return D}s(vb,"charsEndIndex");function p3(C,U){for(var D=C.length,te=0;D--;)C[D]===U&&++te;return te}s(p3,"countHolders");var m3=Og(ZW),g3=Og(QW);function y3(C){return"\\"+t3[C]}s(y3,"escapeStringChar");function S3(C,U){return C==null?e:C[U]}s(S3,"getValue");function Xo(C){return GW.test(C)}s(Xo,"hasUnicode");function _3(C){return KW.test(C)}s(_3,"hasUnicodeWord");function w3(C){for(var U,D=[];!(U=C.next()).done;)D.push(U.value);return D}s(w3,"iteratorToArray");function bg(C){var U=-1,D=Array(C.size);return C.forEach(function(te,we){D[++U]=[we,te]}),D}s(bg,"mapToArray");function Ob(C,U){return function(D){return C(U(D))}}s(Ob,"overArg");function es(C,U){for(var D=-1,te=C.length,we=0,Ye=[];++D-1}s(oF,"listCacheHas");function aF(o,c){var d=this.__data__,y=Sl(d,o);return y<0?(++this.size,d.push([o,c])):d[y][1]=c,this}s(aF,"listCacheSet"),ci.prototype.clear=nF,ci.prototype.delete=iF,ci.prototype.get=sF,ci.prototype.has=oF,ci.prototype.set=aF;function fi(o){var c=-1,d=o==null?0:o.length;for(this.clear();++c=c?o:c)),o}s(Xs,"baseClamp");function fn(o,c,d,y,S,v){var T,b=c&h,B=c&m,F=c&p;if(d&&(T=S?d(o,y,S,v):d(o)),T!==e)return T;if(!gt(o))return o;var $=ve(o);if($){if(T=l6(o),!b)return Ir(o,T)}else{var z=er(o),Z=z==st||z==Fn;if(as(o))return iA(o,b);if(z==pr||z==lr||Z&&!S){if(T=B||Z?{}:EA(o),!b)return B?e6(o,EF(T,o)):QF(o,Db(T,o))}else{if(!ot[z])return S?o:{};T=h6(o,z,b)}}v||(v=new Bn);var se=v.get(o);if(se)return se;v.set(o,T),ZA(o)?o.forEach(function(pe){T.add(fn(pe,c,d,pe,o,v))}):XA(o)&&o.forEach(function(pe,qe){T.set(qe,fn(pe,c,d,qe,o,v))});var de=F?B?Zg:Jg:B?Rr:Ut,be=$?e:de(o);return an(be||o,function(pe,qe){be&&(qe=pe,pe=o[qe]),Vu(T,qe,fn(pe,c,d,qe,o,v))}),T}s(fn,"baseClone");function TF(o){var c=Ut(o);return function(d){return qb(d,o,c)}}s(TF,"baseConforms");function qb(o,c,d){var y=d.length;if(o==null)return!y;for(o=nt(o);y--;){var S=d[y],v=c[S],T=o[S];if(T===e&&!(S in o)||!v(T))return!1}return!0}s(qb,"baseConformsTo");function Pb(o,c,d){if(typeof o!="function")throw new un(i);return Zu(function(){o.apply(e,d)},c)}s(Pb,"baseDelay");function Yu(o,c,d,y){var S=-1,v=tl,T=!0,b=o.length,B=[],F=c.length;if(!b)return B;d&&(c=dt(c,Hr(d))),y?(v=Sg,T=!1):c.length>=r&&(v=ju,T=!1,c=new Ks(c));e:for(;++SS?0:S+d),y=y===e||y>S?S:Te(y),y<0&&(y+=S),y=d>y?0:eC(y);d0&&d(b)?c>1?$t(b,c-1,d,y,S):Qi(S,b):y||(S[S.length]=b)}return S}s($t,"baseFlatten");var Mg=fA(),jb=fA(!0);function Hn(o,c){return o&&Mg(o,c,Ut)}s(Hn,"baseForOwn");function Dg(o,c){return o&&jb(o,c,Ut)}s(Dg,"baseForOwnRight");function wl(o,c){return Zi(c,function(d){return mi(o[d])})}s(wl,"baseFunctions");function Js(o,c){c=ss(c,o);for(var d=0,y=c.length;o!=null&&dc}s(qg,"baseGt");function AF(o,c){return o!=null&&Je.call(o,c)}s(AF,"baseHas");function CF(o,c){return o!=null&&c in nt(o)}s(CF,"baseHasIn");function IF(o,c,d){return o>=Qt(c,d)&&o=120&&$.length>=120)?new Ks(T&&$):e}$=o[0];var z=-1,Z=b[0];e:for(;++z-1;)b!==o&&ll.call(b,B,1),ll.call(o,B,1);return o}s(Wg,"basePullAll");function Xb(o,c){for(var d=o?c.length:0,y=d-1;d--;){var S=c[d];if(d==y||S!==v){var v=S;pi(S)?ll.call(o,S,1):Hg(o,S)}}return o}s(Xb,"basePullAt");function Fg(o,c){return o+pl(Bb()*(c-o+1))}s(Fg,"baseRandom");function $F(o,c,d,y){for(var S=-1,v=Pt(dl((c-o)/(d||1)),0),T=D(v);v--;)T[y?v:++S]=o,o+=d;return T}s($F,"baseRange");function $g(o,c){var d="";if(!o||c<1||c>oe)return d;do c%2&&(d+=o),c=pl(c/2),c&&(o+=o);while(c);return d}s($g,"baseRepeat");function Ie(o,c){return sy(bA(o,c,xr),o+"")}s(Ie,"baseRest");function zF(o){return Mb(oa(o))}s(zF,"baseSample");function HF(o,c){var d=oa(o);return Rl(d,Xs(c,0,d.length))}s(HF,"baseSampleSize");function Ku(o,c,d,y){if(!gt(o))return o;c=ss(c,o);for(var S=-1,v=c.length,T=v-1,b=o;b!=null&&++SS?0:S+c),d=d>S?S:d,d<0&&(d+=S),S=c>d?0:d-c>>>0,c>>>=0;for(var v=D(S);++y>>1,T=o[v];T!==null&&!Yr(T)&&(d?T<=c:T=r){var F=c?null:i6(o);if(F)return nl(F);T=!1,S=ju,B=new Ks}else B=c?[]:b;e:for(;++y=y?o:ln(o,c,d)}s(os,"castSlice");var nA=q3||function(o){return Lt.clearTimeout(o)};function iA(o,c){if(c)return o.slice();var d=o.length,y=Nb?Nb(d):new o.constructor(d);return o.copy(y),y}s(iA,"cloneBuffer");function Gg(o){var c=new o.constructor(o.byteLength);return new cl(c).set(new cl(o)),c}s(Gg,"cloneArrayBuffer");function KF(o,c){var d=c?Gg(o.buffer):o.buffer;return new o.constructor(d,o.byteOffset,o.byteLength)}s(KF,"cloneDataView");function XF(o){var c=new o.constructor(o.source,FN.exec(o));return c.lastIndex=o.lastIndex,c}s(XF,"cloneRegExp");function JF(o){return Hu?nt(Hu.call(o)):{}}s(JF,"cloneSymbol");function sA(o,c){var d=c?Gg(o.buffer):o.buffer;return new o.constructor(d,o.byteOffset,o.length)}s(sA,"cloneTypedArray");function oA(o,c){if(o!==c){var d=o!==e,y=o===null,S=o===o,v=Yr(o),T=c!==e,b=c===null,B=c===c,F=Yr(c);if(!b&&!F&&!v&&o>c||v&&T&&B&&!b&&!F||y&&T&&B||!d&&B||!S)return 1;if(!y&&!v&&!F&&o=b)return B;var F=d[y];return B*(F=="desc"?-1:1)}}return o.index-c.index}s(ZF,"compareMultiple");function aA(o,c,d,y){for(var S=-1,v=o.length,T=d.length,b=-1,B=c.length,F=Pt(v-T,0),$=D(B+F),z=!y;++b1?d[S-1]:e,T=S>2?d[2]:e;for(v=o.length>3&&typeof v=="function"?(S--,v):e,T&&yr(d[0],d[1],T)&&(v=S<3?e:v,S=1),c=nt(c);++y-1?S[v?c[T]:T]:e}}s(hA,"createFind");function dA(o){return di(function(c){var d=c.length,y=d,S=cn.prototype.thru;for(o&&c.reverse();y--;){var v=c[y];if(typeof v!="function")throw new un(i);if(S&&!T&&Il(v)=="wrapper")var T=new cn([],!0)}for(y=T?y:d;++y1&&je.reverse(),$&&Bb))return!1;var F=v.get(o),$=v.get(c);if(F&&$)return F==c&&$==o;var z=-1,Z=!0,se=d&w?new Ks:e;for(v.set(o,c),v.set(c,o);++z1?"& ":"")+c[y],c=c.join(d>2?", ":" "),o.replace(mW,`{ +/* [wrapped with `+c+`] */ +`)}s(d6,"insertWrapDetails");function p6(o){return ve(o)||eo(o)||!!(Cb&&o&&o[Cb])}s(p6,"isFlattenable");function pi(o,c){var d=typeof o;return c=c??oe,!!c&&(d=="number"||d!="symbol"&&bW.test(o))&&o>-1&&o%1==0&&o0){if(++c>=fe)return arguments[0]}else c=0;return o.apply(e,arguments)}}s(BA,"shortOut");function Rl(o,c){var d=-1,y=o.length,S=y-1;for(c=c===e?y:c;++d1?o[c-1]:e;return d=typeof d=="function"?(o.pop(),d):e,UA(o,d)});function jA(o){var c=_(o);return c.__chain__=!0,c}s(jA,"chain");function N8(o,c){return c(o),o}s(N8,"tap");function xl(o,c){return c(o)}s(xl,"thru");var b8=di(function(o){var c=o.length,d=c?o[0]:0,y=this.__wrapped__,S=s(function(v){return xg(v,o)},"interceptor");return c>1||this.__actions__.length||!(y instanceof Le)||!pi(d)?this.thru(S):(y=y.slice(d,+d+(c?1:0)),y.__actions__.push({func:xl,args:[S],thisArg:e}),new cn(y,this.__chain__).thru(function(v){return c&&!v.length&&v.push(e),v}))});function A8(){return jA(this)}s(A8,"wrapperChain");function C8(){return new cn(this.value(),this.__chain__)}s(C8,"wrapperCommit");function I8(){this.__values__===e&&(this.__values__=QA(this.value()));var o=this.__index__>=this.__values__.length,c=o?e:this.__values__[this.__index__++];return{done:o,value:c}}s(I8,"wrapperNext");function B8(){return this}s(B8,"wrapperToIterator");function R8(o){for(var c,d=this;d instanceof yl;){var y=xA(d);y.__index__=0,y.__values__=e,c?S.__wrapped__=y:c=y;var S=y;d=d.__wrapped__}return S.__wrapped__=o,c}s(R8,"wrapperPlant");function x8(){var o=this.__wrapped__;if(o instanceof Le){var c=o;return this.__actions__.length&&(c=new Le(this)),c=c.reverse(),c.__actions__.push({func:xl,args:[oy],thisArg:e}),new cn(c,this.__chain__)}return this.thru(oy)}s(x8,"wrapperReverse");function M8(){return tA(this.__wrapped__,this.__actions__)}s(M8,"wrapperValue");var D8=Tl(function(o,c,d){Je.call(o,d)?++o[d]:li(o,d,1)});function q8(o,c,d){var y=ve(o)?pb:NF;return d&&yr(o,c,d)&&(c=e),y(o,he(c,3))}s(q8,"every");function P8(o,c){var d=ve(o)?Zi:Ub;return d(o,he(c,3))}s(P8,"filter");var L8=hA(MA),U8=hA(DA);function j8(o,c){return $t(Ml(o,c),1)}s(j8,"flatMap");function W8(o,c){return $t(Ml(o,c),me)}s(W8,"flatMapDeep");function F8(o,c,d){return d=d===e?1:Te(d),$t(Ml(o,c),d)}s(F8,"flatMapDepth");function WA(o,c){var d=ve(o)?an:ns;return d(o,he(c,3))}s(WA,"forEach");function FA(o,c){var d=ve(o)?o3:Lb;return d(o,he(c,3))}s(FA,"forEachRight");var $8=Tl(function(o,c,d){Je.call(o,d)?o[d].push(c):li(o,d,[c])});function z8(o,c,d,y){o=Br(o)?o:oa(o),d=d&&!y?Te(d):0;var S=o.length;return d<0&&(d=Pt(S+d,0)),Ul(o)?d<=S&&o.indexOf(c,d)>-1:!!S&&Ko(o,c,d)>-1}s(z8,"includes");var H8=Ie(function(o,c,d){var y=-1,S=typeof c=="function",v=Br(o)?D(o.length):[];return ns(o,function(T){v[++y]=S?zr(c,T,d):ku(T,c,d)}),v}),V8=Tl(function(o,c,d){li(o,d,c)});function Ml(o,c){var d=ve(o)?dt:Hb;return d(o,he(c,3))}s(Ml,"map");function Y8(o,c,d,y){return o==null?[]:(ve(c)||(c=c==null?[]:[c]),d=y?e:d,ve(d)||(d=d==null?[]:[d]),Gb(o,c,d))}s(Y8,"orderBy");var k8=Tl(function(o,c,d){o[d?0:1].push(c)},function(){return[[],[]]});function G8(o,c,d){var y=ve(o)?_g:Sb,S=arguments.length<3;return y(o,he(c,4),d,S,ns)}s(G8,"reduce");function K8(o,c,d){var y=ve(o)?a3:Sb,S=arguments.length<3;return y(o,he(c,4),d,S,Lb)}s(K8,"reduceRight");function X8(o,c){var d=ve(o)?Zi:Ub;return d(o,Pl(he(c,3)))}s(X8,"reject");function J8(o){var c=ve(o)?Mb:zF;return c(o)}s(J8,"sample");function Z8(o,c,d){(d?yr(o,c,d):c===e)?c=1:c=Te(c);var y=ve(o)?wF:HF;return y(o,c)}s(Z8,"sampleSize");function Q8(o){var c=ve(o)?vF:YF;return c(o)}s(Q8,"shuffle");function e$(o){if(o==null)return 0;if(Br(o))return Ul(o)?Jo(o):o.length;var c=er(o);return c==bt||c==mr?o.size:Ug(o).length}s(e$,"size");function t$(o,c,d){var y=ve(o)?wg:kF;return d&&yr(o,c,d)&&(c=e),y(o,he(c,3))}s(t$,"some");var r$=Ie(function(o,c){if(o==null)return[];var d=c.length;return d>1&&yr(o,c[0],c[1])?c=[]:d>2&&yr(c[0],c[1],c[2])&&(c=[c[0]]),Gb(o,$t(c,1),[])}),Dl=P3||function(){return Lt.Date.now()};function n$(o,c){if(typeof c!="function")throw new un(i);return o=Te(o),function(){if(--o<1)return c.apply(this,arguments)}}s(n$,"after");function $A(o,c,d){return c=d?e:c,c=o&&c==null?o.length:c,hi(o,Y,e,e,e,e,c)}s($A,"ary");function zA(o,c){var d;if(typeof c!="function")throw new un(i);return o=Te(o),function(){return--o>0&&(d=c.apply(this,arguments)),o<=1&&(c=e),d}}s(zA,"before");var uy=Ie(function(o,c,d){var y=O;if(d.length){var S=es(d,ia(uy));y|=I}return hi(o,y,c,d,S)}),HA=Ie(function(o,c,d){var y=O|N;if(d.length){var S=es(d,ia(HA));y|=I}return hi(c,y,o,d,S)});function VA(o,c,d){c=d?e:c;var y=hi(o,M,e,e,e,e,e,c);return y.placeholder=VA.placeholder,y}s(VA,"curry");function YA(o,c,d){c=d?e:c;var y=hi(o,L,e,e,e,e,e,c);return y.placeholder=YA.placeholder,y}s(YA,"curryRight");function kA(o,c,d){var y,S,v,T,b,B,F=0,$=!1,z=!1,Z=!0;if(typeof o!="function")throw new un(i);c=dn(c)||0,gt(d)&&($=!!d.leading,z="maxWait"in d,v=z?Pt(dn(d.maxWait)||0,c):v,Z="trailing"in d?!!d.trailing:Z);function se(Ct){var xn=y,yi=S;return y=S=e,F=Ct,T=o.apply(yi,xn),T}s(se,"invokeFunc");function de(Ct){return F=Ct,b=Zu(qe,c),$?se(Ct):T}s(de,"leadingEdge");function be(Ct){var xn=Ct-B,yi=Ct-F,hC=c-xn;return z?Qt(hC,v-yi):hC}s(be,"remainingWait");function pe(Ct){var xn=Ct-B,yi=Ct-F;return B===e||xn>=c||xn<0||z&&yi>=v}s(pe,"shouldInvoke");function qe(){var Ct=Dl();if(pe(Ct))return je(Ct);b=Zu(qe,be(Ct))}s(qe,"timerExpired");function je(Ct){return b=e,Z&&y?se(Ct):(y=S=e,T)}s(je,"trailingEdge");function kr(){b!==e&&nA(b),F=0,y=B=S=b=e}s(kr,"cancel");function Sr(){return b===e?T:je(Dl())}s(Sr,"flush");function Gr(){var Ct=Dl(),xn=pe(Ct);if(y=arguments,S=this,B=Ct,xn){if(b===e)return de(B);if(z)return nA(b),b=Zu(qe,c),se(B)}return b===e&&(b=Zu(qe,c)),T}return s(Gr,"debounced"),Gr.cancel=kr,Gr.flush=Sr,Gr}s(kA,"debounce");var i$=Ie(function(o,c){return Pb(o,1,c)}),s$=Ie(function(o,c,d){return Pb(o,dn(c)||0,d)});function o$(o){return hi(o,ee)}s(o$,"flip");function ql(o,c){if(typeof o!="function"||c!=null&&typeof c!="function")throw new un(i);var d=s(function(){var y=arguments,S=c?c.apply(this,y):y[0],v=d.cache;if(v.has(S))return v.get(S);var T=o.apply(this,y);return d.cache=v.set(S,T)||v,T},"memoized");return d.cache=new(ql.Cache||fi),d}s(ql,"memoize"),ql.Cache=fi;function Pl(o){if(typeof o!="function")throw new un(i);return function(){var c=arguments;switch(c.length){case 0:return!o.call(this);case 1:return!o.call(this,c[0]);case 2:return!o.call(this,c[0],c[1]);case 3:return!o.call(this,c[0],c[1],c[2])}return!o.apply(this,c)}}s(Pl,"negate");function a$(o){return zA(2,o)}s(a$,"once");var u$=GF(function(o,c){c=c.length==1&&ve(c[0])?dt(c[0],Hr(he())):dt($t(c,1),Hr(he()));var d=c.length;return Ie(function(y){for(var S=-1,v=Qt(y.length,d);++S=c}),eo=Fb(function(){return arguments}())?Fb:function(o){return _t(o)&&Je.call(o,"callee")&&!Ab.call(o,"callee")},ve=D.isArray,E$=ub?Hr(ub):RF;function Br(o){return o!=null&&Ll(o.length)&&!mi(o)}s(Br,"isArrayLike");function At(o){return _t(o)&&Br(o)}s(At,"isArrayLikeObject");function T$(o){return o===!0||o===!1||_t(o)&&gr(o)==sn}s(T$,"isBoolean");var as=U3||wy,N$=cb?Hr(cb):xF;function b$(o){return _t(o)&&o.nodeType===1&&!Qu(o)}s(b$,"isElement");function A$(o){if(o==null)return!0;if(Br(o)&&(ve(o)||typeof o=="string"||typeof o.splice=="function"||as(o)||sa(o)||eo(o)))return!o.length;var c=er(o);if(c==bt||c==mr)return!o.size;if(Ju(o))return!Ug(o).length;for(var d in o)if(Je.call(o,d))return!1;return!0}s(A$,"isEmpty");function C$(o,c){return Gu(o,c)}s(C$,"isEqual");function I$(o,c,d){d=typeof d=="function"?d:e;var y=d?d(o,c):e;return y===e?Gu(o,c,e,d):!!y}s(I$,"isEqualWith");function fy(o){if(!_t(o))return!1;var c=gr(o);return c==Cn||c==Hs||typeof o.message=="string"&&typeof o.name=="string"&&!Qu(o)}s(fy,"isError");function B$(o){return typeof o=="number"&&Ib(o)}s(B$,"isFinite");function mi(o){if(!gt(o))return!1;var c=gr(o);return c==st||c==Fn||c==hr||c==Xf}s(mi,"isFunction");function KA(o){return typeof o=="number"&&o==Te(o)}s(KA,"isInteger");function Ll(o){return typeof o=="number"&&o>-1&&o%1==0&&o<=oe}s(Ll,"isLength");function gt(o){var c=typeof o;return o!=null&&(c=="object"||c=="function")}s(gt,"isObject");function _t(o){return o!=null&&typeof o=="object"}s(_t,"isObjectLike");var XA=fb?Hr(fb):DF;function R$(o,c){return o===c||Lg(o,c,ey(c))}s(R$,"isMatch");function x$(o,c,d){return d=typeof d=="function"?d:e,Lg(o,c,ey(c),d)}s(x$,"isMatchWith");function M$(o){return JA(o)&&o!=+o}s(M$,"isNaN");function D$(o){if(y6(o))throw new we(n);return $b(o)}s(D$,"isNative");function q$(o){return o===null}s(q$,"isNull");function P$(o){return o==null}s(P$,"isNil");function JA(o){return typeof o=="number"||_t(o)&&gr(o)==$n}s(JA,"isNumber");function Qu(o){if(!_t(o)||gr(o)!=pr)return!1;var c=fl(o);if(c===null)return!0;var d=Je.call(c,"constructor")&&c.constructor;return typeof d=="function"&&d instanceof d&&ol.call(d)==x3}s(Qu,"isPlainObject");var ly=lb?Hr(lb):qF;function L$(o){return KA(o)&&o>=-oe&&o<=oe}s(L$,"isSafeInteger");var ZA=hb?Hr(hb):PF;function Ul(o){return typeof o=="string"||!ve(o)&&_t(o)&&gr(o)==Ji}s(Ul,"isString");function Yr(o){return typeof o=="symbol"||_t(o)&&gr(o)==Yo}s(Yr,"isSymbol");var sa=db?Hr(db):LF;function U$(o){return o===e}s(U$,"isUndefined");function j$(o){return _t(o)&&er(o)==zn}s(j$,"isWeakMap");function W$(o){return _t(o)&&gr(o)==Lu}s(W$,"isWeakSet");var F$=Cl(jg),$$=Cl(function(o,c){return o<=c});function QA(o){if(!o)return[];if(Br(o))return Ul(o)?In(o):Ir(o);if(Wu&&o[Wu])return w3(o[Wu]());var c=er(o),d=c==bt?bg:c==mr?nl:oa;return d(o)}s(QA,"toArray");function gi(o){if(!o)return o===0?o:0;if(o=dn(o),o===me||o===-me){var c=o<0?-1:1;return c*ae}return o===o?o:0}s(gi,"toFinite");function Te(o){var c=gi(o),d=c%1;return c===c?d?c-d:c:0}s(Te,"toInteger");function eC(o){return o?Xs(Te(o),0,le):0}s(eC,"toLength");function dn(o){if(typeof o=="number")return o;if(Yr(o))return De;if(gt(o)){var c=typeof o.valueOf=="function"?o.valueOf():o;o=gt(c)?c+"":c}if(typeof o!="string")return o===0?o:+o;o=_b(o);var d=EW.test(o);return d||NW.test(o)?n3(o.slice(2),d?2:8):OW.test(o)?De:+o}s(dn,"toNumber");function tC(o){return Vn(o,Rr(o))}s(tC,"toPlainObject");function z$(o){return o?Xs(Te(o),-oe,oe):o===0?o:0}s(z$,"toSafeInteger");function Xe(o){return o==null?"":Vr(o)}s(Xe,"toString");var H$=ra(function(o,c){if(Ju(c)||Br(c)){Vn(c,Ut(c),o);return}for(var d in c)Je.call(c,d)&&Vu(o,d,c[d])}),rC=ra(function(o,c){Vn(c,Rr(c),o)}),jl=ra(function(o,c,d,y){Vn(c,Rr(c),o,y)}),V$=ra(function(o,c,d,y){Vn(c,Ut(c),o,y)}),Y$=di(xg);function k$(o,c){var d=ta(o);return c==null?d:Db(d,c)}s(k$,"create");var G$=Ie(function(o,c){o=nt(o);var d=-1,y=c.length,S=y>2?c[2]:e;for(S&&yr(c[0],c[1],S)&&(y=1);++d1),v}),Vn(o,Zg(o),d),y&&(d=fn(d,h|m|p,s6));for(var S=c.length;S--;)Hg(d,c[S]);return d});function h4(o,c){return iC(o,Pl(he(c)))}s(h4,"omitBy");var d4=di(function(o,c){return o==null?{}:WF(o,c)});function iC(o,c){if(o==null)return{};var d=dt(Zg(o),function(y){return[y]});return c=he(c),Kb(o,d,function(y,S){return c(y,S[0])})}s(iC,"pickBy");function p4(o,c,d){c=ss(c,o);var y=-1,S=c.length;for(S||(S=1,o=e);++yc){var y=o;o=c,c=y}if(d||o%1||c%1){var S=Bb();return Qt(o+S*(c-o+r3("1e-"+((S+"").length-1))),c)}return Fg(o,c)}s(T4,"random");var N4=na(function(o,c,d){return c=c.toLowerCase(),o+(d?aC(c):c)});function aC(o){return py(Xe(o).toLowerCase())}s(aC,"capitalize");function uC(o){return o=Xe(o),o&&o.replace(AW,m3).replace(YW,"")}s(uC,"deburr");function b4(o,c,d){o=Xe(o),c=Vr(c);var y=o.length;d=d===e?y:Xs(Te(d),0,y);var S=d;return d-=c.length,d>=0&&o.slice(d,S)==c}s(b4,"endsWith");function A4(o){return o=Xe(o),o&&aW.test(o)?o.replace(jN,g3):o}s(A4,"escape");function C4(o){return o=Xe(o),o&&dW.test(o)?o.replace(cg,"\\$&"):o}s(C4,"escapeRegExp");var I4=na(function(o,c,d){return o+(d?"-":"")+c.toLowerCase()}),B4=na(function(o,c,d){return o+(d?" ":"")+c.toLowerCase()}),R4=lA("toLowerCase");function x4(o,c,d){o=Xe(o),c=Te(c);var y=c?Jo(o):0;if(!c||y>=c)return o;var S=(c-y)/2;return Al(pl(S),d)+o+Al(dl(S),d)}s(x4,"pad");function M4(o,c,d){o=Xe(o),c=Te(c);var y=c?Jo(o):0;return c&&y>>0,d?(o=Xe(o),o&&(typeof c=="string"||c!=null&&!ly(c))&&(c=Vr(c),!c&&Xo(o))?os(In(o),0,d):o.split(c,d)):[]}s(j4,"split");var W4=na(function(o,c,d){return o+(d?" ":"")+py(c)});function F4(o,c,d){return o=Xe(o),d=d==null?0:Xs(Te(d),0,o.length),c=Vr(c),o.slice(d,d+c.length)==c}s(F4,"startsWith");function $4(o,c,d){var y=_.templateSettings;d&&yr(o,c,d)&&(c=e),o=Xe(o),c=jl({},c,y,SA);var S=jl({},c.imports,y.imports,SA),v=Ut(S),T=Ng(S,v),b,B,F=0,$=c.interpolate||Zf,z="__p += '",Z=Ag((c.escape||Zf).source+"|"+$.source+"|"+($===WN?vW:Zf).source+"|"+(c.evaluate||Zf).source+"|$","g"),se="//# sourceURL="+(Je.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++JW+"]")+` +`;o.replace(Z,function(pe,qe,je,kr,Sr,Gr){return je||(je=kr),z+=o.slice(F,Gr).replace(CW,y3),qe&&(b=!0,z+=`' + +__e(`+qe+`) + +'`),Sr&&(B=!0,z+=`'; +`+Sr+`; +__p += '`),je&&(z+=`' + +((__t = (`+je+`)) == null ? '' : __t) + +'`),F=Gr+pe.length,pe}),z+=`'; +`;var de=Je.call(c,"variable")&&c.variable;if(!de)z=`with (obj) { +`+z+` +} +`;else if(_W.test(de))throw new we(a);z=(B?z.replace(nW,""):z).replace(iW,"$1").replace(sW,"$1;"),z="function("+(de||"obj")+`) { +`+(de?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(b?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+z+`return __p +}`;var be=fC(function(){return Ye(v,se+"return "+z).apply(e,T)});if(be.source=z,fy(be))throw be;return be}s($4,"template");function z4(o){return Xe(o).toLowerCase()}s(z4,"toLower");function H4(o){return Xe(o).toUpperCase()}s(H4,"toUpper");function V4(o,c,d){if(o=Xe(o),o&&(d||c===e))return _b(o);if(!o||!(c=Vr(c)))return o;var y=In(o),S=In(c),v=wb(y,S),T=vb(y,S)+1;return os(y,v,T).join("")}s(V4,"trim");function Y4(o,c,d){if(o=Xe(o),o&&(d||c===e))return o.slice(0,Eb(o)+1);if(!o||!(c=Vr(c)))return o;var y=In(o),S=vb(y,In(c))+1;return os(y,0,S).join("")}s(Y4,"trimEnd");function k4(o,c,d){if(o=Xe(o),o&&(d||c===e))return o.replace(fg,"");if(!o||!(c=Vr(c)))return o;var y=In(o),S=wb(y,In(c));return os(y,S).join("")}s(k4,"trimStart");function G4(o,c){var d=Ee,y=V;if(gt(c)){var S="separator"in c?c.separator:S;d="length"in c?Te(c.length):d,y="omission"in c?Vr(c.omission):y}o=Xe(o);var v=o.length;if(Xo(o)){var T=In(o);v=T.length}if(d>=v)return o;var b=d-Jo(y);if(b<1)return y;var B=T?os(T,0,b).join(""):o.slice(0,b);if(S===e)return B+y;if(T&&(b+=B.length-b),ly(S)){if(o.slice(b).search(S)){var F,$=B;for(S.global||(S=Ag(S.source,Xe(FN.exec(S))+"g")),S.lastIndex=0;F=S.exec($);)var z=F.index;B=B.slice(0,z===e?b:z)}}else if(o.indexOf(Vr(S),b)!=b){var Z=B.lastIndexOf(S);Z>-1&&(B=B.slice(0,Z))}return B+y}s(G4,"truncate");function K4(o){return o=Xe(o),o&&oW.test(o)?o.replace(UN,T3):o}s(K4,"unescape");var X4=na(function(o,c,d){return o+(d?" ":"")+c.toUpperCase()}),py=lA("toUpperCase");function cC(o,c,d){return o=Xe(o),c=d?e:c,c===e?_3(o)?A3(o):f3(o):o.match(c)||[]}s(cC,"words");var fC=Ie(function(o,c){try{return zr(o,e,c)}catch(d){return fy(d)?d:new we(d)}}),J4=di(function(o,c){return an(c,function(d){d=Yn(d),li(o,d,uy(o[d],o))}),o});function Z4(o){var c=o==null?0:o.length,d=he();return o=c?dt(o,function(y){if(typeof y[1]!="function")throw new un(i);return[d(y[0]),y[1]]}):[],Ie(function(y){for(var S=-1;++Soe)return[];var d=le,y=Qt(o,le);c=he(c),o-=le;for(var S=Tg(y,c);++d0||c<0)?new Le(d):(o<0?d=d.takeRight(-o):o&&(d=d.drop(o)),c!==e&&(c=Te(c),d=c<0?d.dropRight(-c):d.take(c-o)),d)},Le.prototype.takeRightWhile=function(o){return this.reverse().takeWhile(o).reverse()},Le.prototype.toArray=function(){return this.take(le)},Hn(Le.prototype,function(o,c){var d=/^(?:filter|find|map|reject)|While$/.test(c),y=/^(?:head|last)$/.test(c),S=_[y?"take"+(c=="last"?"Right":""):c],v=y||/^find/.test(c);S&&(_.prototype[c]=function(){var T=this.__wrapped__,b=y?[1]:arguments,B=T instanceof Le,F=b[0],$=B||ve(T),z=s(function(qe){var je=S.apply(_,Qi([qe],b));return y&&Z?je[0]:je},"interceptor");$&&d&&typeof F=="function"&&F.length!=1&&(B=$=!1);var Z=this.__chain__,se=!!this.__actions__.length,de=v&&!Z,be=B&&!se;if(!v&&$){T=be?T:new Le(this);var pe=o.apply(T,b);return pe.__actions__.push({func:xl,args:[z],thisArg:e}),new cn(pe,Z)}return de&&be?o.apply(this,b):(pe=this.thru(z),de?y?pe.value()[0]:pe.value():pe)})}),an(["pop","push","shift","sort","splice","unshift"],function(o){var c=il[o],d=/^(?:push|sort|unshift)$/.test(o)?"tap":"thru",y=/^(?:pop|shift)$/.test(o);_.prototype[o]=function(){var S=arguments;if(y&&!this.__chain__){var v=this.value();return c.apply(ve(v)?v:[],S)}return this[d](function(T){return c.apply(ve(T)?T:[],S)})}}),Hn(Le.prototype,function(o,c){var d=_[c];if(d){var y=d.name+"";Je.call(ea,y)||(ea[y]=[]),ea[y].push({name:c,func:d})}}),ea[Nl(e,N).name]=[{name:"wrapper",func:e}],Le.prototype.clone=K3,Le.prototype.reverse=X3,Le.prototype.value=J3,_.prototype.at=b8,_.prototype.chain=A8,_.prototype.commit=C8,_.prototype.next=I8,_.prototype.plant=R8,_.prototype.reverse=x8,_.prototype.toJSON=_.prototype.valueOf=_.prototype.value=M8,_.prototype.first=_.prototype.head,Wu&&(_.prototype[Wu]=B8),_},"runInContext"),ts=C3();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Lt._=ts,define(function(){return ts})):Ys?((Ys.exports=ts)._=ts,gg._=ts):Lt._=ts}).call(aa)});var Wl=E((xpe,tc)=>{"use strict";typeof global.Map<"u"?(tc.exports=global.Map,tc.exports.Map=global.Map):(Kr=s(function(e){this._keys=[],this._values={};for(var t=0;t{function q(e,t){if(!(this instanceof q))return new q(e,t);this._bsontype="Long",this.low_=e|0,this.high_=t|0}s(q,"Long");q.prototype.toInt=function(){return this.low_};q.prototype.toNumber=function(){return this.high_*q.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};q.prototype.toBigInt=function(){return BigInt(this.toString())};q.prototype.toJSON=function(){return this.toString()};q.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:q.TWO_PWR_32_DBL_+this.low_};q.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(q.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=this.high_!==0?this.high_:this.low_,t=31;t>0&&!(e&1<0};q.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};q.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.subtract(e).isNegative()?-1:1};q.prototype.negate=function(){return this.equals(q.MIN_VALUE)?q.MIN_VALUE:this.not().add(q.ONE)};q.prototype.add=function(e){var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,a=e.high_>>>16,u=e.high_&65535,f=e.low_>>>16,l=e.low_&65535,h=0,m=0,p=0,g=0;return g+=i+l,p+=g>>>16,g&=65535,p+=n+f,m+=p>>>16,p&=65535,m+=r+u,h+=m>>>16,m&=65535,h+=t+a,h&=65535,q.fromBits(p<<16|g,h<<16|m)};q.prototype.subtract=function(e){return this.add(e.negate())};q.prototype.multiply=function(e){if(this.isZero())return q.ZERO;if(e.isZero())return q.ZERO;if(this.equals(q.MIN_VALUE))return e.isOdd()?q.MIN_VALUE:q.ZERO;if(e.equals(q.MIN_VALUE))return this.isOdd()?q.MIN_VALUE:q.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(q.TWO_PWR_24_)&&e.lessThan(q.TWO_PWR_24_))return q.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,a=e.high_>>>16,u=e.high_&65535,f=e.low_>>>16,l=e.low_&65535,h=0,m=0,p=0,g=0;return g+=i*l,p+=g>>>16,g&=65535,p+=n*l,m+=p>>>16,p&=65535,p+=i*f,m+=p>>>16,p&=65535,m+=r*l,h+=m>>>16,m&=65535,m+=n*f,h+=m>>>16,m&=65535,m+=i*u,h+=m>>>16,m&=65535,h+=t*l+r*f+n*u+i*a,h&=65535,q.fromBits(p<<16|g,h<<16|m)};q.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return q.ZERO;if(this.equals(q.MIN_VALUE)){if(e.equals(q.ONE)||e.equals(q.NEG_ONE))return q.MIN_VALUE;if(e.equals(q.MIN_VALUE))return q.ONE;var t=this.shiftRight(1),r=t.div(e).shiftLeft(1);if(r.equals(q.ZERO))return e.isNegative()?q.ONE:q.NEG_ONE;var n=this.subtract(e.multiply(r)),i=r.add(n.div(e));return i}else if(e.equals(q.MIN_VALUE))return q.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var a=q.ZERO;for(n=this;n.greaterThanOrEqual(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var u=Math.ceil(Math.log(r)/Math.LN2),f=u<=48?1:Math.pow(2,u-48),l=q.fromNumber(r),h=l.multiply(e);h.isNegative()||h.greaterThan(n);)r-=f,l=q.fromNumber(r),h=l.multiply(e);l.isZero()&&(l=q.ONE),a=a.add(l),n=n.subtract(h)}return a};q.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};q.prototype.not=function(){return q.fromBits(~this.low_,~this.high_)};q.prototype.and=function(e){return q.fromBits(this.low_&e.low_,this.high_&e.high_)};q.prototype.or=function(e){return q.fromBits(this.low_|e.low_,this.high_|e.high_)};q.prototype.xor=function(e){return q.fromBits(this.low_^e.low_,this.high_^e.high_)};q.prototype.shiftLeft=function(e){if(e&=63,e===0)return this;var t=this.low_;if(e<32){var r=this.high_;return q.fromBits(t<>>32-e)}else return q.fromBits(0,t<>>e|t<<32-e,t>>e)}else return q.fromBits(t>>e-32,t>=0?0:-1)};q.prototype.shiftRightUnsigned=function(e){if(e&=63,e===0)return this;var t=this.high_;if(e<32){var r=this.low_;return q.fromBits(r>>>e|t<<32-e,t>>>e)}else return e===32?q.fromBits(t,0):q.fromBits(t>>>e-32,0)};q.fromInt=function(e){if(-128<=e&&e<128){var t=q.INT_CACHE_[e];if(t)return t}var r=new q(e|0,e<0?-1:0);return-128<=e&&e<128&&(q.INT_CACHE_[e]=r),r};q.fromNumber=function(e){return isNaN(e)||!isFinite(e)?q.ZERO:e<=-q.TWO_PWR_63_DBL_?q.MIN_VALUE:e+1>=q.TWO_PWR_63_DBL_?q.MAX_VALUE:e<0?q.fromNumber(-e).negate():new q(e%q.TWO_PWR_32_DBL_|0,e/q.TWO_PWR_32_DBL_|0)};q.fromBigInt=function(e){return q.fromString(e.toString(10),10)};q.fromBits=function(e,t){return new q(e,t)};q.fromString=function(e,t){if(e.length===0)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var n=q.fromNumber(Math.pow(r,8)),i=q.ZERO,a=0;a{function ua(e){if(!(this instanceof ua))return new ua(e);this._bsontype="Double",this.value=e}s(ua,"Double");ua.prototype.valueOf=function(){return this.value};ua.prototype.toJSON=function(){return this.value};Oy.exports=ua;Oy.exports.Double=ua});var nc=E((Upe,Ey)=>{function P(e,t){if(!(this instanceof P))return new P(e,t);this._bsontype="Timestamp",this.low_=e|0,this.high_=t|0}s(P,"Timestamp");P.prototype.toInt=function(){return this.low_};P.prototype.toNumber=function(){return this.high_*P.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};P.prototype.toJSON=function(){return this.toString()};P.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:P.TWO_PWR_32_DBL_+this.low_};P.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(P.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=this.high_!==0?this.high_:this.low_,t=31;t>0&&!(e&1<0};P.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};P.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.subtract(e).isNegative()?-1:1};P.prototype.negate=function(){return this.equals(P.MIN_VALUE)?P.MIN_VALUE:this.not().add(P.ONE)};P.prototype.add=function(e){var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,a=e.high_>>>16,u=e.high_&65535,f=e.low_>>>16,l=e.low_&65535,h=0,m=0,p=0,g=0;return g+=i+l,p+=g>>>16,g&=65535,p+=n+f,m+=p>>>16,p&=65535,m+=r+u,h+=m>>>16,m&=65535,h+=t+a,h&=65535,P.fromBits(p<<16|g,h<<16|m)};P.prototype.subtract=function(e){return this.add(e.negate())};P.prototype.multiply=function(e){if(this.isZero())return P.ZERO;if(e.isZero())return P.ZERO;if(this.equals(P.MIN_VALUE))return e.isOdd()?P.MIN_VALUE:P.ZERO;if(e.equals(P.MIN_VALUE))return this.isOdd()?P.MIN_VALUE:P.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(P.TWO_PWR_24_)&&e.lessThan(P.TWO_PWR_24_))return P.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,a=e.high_>>>16,u=e.high_&65535,f=e.low_>>>16,l=e.low_&65535,h=0,m=0,p=0,g=0;return g+=i*l,p+=g>>>16,g&=65535,p+=n*l,m+=p>>>16,p&=65535,p+=i*f,m+=p>>>16,p&=65535,m+=r*l,h+=m>>>16,m&=65535,m+=n*f,h+=m>>>16,m&=65535,m+=i*u,h+=m>>>16,m&=65535,h+=t*l+r*f+n*u+i*a,h&=65535,P.fromBits(p<<16|g,h<<16|m)};P.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return P.ZERO;if(this.equals(P.MIN_VALUE)){if(e.equals(P.ONE)||e.equals(P.NEG_ONE))return P.MIN_VALUE;if(e.equals(P.MIN_VALUE))return P.ONE;var t=this.shiftRight(1),r=t.div(e).shiftLeft(1);if(r.equals(P.ZERO))return e.isNegative()?P.ONE:P.NEG_ONE;var n=this.subtract(e.multiply(r)),i=r.add(n.div(e));return i}else if(e.equals(P.MIN_VALUE))return P.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var a=P.ZERO;for(n=this;n.greaterThanOrEqual(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var u=Math.ceil(Math.log(r)/Math.LN2),f=u<=48?1:Math.pow(2,u-48),l=P.fromNumber(r),h=l.multiply(e);h.isNegative()||h.greaterThan(n);)r-=f,l=P.fromNumber(r),h=l.multiply(e);l.isZero()&&(l=P.ONE),a=a.add(l),n=n.subtract(h)}return a};P.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};P.prototype.not=function(){return P.fromBits(~this.low_,~this.high_)};P.prototype.and=function(e){return P.fromBits(this.low_&e.low_,this.high_&e.high_)};P.prototype.or=function(e){return P.fromBits(this.low_|e.low_,this.high_|e.high_)};P.prototype.xor=function(e){return P.fromBits(this.low_^e.low_,this.high_^e.high_)};P.prototype.shiftLeft=function(e){if(e&=63,e===0)return this;var t=this.low_;if(e<32){var r=this.high_;return P.fromBits(t<>>32-e)}else return P.fromBits(0,t<>>e|t<<32-e,t>>e)}else return P.fromBits(t>>e-32,t>=0?0:-1)};P.prototype.shiftRightUnsigned=function(e){if(e&=63,e===0)return this;var t=this.high_;if(e<32){var r=this.low_;return P.fromBits(r>>>e|t<<32-e,t>>>e)}else return e===32?P.fromBits(t,0):P.fromBits(t>>>e-32,0)};P.fromInt=function(e){if(-128<=e&&e<128){var t=P.INT_CACHE_[e];if(t)return t}var r=new P(e|0,e<0?-1:0);return-128<=e&&e<128&&(P.INT_CACHE_[e]=r),r};P.fromNumber=function(e){return isNaN(e)||!isFinite(e)?P.ZERO:e<=-P.TWO_PWR_63_DBL_?P.MIN_VALUE:e+1>=P.TWO_PWR_63_DBL_?P.MAX_VALUE:e<0?P.fromNumber(-e).negate():new P(e%P.TWO_PWR_32_DBL_|0,e/P.TWO_PWR_32_DBL_|0)};P.fromBits=function(e,t){return new P(e,t)};P.fromString=function(e,t){if(e.length===0)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var n=P.fromNumber(Math.pow(r,8)),i=P.ZERO,a=0;a{"use strict";function Lz(e){return e.toString().replace(/function *\(/,"function (")}s(Lz,"normalizedFunctionString");function pC(e,t){return new Buffer(e,t)}s(pC,"newBuffer");function Uz(){return Buffer.alloc.apply(Buffer,arguments)}s(Uz,"allocBuffer");function jz(){return Buffer.from.apply(Buffer,arguments)}s(jz,"toBuffer");mC.exports={normalizedFunctionString:Lz,allocBuffer:typeof Buffer.alloc=="function"?Uz:pC,toBuffer:typeof Buffer.from=="function"?jz:pC}});var oc=E(($pe,zl)=>{var yC="inspect",$l=us(),Ty=parseInt(Math.random()*16777215,10),gC=new RegExp("^[0-9a-fA-F]{24}$");try{Buffer&&Buffer.from&&(Fl=!0,yC=require("util").inspect.custom||"inspect")}catch{Fl=!1}var Fl,Fe=s(function e(t){if(t instanceof e)return t;if(!(this instanceof e))return new e(t);if(this._bsontype="ObjectID",t==null||typeof t=="number"){this.id=this.generate(t),e.cacheHexString&&(this.__id=this.toString("hex"));return}var r=e.isValid(t);if(!r&&t!=null)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(r&&typeof t=="string"&&t.length===24&&Fl)return new e($l.toBuffer(t,"hex"));if(r&&typeof t=="string"&&t.length===24)return e.createFromHexString(t);if(t!=null&&t.length===12)this.id=t;else{if(t!=null&&typeof t.toHexString=="function")return t;throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}e.cacheHexString&&(this.__id=this.toString("hex"))},"ObjectID"),SC=[];for(Mr=0;Mr<256;Mr++)SC[Mr]=(Mr<=15?"0":"")+Mr.toString(16);var Mr;Fe.prototype.toHexString=function(){if(Fe.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length)throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]");if(this.id instanceof sc)return e=Wz(this.id),Fe.cacheHexString&&(this.__id=e),e;for(var t=0;t"u"||process.pid===1?Math.floor(Math.random()*1e5):process.pid)%65535,r=this.get_inc(),n=$l.allocBuffer(12);return n[3]=e&255,n[2]=e>>8&255,n[1]=e>>16&255,n[0]=e>>24&255,n[6]=Ty&255,n[5]=Ty>>8&255,n[4]=Ty>>16&255,n[8]=t&255,n[7]=t>>8&255,n[11]=r&255,n[10]=r>>8&255,n[9]=r>>16&255,n};Fe.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString(typeof e=="string"?e:"hex"):this.toHexString()};Fe.prototype[yC]=Fe.prototype.toString;Fe.prototype.toJSON=function(){return this.toHexString()};Fe.prototype.equals=s(function(t){return t instanceof Fe?this.toString()===t.toString():typeof t=="string"&&Fe.isValid(t)&&t.length===12&&this.id instanceof sc?t===this.id.toString("binary"):typeof t=="string"&&Fe.isValid(t)&&t.length===24?t.toLowerCase()===this.toHexString():typeof t=="string"&&Fe.isValid(t)&&t.length===12?t===this.id:t!=null&&(t instanceof Fe||t.toHexString)?t.toHexString()===this.toHexString():!1},"equals");Fe.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(Math.floor(t)*1e3),e};Fe.index=~~(Math.random()*16777215);Fe.createPk=s(function(){return new Fe},"createPk");Fe.createFromTime=s(function(t){var r=$l.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return r[3]=t&255,r[2]=t>>8&255,r[1]=t>>16&255,r[0]=t>>24&255,new Fe(r)},"createFromTime");var ic=[];Mr=0;for(;Mr<10;)ic[48+Mr]=Mr++;for(;Mr<16;)ic[65-10+Mr]=ic[97-10+Mr]=Mr++;var sc=Buffer,Wz=s(function(e){return e.toString("hex")},"convertToHex");Fe.createFromHexString=s(function(t){if(typeof t>"u"||t!=null&&t.length!==24)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(Fl)return new Fe($l.toBuffer(t,"hex"));for(var r=new sc(12),n=0,i=0;i<24;)r[n++]=ic[t.charCodeAt(i++)]<<4|ic[t.charCodeAt(i++)];return new Fe(r)},"createFromHexString");Fe.isValid=s(function(t){return t==null?!1:typeof t=="number"?!0:typeof t=="string"?t.length===12||t.length===24&&gC.test(t):t instanceof Fe||t instanceof sc?!0:typeof t.toHexString=="function"&&(t.id instanceof sc||typeof t.id=="string")?t.id.length===12||t.id.length===24&&gC.test(t.id):!1},"isValid");Object.defineProperty(Fe.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=e&255,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}});zl.exports=Fe;zl.exports.ObjectID=Fe;zl.exports.ObjectId=Fe});var ac=E((Hpe,Ny)=>{function Hl(e,t){if(!(this instanceof Hl))return new Hl;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r{var Fz=Buffer&&require("util").inspect.custom||"inspect";function cs(e){if(!(this instanceof cs))return new cs(e);this._bsontype="Symbol",this.value=e}s(cs,"Symbol");cs.prototype.valueOf=function(){return this.value};cs.prototype.toString=function(){return this.value};cs.prototype[Fz]=function(){return this.value};cs.prototype.toJSON=function(){return this.value};by.exports=cs;by.exports.Symbol=cs});var Vl=E((Gpe,Ay)=>{var ca=s(function(e){if(!(this instanceof ca))return new ca(e);this._bsontype="Int32",this.value=e},"Int32");ca.prototype.valueOf=function(){return this.value};ca.prototype.toJSON=function(){return this.value};Ay.exports=ca;Ay.exports.Int32=ca});var cc=E((Xpe,Iy)=>{var Cy=s(function e(t,r){if(!(this instanceof e))return new e(t,r);this._bsontype="Code",this.code=t,this.scope=r},"Code");Cy.prototype.toJSON=function(){return{scope:this.scope,code:this.code}};Iy.exports=Cy;Iy.exports.Code=Cy});var lc=E((Zpe,Ry)=>{"use strict";var Be=to(),$z=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,zz=/^(\+|-)?(Infinity|inf)$/i,Hz=/^(\+|-)?NaN$/i,fc=6111,Yl=-6176,By=6176,Vz=34,kl=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),Gl=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),Kl=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),Yz=/^([-+])?(\d+)?$/,Si=us(),_C=s(function(e){return!isNaN(parseInt(e,10))},"isDigit"),kz=s(function(e){var t=Be.fromNumber(1e9),r=Be.fromNumber(0),n=0;if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3])return{quotient:e,rem:r};for(n=0;n<=3;n++)r=r.shiftLeft(32),r=r.add(new Be(e.parts[n],0)),e.parts[n]=r.div(t).low_,r=r.modulo(t);return{quotient:e,rem:r}},"divideu128"),Gz=s(function(e,t){if(!e&&!t)return{high:Be.fromNumber(0),low:Be.fromNumber(0)};var r=e.shiftRightUnsigned(32),n=new Be(e.getLowBits(),0),i=t.shiftRightUnsigned(32),a=new Be(t.getLowBits(),0),u=r.multiply(i),f=r.multiply(a),l=n.multiply(i),h=n.multiply(a);return u=u.add(f.shiftRightUnsigned(32)),f=new Be(f.getLowBits(),0).add(l).add(h.shiftRightUnsigned(32)),u=u.add(f.shiftRightUnsigned(32)),h=f.shiftLeft(32).add(new Be(h.getLowBits(),0)),{high:u,low:h}},"multiply64x2"),Kz=s(function(e,t){var r=e.high_>>>0,n=t.high_>>>0;if(r>>0,a=t.low_>>>0;if(i=7e3)throw new Error(""+e+" not a valid Decimal128 string");var R=e.match($z),Y=e.match(zz),W=e.match(Hz);if(!R&&!Y&&!W||e.length===0)throw new Error(""+e+" not a valid Decimal128 string");if(R&&R[4]&&R[2]===void 0)throw new Error(""+e+" not a valid Decimal128 string");if((e[I]==="+"||e[I]==="-")&&(t=e[I++]==="-"),!_C(e[I])&&e[I]!=="."){if(e[I]==="i"||e[I]==="I")return new Dr(Si.toBuffer(t?Gl:Kl));if(e[I]==="N")return new Dr(Si.toBuffer(kl))}for(;_C(e[I])||e[I]===".";){if(e[I]==="."){if(r)return new Dr(Si.toBuffer(kl));r=!0,I=I+1;continue}m<34&&(e[I]!=="0"||n)&&(n||(l=a),n=!0,h[p++]=parseInt(e[I],10),m=m+1),n&&(u=u+1),r&&(f=f+1),a=a+1,I=I+1}if(r&&!a)throw new Error(""+e+" not a valid Decimal128 string");if(e[I]==="e"||e[I]==="E"){var ee=e.substr(++I).match(Yz);if(!ee||!ee[2])return new Dr(Si.toBuffer(kl));O=parseInt(ee[0],10),I=I+ee[0].length}if(e[I])return new Dr(Si.toBuffer(kl));if(g=0,!m)g=0,w=0,h[0]=0,u=1,m=1,i=0;else if(w=m-1,i=u,O!==0&&i!==1)for(;e[l+i-1]==="0";)i=i-1;for(O<=f&&f-O>16384?O=Yl:O=O-f;O>fc;){if(w=w+1,w-g>Vz){var Ee=h.join("");if(Ee.match(/^0+$/)){O=fc;break}else return new Dr(Si.toBuffer(t?Gl:Kl))}O=O-1}for(;O=5&&(ne=1,fe===5)){for(ne=h[w]%2===1,N=l+w+2;N=0&&++h[J]>9;J--)if(h[J]=0,J===0)if(O>8&255,me[I++]=ue.low.low_>>16&255,me[I++]=ue.low.low_>>24&255,me[I++]=ue.low.high_&255,me[I++]=ue.low.high_>>8&255,me[I++]=ue.low.high_>>16&255,me[I++]=ue.low.high_>>24&255,me[I++]=ue.high.low_&255,me[I++]=ue.high.low_>>8&255,me[I++]=ue.high.low_>>16&255,me[I++]=ue.high.low_>>24&255,me[I++]=ue.high.high_&255,me[I++]=ue.high.high_>>8&255,me[I++]=ue.high.high_>>16&255,me[I++]=ue.high.high_>>24&255,new Dr(me)};var Xz=31,wC=16383,Jz=30,Zz=31;By=6176;Dr.prototype.toString=function(){for(var e,t,r,n,i,a,u=0,f=new Array(36),l=0;l>26&Xz,i>>3===3){if(i===Jz)return M.join("")+"Infinity";if(i===Zz)return"NaN";a=e>>15&wC,w=8+(e>>14&1)}else w=e>>14&7,a=e>>17&wC;if(m=a-By,O.parts[0]=(e&16383)+((w&15)<<14),O.parts[1]=t,O.parts[2]=r,O.parts[3]=n,O.parts[0]===0&&O.parts[1]===0&&O.parts[2]===0&&O.parts[3]===0)g=!0;else for(A=3;A>=0;A--){var R=0,Y=kz(O);if(O=Y.quotient,R=Y.rem.low_,!!R)for(N=8;N>=0;N--)f[A*9+N]=R%10,R=Math.floor(R/10)}if(g)u=1,f[h]=0;else for(u=36,l=0;!f[h];)l++,u=u-1,h=h+1;if(p=u-1+m,p>=34||p<=-7||m>0){for(M.push(f[h++]),u=u-1,u&&M.push("."),l=0;l0?M.push("+"+p):M.push(p)}else if(m>=0)for(l=0;l0)for(l=0;l{function Xl(){if(!(this instanceof Xl))return new Xl;this._bsontype="MinKey"}s(Xl,"MinKey");xy.exports=Xl;xy.exports.MinKey=Xl});var dc=E((rme,My)=>{function Jl(){if(!(this instanceof Jl))return new Jl;this._bsontype="MaxKey"}s(Jl,"MaxKey");My.exports=Jl;My.exports.MaxKey=Jl});var mc=E((ime,Dy)=>{function pc(e,t,r){if(!(this instanceof pc))return new pc(e,t,r);this._bsontype="DBRef",this.namespace=e,this.oid=t,this.db=r}s(pc,"DBRef");pc.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:this.db==null?"":this.db}};Dy.exports=pc;Dy.exports.DBRef=pc});var fa=E((ome,qy)=>{typeof global<"u"&&(zt=require("buffer").Buffer);var zt,Zl=us();function lt(e,t){if(!(this instanceof lt))return new lt(e,t);if(e!=null&&typeof e!="string"&&!zt.isBuffer(e)&&!(e instanceof Uint8Array)&&!Array.isArray(e))throw new Error("only String, Buffer, Uint8Array or Array accepted");if(this._bsontype="Binary",e instanceof Number?(this.sub_type=e,this.position=0):(this.sub_type=t??Qz,this.position=0),e!=null&&!(e instanceof Number)){if(typeof e=="string")if(typeof zt<"u")this.buffer=Zl.toBuffer(e);else if(typeof Uint8Array<"u"||Object.prototype.toString.call(e)==="[object Array]")this.buffer=eH(e);else throw new Error("only String, Buffer, Uint8Array or Array accepted");else this.buffer=e;this.position=e.length}else typeof zt<"u"?this.buffer=Zl.allocBuffer(lt.BUFFER_SIZE):typeof Uint8Array<"u"?this.buffer=new Uint8Array(new ArrayBuffer(lt.BUFFER_SIZE)):this.buffer=new Array(lt.BUFFER_SIZE),this.position=0}s(lt,"Binary");lt.prototype.put=s(function(t){if(t.length!=null&&typeof t!="number"&&t.length!==1)throw new Error("only accepts single character String, Uint8Array or Array");if(typeof t!="number"&&t<0||t>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var r=null;if(typeof t=="string"?r=t.charCodeAt(0):t.length!=null?r=t[0]:r=t,this.buffer.length>this.position)this.buffer[this.position++]=r;else if(typeof zt<"u"&&zt.isBuffer(this.buffer)){var n=Zl.allocBuffer(lt.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=r}else{n=null,Object.prototype.toString.call(this.buffer)==="[object Uint8Array]"?n=new Uint8Array(new ArrayBuffer(lt.BUFFER_SIZE+this.buffer.length)):n=new Array(lt.BUFFER_SIZE+this.buffer.length);for(var i=0;ithis.position?r+t.length:this.position;else if(typeof zt<"u"&&typeof t=="string"&&zt.isBuffer(this.buffer))this.buffer.write(t,r,"binary"),this.position=r+t.length>this.position?r+t.length:this.position;else if(Object.prototype.toString.call(t)==="[object Uint8Array]"||Object.prototype.toString.call(t)==="[object Array]"&&typeof t!="string"){for(i=0;ithis.position?r:this.position}else if(typeof t=="string"){for(i=0;ithis.position?r:this.position}},"write");lt.prototype.read=s(function(t,r){if(r=r&&r>0?r:this.position,this.buffer.slice)return this.buffer.slice(t,t+r);for(var n=typeof Uint8Array<"u"?new Uint8Array(new ArrayBuffer(r)):new Array(r),i=0;i{"use strict";var Long=to().Long,Double=rc().Double,Timestamp=nc().Timestamp,ObjectID=oc().ObjectID,Symbol=uc().Symbol,Code=cc().Code,MinKey=hc().MinKey,MaxKey=dc().MaxKey,Decimal128=lc(),Int32=Vl(),DBRef=mc().DBRef,BSONRegExp=ac().BSONRegExp,Binary=fa().Binary,utils=us(),deserialize=s(function(e,t,r){t=t??{};var n=t&&t.index?t.index:0,i=e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24;if(i<5||e.lengthe.length)throw new Error("corrupt bson message");if(e[n+i-1]!==0)throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,n,t,r)},"deserialize"),deserializeObject=s(function(e,t,r,n){var i=r.evalFunctions==null?!1:r.evalFunctions,a=r.cacheFunctions==null?!1:r.cacheFunctions,u=r.cacheFunctionsCrc32==null?!1:r.cacheFunctionsCrc32;if(!u)var f=null;var l=r.fieldsAsRaw==null?null:r.fieldsAsRaw,h=r.raw==null?!1:r.raw,m=typeof r.bsonRegExp=="boolean"?r.bsonRegExp:!1,p=r.promoteBuffers==null?!1:r.promoteBuffers,g=r.promoteLongs==null?!0:r.promoteLongs,w=r.promoteValues==null?!0:r.promoteValues,O=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var N=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(N<5||N>e.length)throw new Error("corrupt bson message");for(var A=n?[]:{},M=0,L=!1;!L;){var I=e[t++];if(I===0)break;for(var R=t;e[R]!==0&&R=e.length)throw new Error("Bad BSON Document: illegal CString");var Y=n?M++:e.toString("utf8",t,R);if(t=R+1,I===BSON.BSON_DATA_STRING){var W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(W<=0||W>e.length-t||e[t+W-1]!==0)throw new Error("bad string length in bson");A[Y]=e.toString("utf8",t,t+W-1),t=t+W}else if(I===BSON.BSON_DATA_OID){var ee=utils.allocBuffer(12);e.copy(ee,0,t,t+12),A[Y]=new ObjectID(ee),t=t+12}else if(I===BSON.BSON_DATA_INT&&w===!1)A[Y]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(I===BSON.BSON_DATA_INT)A[Y]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(I===BSON.BSON_DATA_NUMBER&&w===!1)A[Y]=new Double(e.readDoubleLE(t)),t=t+8;else if(I===BSON.BSON_DATA_NUMBER)A[Y]=e.readDoubleLE(t),t=t+8;else if(I===BSON.BSON_DATA_DATE){var Ee=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,V=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;A[Y]=new Date(new Long(Ee,V).toNumber())}else if(I===BSON.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new Error("illegal boolean type value");A[Y]=e[t++]===1}else if(I===BSON.BSON_DATA_OBJECT){var fe=t,ne=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(ne<=0||ne>e.length-t)throw new Error("bad embedded document length in bson");h?A[Y]=e.slice(t,t+ne):A[Y]=deserializeObject(e,fe,r,!1),t=t+ne}else if(I===BSON.BSON_DATA_ARRAY){fe=t,ne=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var J=r,K=t+ne;if(l&&l[Y]){J={};for(var ue in r)J[ue]=r[ue];J.raw=!0}if(A[Y]=deserializeObject(e,fe,J,!0),t=t+ne,e[t-1]!==0)throw new Error("invalid array terminator byte");if(t!==K)throw new Error("corrupted array bson")}else if(I===BSON.BSON_DATA_UNDEFINED)A[Y]=void 0;else if(I===BSON.BSON_DATA_NULL)A[Y]=null;else if(I===BSON.BSON_DATA_LONG){Ee=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,V=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var me=new Long(Ee,V);g&&w===!0?A[Y]=me.lessThanOrEqual(JS_INT_MAX_LONG)&&me.greaterThanOrEqual(JS_INT_MIN_LONG)?me.toNumber():me:A[Y]=me}else if(I===BSON.BSON_DATA_DECIMAL128){var oe=utils.allocBuffer(16);e.copy(oe,0,t,t+16),t=t+16;var ae=new Decimal128(oe);A[Y]=ae.toObject?ae.toObject():ae}else if(I===BSON.BSON_DATA_BINARY){var De=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,le=De,Ke=e[t++];if(De<0)throw new Error("Negative binary type element size found");if(De>e.length)throw new Error("Binary type size larger than document size");if(e.slice!=null){if(Ke===Binary.SUBTYPE_BYTE_ARRAY){if(De=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,De<0)throw new Error("Negative binary type element size found for subtype 0x02");if(De>le-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(Dele-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(De=e.length)throw new Error("Bad BSON Document: illegal CString");var Ft=e.toString("utf8",t,R);for(t=R+1,R=t;e[R]!==0&&R=e.length)throw new Error("Bad BSON Document: illegal CString");var lr=e.toString("utf8",t,R);t=R+1;var Zt=new Array(lr.length);for(R=0;R=e.length)throw new Error("Bad BSON Document: illegal CString");for(Ft=e.toString("utf8",t,R),t=R+1,R=t;e[R]!==0&&R=e.length)throw new Error("Bad BSON Document: illegal CString");lr=e.toString("utf8",t,R),t=R+1,A[Y]=new BSONRegExp(Ft,lr)}else if(I===BSON.BSON_DATA_SYMBOL){if(W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,W<=0||W>e.length-t||e[t+W-1]!==0)throw new Error("bad string length in bson");A[Y]=new Symbol(e.toString("utf8",t,t+W-1)),t=t+W}else if(I===BSON.BSON_DATA_TIMESTAMP)Ee=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,V=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,A[Y]=new Timestamp(Ee,V);else if(I===BSON.BSON_DATA_MIN_KEY)A[Y]=new MinKey;else if(I===BSON.BSON_DATA_MAX_KEY)A[Y]=new MaxKey;else if(I===BSON.BSON_DATA_CODE){if(W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,W<=0||W>e.length-t||e[t+W-1]!==0)throw new Error("bad string length in bson");var hr=e.toString("utf8",t,t+W-1);if(i)if(a){var sn=u?f(hr):hr;A[Y]=isolateEvalWithHash(functionCache,sn,hr,A)}else A[Y]=isolateEval(hr);else A[Y]=new Code(hr);t=t+W}else if(I===BSON.BSON_DATA_CODE_W_SCOPE){var dr=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(dr<4+4+4+1)throw new Error("code_w_scope total size shorter minimum expected length");if(W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,W<=0||W>e.length-t||e[t+W-1]!==0)throw new Error("bad string length in bson");hr=e.toString("utf8",t,t+W-1),t=t+W,fe=t,ne=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var Hs=deserializeObject(e,fe,r,!1);if(t=t+ne,dr<4+4+ne+W)throw new Error("code_w_scope total size is to short, truncating scope");if(dr>4+4+ne+W)throw new Error("code_w_scope total size is to long, clips outer document");i?(a?(sn=u?f(hr):hr,A[Y]=isolateEvalWithHash(functionCache,sn,hr,A)):A[Y]=isolateEval(hr),A[Y].scope=Hs):A[Y]=new Code(hr,Hs)}else if(I===BSON.BSON_DATA_DBPOINTER){if(W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,W<=0||W>e.length-t||e[t+W-1]!==0)throw new Error("bad string length in bson");var Cn=e.toString("utf8",t,t+W-1);t=t+W;var st=utils.allocBuffer(12);e.copy(st,0,t,t+12),ee=new ObjectID(st),t=t+12;var Fn=Cn.split("."),bt=Fn.shift(),$n=Fn.join(".");A[Y]=new DBRef($n,ee,bt)}else throw new Error("Detected unknown BSON type "+I.toString(16)+' for fieldname "'+Y+'", are you using the latest BSON parser')}if(N!==t-O)throw n?new Error("corrupt array bson"):new Error("corrupt object bson");return A.$id!=null&&(A=new DBRef(A.$ref,A.$id,A.$db)),A},"deserializeObject"),isolateEvalWithHash=s(function(functionCache,hash,functionString,object){var value=null;return functionCache[hash]==null&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},"isolateEvalWithHash"),isolateEval=s(function(functionString){var value=null;return eval("value = "+functionString),value},"isolateEval"),BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1;BSON.BSON_DATA_STRING=2;BSON.BSON_DATA_OBJECT=3;BSON.BSON_DATA_ARRAY=4;BSON.BSON_DATA_BINARY=5;BSON.BSON_DATA_UNDEFINED=6;BSON.BSON_DATA_OID=7;BSON.BSON_DATA_BOOLEAN=8;BSON.BSON_DATA_DATE=9;BSON.BSON_DATA_NULL=10;BSON.BSON_DATA_REGEXP=11;BSON.BSON_DATA_DBPOINTER=12;BSON.BSON_DATA_CODE=13;BSON.BSON_DATA_SYMBOL=14;BSON.BSON_DATA_CODE_W_SCOPE=15;BSON.BSON_DATA_INT=16;BSON.BSON_DATA_TIMESTAMP=17;BSON.BSON_DATA_LONG=18;BSON.BSON_DATA_DECIMAL128=19;BSON.BSON_DATA_MIN_KEY=255;BSON.BSON_DATA_MAX_KEY=127;BSON.BSON_BINARY_SUBTYPE_DEFAULT=0;BSON.BSON_BINARY_SUBTYPE_FUNCTION=1;BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;BSON.BSON_BINARY_SUBTYPE_UUID=3;BSON.BSON_BINARY_SUBTYPE_MD5=4;BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128;BSON.BSON_INT32_MAX=2147483647;BSON.BSON_INT32_MIN=-2147483648;BSON.BSON_INT64_MAX=Math.pow(2,63)-1;BSON.BSON_INT64_MIN=-Math.pow(2,63);BSON.JS_INT_MAX=9007199254740992;BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize});var OC=E(Py=>{var rH=s(function(e,t,r,n,i){var a,u,f=r==="big",l=i*8-n-1,h=(1<>1,p=-7,g=f?0:i-1,w=f?1:-1,O=e[t+g];for(g+=w,a=O&(1<<-p)-1,O>>=-p,p+=l;p>0;a=a*256+e[t+g],g+=w,p-=8);for(u=a&(1<<-p)-1,a>>=-p,p+=n;p>0;u=u*256+e[t+g],g+=w,p-=8);if(a===0)a=1-m;else{if(a===h)return u?NaN:(O?-1:1)*(1/0);u=u+Math.pow(2,n),a=a-m}return(O?-1:1)*u*Math.pow(2,a-n)},"readIEEE754"),nH=s(function(e,t,r,n,i,a){var u,f,l,h=n==="big",m=a*8-i-1,p=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=h?a-1:0,N=h?-1:1,A=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(f=isNaN(t)?1:0,u=p):(u=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-u))<1&&(u--,l*=2),u+g>=1?t+=w/l:t+=w*Math.pow(2,1-g),t*l>=2&&(u++,l/=2),u+g>=p?(f=0,u=p):u+g>=1?(f=(t*l-1)*Math.pow(2,i),u=u+g):(f=t*Math.pow(2,g-1)*Math.pow(2,i),u=0));i>=8;e[r+O]=f&255,O+=N,f/=256,i-=8);for(u=u<0;e[r+O]=u&255,O+=N,u/=256,m-=8);e[r+O-N]|=A*128},"writeIEEE754");Py.readIEEE754=rH;Py.writeIEEE754=nH});var AC=E((lme,bC)=>{"use strict";var iS=OC().writeIEEE754,NC=to().Long,iH=Wl(),EC=fa().Binary,sH=us().normalizedFunctionString,Ql=/\x00/,TC=["$db","$ref","$id","$clusterTime"],Ly=s(function(t){return typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"},"isDate"),Uy=s(function(t){return Object.prototype.toString.call(t)==="[object RegExp]"},"isRegExp"),jy=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_STRING;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+a+1,e[n-1]=0;var u=e.write(r,n+4,"utf8");return e[n+3]=u+1>>24&255,e[n+2]=u+1>>16&255,e[n+1]=u+1>>8&255,e[n]=u+1&255,n=n+4+u,e[n++]=0,n},"serializeString"),Wy=s(function(e,t,r,n,i){if(Math.floor(r)===r&&r>=re.JS_INT_MIN&&r<=re.JS_INT_MAX)if(r>=re.BSON_INT32_MIN&&r<=re.BSON_INT32_MAX){e[n++]=re.BSON_DATA_INT;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+a,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255}else if(r>=re.JS_INT_MIN&&r<=re.JS_INT_MAX)e[n++]=re.BSON_DATA_NUMBER,a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+a,e[n++]=0,iS(e,r,n,"little",52,8),n=n+8;else{e[n++]=re.BSON_DATA_LONG,a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+a,e[n++]=0;var u=NC.fromNumber(r),f=u.getLowBits(),l=u.getHighBits();e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255,e[n++]=l&255,e[n++]=l>>8&255,e[n++]=l>>16&255,e[n++]=l>>24&255}else e[n++]=re.BSON_DATA_NUMBER,a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+a,e[n++]=0,iS(e,r,n,"little",52,8),n=n+8;return n},"serializeNumber"),gc=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_NULL;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+a,e[n++]=0,n},"serializeNull"),Fy=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_BOOLEAN;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+a,e[n++]=0,e[n++]=r?1:0,n},"serializeBoolean"),$y=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_DATE;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+a,e[n++]=0;var u=NC.fromNumber(r.getTime()),f=u.getLowBits(),l=u.getHighBits();return e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255,e[n++]=l&255,e[n++]=l>>8&255,e[n++]=l>>16&255,e[n++]=l>>24&255,n},"serializeDate"),zy=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_REGEXP;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");if(n=n+a,e[n++]=0,r.source&&r.source.match(Ql)!=null)throw Error("value "+r.source+" must not contain null bytes");return n=n+e.write(r.source,n,"utf8"),e[n++]=0,r.global&&(e[n++]=115),r.ignoreCase&&(e[n++]=105),r.multiline&&(e[n++]=109),e[n++]=0,n},"serializeRegExp"),Hy=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_REGEXP;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");if(n=n+a,e[n++]=0,r.pattern.match(Ql)!=null)throw Error("pattern "+r.pattern+" must not contain null bytes");return n=n+e.write(r.pattern,n,"utf8"),e[n++]=0,n=n+e.write(r.options.split("").sort().join(""),n,"utf8"),e[n++]=0,n},"serializeBSONRegExp"),Vy=s(function(e,t,r,n,i){r===null?e[n++]=re.BSON_DATA_NULL:r._bsontype==="MinKey"?e[n++]=re.BSON_DATA_MIN_KEY:e[n++]=re.BSON_DATA_MAX_KEY;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+a,e[n++]=0,n},"serializeMinMax"),Yy=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_OID;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");if(n=n+a,e[n++]=0,typeof r.id=="string")e.write(r.id,n,"binary");else if(r.id&&r.id.copy)r.id.copy(e,n,0,12);else throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId");return n+12},"serializeObjectId"),ky=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_BINARY;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+a,e[n++]=0;var u=r.length;return e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=re.BSON_BINARY_SUBTYPE_DEFAULT,r.copy(e,n,0,u),n=n+u,n},"serializeBuffer"),Gy=s(function(e,t,r,n,i,a,u,f,l,h){for(var m=0;m>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255,n},"serializeLong"),Jy=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_INT;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+a,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255,n},"serializeInt32"),Zy=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_NUMBER;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+a,e[n++]=0,iS(e,r,n,"little",52,8),n=n+8,n},"serializeDouble"),Qy=s(function(e,t,r,n,i,a,u){e[n++]=re.BSON_DATA_CODE;var f=u?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+f,e[n++]=0;var l=sH(r),h=e.write(l,n+4,"utf8")+1;return e[n]=h&255,e[n+1]=h>>8&255,e[n+2]=h>>16&255,e[n+3]=h>>24&255,n=n+4+h-1,e[n++]=0,n},"serializeFunction"),eS=s(function(e,t,r,n,i,a,u,f,l){if(r.scope&&typeof r.scope=="object"){e[n++]=re.BSON_DATA_CODE_W_SCOPE;var h=l?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+h,e[n++]=0;var m=n,p=typeof r.code=="string"?r.code:r.code.toString();n=n+4;var g=e.write(p,n+4,"utf8")+1;e[n]=g&255,e[n+1]=g>>8&255,e[n+2]=g>>16&255,e[n+3]=g>>24&255,e[n+4+g-1]=0,n=n+g+4;var w=yc(e,r.scope,i,n,a+1,u,f);n=w-1;var O=w-m;e[m++]=O&255,e[m++]=O>>8&255,e[m++]=O>>16&255,e[m++]=O>>24&255,e[n++]=0}else{e[n++]=re.BSON_DATA_CODE,h=l?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+h,e[n++]=0,p=r.code.toString();var N=e.write(p,n+4,"utf8")+1;e[n]=N&255,e[n+1]=N>>8&255,e[n+2]=N>>16&255,e[n+3]=N>>24&255,n=n+4+N-1,e[n++]=0}return n},"serializeCode"),tS=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_BINARY;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+a,e[n++]=0;var u=r.value(!0),f=r.position;return r.sub_type===EC.SUBTYPE_BYTE_ARRAY&&(f=f+4),e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255,e[n++]=r.sub_type,r.sub_type===EC.SUBTYPE_BYTE_ARRAY&&(f=f-4,e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255),u.copy(e,n,0,r.position),n=n+r.position,n},"serializeBinary"),rS=s(function(e,t,r,n,i){e[n++]=re.BSON_DATA_SYMBOL;var a=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+a,e[n++]=0;var u=e.write(r.value,n+4,"utf8")+1;return e[n]=u&255,e[n+1]=u>>8&255,e[n+2]=u>>16&255,e[n+3]=u>>24&255,n=n+4+u-1,e[n++]=0,n},"serializeSymbol"),nS=s(function(e,t,r,n,i,a,u){e[n++]=re.BSON_DATA_OBJECT;var f=u?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+f,e[n++]=0;var l=n,h;r.db!=null?h=yc(e,{$ref:r.namespace,$id:r.oid,$db:r.db},!1,n,i+1,a):h=yc(e,{$ref:r.namespace,$id:r.oid},!1,n,i+1,a);var m=h-l;return e[l++]=m&255,e[l++]=m>>8&255,e[l++]=m>>16&255,e[l++]=m>>24&255,h},"serializeDBRef"),yc=s(function(t,r,n,i,a,u,f,l){i=i||0,l=l||[],l.push(r);var h=i+4;if(Array.isArray(r))for(var m=0;m>8&255,t[i++]=M>>16&255,t[i++]=M>>24&255,h},"serializeInto"),re={};re.BSON_DATA_NUMBER=1;re.BSON_DATA_STRING=2;re.BSON_DATA_OBJECT=3;re.BSON_DATA_ARRAY=4;re.BSON_DATA_BINARY=5;re.BSON_DATA_UNDEFINED=6;re.BSON_DATA_OID=7;re.BSON_DATA_BOOLEAN=8;re.BSON_DATA_DATE=9;re.BSON_DATA_NULL=10;re.BSON_DATA_REGEXP=11;re.BSON_DATA_CODE=13;re.BSON_DATA_SYMBOL=14;re.BSON_DATA_CODE_W_SCOPE=15;re.BSON_DATA_INT=16;re.BSON_DATA_TIMESTAMP=17;re.BSON_DATA_LONG=18;re.BSON_DATA_DECIMAL128=19;re.BSON_DATA_MIN_KEY=255;re.BSON_DATA_MAX_KEY=127;re.BSON_BINARY_SUBTYPE_DEFAULT=0;re.BSON_BINARY_SUBTYPE_FUNCTION=1;re.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;re.BSON_BINARY_SUBTYPE_UUID=3;re.BSON_BINARY_SUBTYPE_MD5=4;re.BSON_BINARY_SUBTYPE_USER_DEFINED=128;re.BSON_INT32_MAX=2147483647;re.BSON_INT32_MIN=-2147483648;re.BSON_INT64_MAX=Math.pow(2,63)-1;re.BSON_INT64_MIN=-Math.pow(2,63);re.JS_INT_MAX=9007199254740992;re.JS_INT_MIN=-9007199254740992;bC.exports=yc});var xC=E((dme,RC)=>{"use strict";var oH=to().Long,aH=rc().Double,uH=nc().Timestamp,cH=oc().ObjectID,fH=uc().Symbol,lH=ac().BSONRegExp,hH=cc().Code,dH=lc(),pH=hc().MinKey,mH=dc().MaxKey,gH=mc().DBRef,CC=fa().Binary,IC=us().normalizedFunctionString,yH=s(function(t){return typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"},"isDate"),Sc=s(function(t,r,n){var i=5;if(Array.isArray(t))for(var a=0;a=fs.JS_INT_MIN&&t<=fs.JS_INT_MAX&&t>=fs.BSON_INT32_MIN&&t<=fs.BSON_INT32_MAX?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(4+1):(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1);case"undefined":return n||!i?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t instanceof pH||t instanceof mH||t._bsontype==="MinKey"||t._bsontype==="MaxKey")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof cH||t._bsontype==="ObjectID"||t._bsontype==="ObjectId")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(12+1);if(t instanceof Date||yH(t))return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(typeof Buffer<"u"&&Buffer.isBuffer(t))return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.length;if(t instanceof oH||t instanceof aH||t instanceof uH||t._bsontype==="Long"||t._bsontype==="Double"||t._bsontype==="Timestamp")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(t instanceof dH||t._bsontype==="Decimal128")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(16+1);if(t instanceof hH||t._bsontype==="Code")return t.scope!=null&&Object.keys(t.scope).length>0?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+Sc(t.scope,r,i):(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof CC||t._bsontype==="Binary")return t.sub_type===CC.SUBTYPE_BYTE_ARRAY?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof fH||t._bsontype==="Symbol")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof gH||t._bsontype==="DBRef"){var a={$ref:t.namespace,$id:t.oid};return t.db!=null&&(a.$db=t.db),(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Sc(a,r,i)}else return t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof lH||t._bsontype==="BSONRegExp"?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Sc(t,r,i)+1;case"function":if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"||String.call(t)==="[object RegExp]")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(r&&t.scope!=null&&Object.keys(t.scope).length>0)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(IC(t),"utf8")+1+Sc(t.scope,r,i);if(r)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(IC(t),"utf8")+1}return 0}s(BC,"calculateElement");var fs={};fs.BSON_INT32_MAX=2147483647;fs.BSON_INT32_MIN=-2147483648;fs.JS_INT_MAX=9007199254740992;fs.JS_INT_MIN=-9007199254740992;RC.exports=Sc});var qC=E((mme,Ht)=>{"use strict";var SH=Wl(),_H=to(),wH=rc(),vH=nc(),OH=oc(),EH=ac(),TH=uc(),NH=Vl(),bH=cc(),AH=lc(),CH=hc(),IH=dc(),BH=mc(),RH=fa(),xH=vC(),MC=AC(),MH=xC(),sS=us(),DC=1024*1024*17,eh=sS.allocBuffer(DC),Pe=s(function(){},"BSON");Pe.prototype.serialize=s(function(t,r){r=r||{};var n=typeof r.checkKeys=="boolean"?r.checkKeys:!1,i=typeof r.serializeFunctions=="boolean"?r.serializeFunctions:!1,a=typeof r.ignoreUndefined=="boolean"?r.ignoreUndefined:!0,u=typeof r.minInternalBufferSize=="number"?r.minInternalBufferSize:DC;eh.length{var wt=qC(),DH=fa(),qH=cc(),PH=mc(),LH=lc(),UH=rc(),jH=Vl(),WH=to(),FH=Wl(),$H=dc(),zH=hc(),PC=oc(),HH=ac(),VH=uc(),YH=nc();wt.BSON_INT32_MAX=2147483647;wt.BSON_INT32_MIN=-2147483648;wt.BSON_INT64_MAX=Math.pow(2,63)-1;wt.BSON_INT64_MIN=-Math.pow(2,63);wt.JS_INT_MAX=9007199254740992;wt.JS_INT_MIN=-9007199254740992;wt.Binary=DH;wt.Code=qH;wt.DBRef=PH;wt.Decimal128=LH;wt.Double=UH;wt.Int32=jH;wt.Long=WH;wt.Map=FH;wt.MaxKey=$H;wt.MinKey=zH;wt.ObjectId=PC;wt.ObjectID=PC;wt.BSONRegExp=HH;wt.Symbol=VH;wt.Timestamp=YH;LC.exports=wt});var UC=E((exports,module)=>{"use strict";var Module=require("module"),xrequire=eval("require"),createRequireFromPath=Module.createRequire||Module.createRequireFromPath||((e,t)=>{let r=new Module(e);r.filename=e,r.paths=Module._nodeModulePaths(t);function n(u){return xrequire(i(u))}s(n,"_require");function i(u,f){return Module._resolveFilename(u,r,!1,f)}s(i,"resolve"),n.resolve=i;function a(u){return Module._resolveLookupPaths(u,r,!0)}return s(a,"paths"),i.paths=a,n.main=process.mainModule,n.extensions=Module._extensions,n.cache=Module._cache,n});module.exports=createRequireFromPath});var WC=E((_me,jC)=>{"use strict";var oS=require("path"),kH=require("fs"),GH=UC(),KH=new Map;function la(e,t){let r=s((n,i)=>{let a=la.cache&&la.cache.get(n);if(!a){let u;try{u=kH.statSync(n)}catch(f){throw new Error(`require-at: stat '${n}' failed: ${f.message}`)}if(!u||!u.isDirectory()){if(i)throw new Error(`require-at: not a directory: '${e}'`);return r(oS.dirname(n),!0)}a=GH(oS.join(n,"._require-at_"),n),la.cache&&la.cache.set(n,a)}return t?a(t):a},"makeIt");return r(oS.resolve(e),!1)}s(la,"requireAt");la.cache=KH;jC.exports=la});var FC=E((exports,module)=>{"use strict";var __assign=exports&&exports.__assign||function(){return __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{"use strict";var Mn=FC();Dn.exports=function(){return Mn.makeOptionalRequire.apply(Mn,arguments)};Dn.exports.tryRequire=Mn.tryRequire;Dn.exports.tryResolve=Mn.tryResolve;Dn.exports.try=Mn.tryRequire;Dn.exports.resolve=Mn.tryResolve;Dn.exports.makeOptionalRequire=Mn.makeOptionalRequire;Dn.exports.optionalRequire=Mn.optionalRequire;Dn.exports.optionalRequireCwd=Mn.optionalRequireCwd;Dn.exports.optionalRequireTop=Mn.optionalRequireTop;var $C;Object.defineProperty(Dn.exports,"log",{set(e){$C=e,Mn.setDefaultLog(e)},get(){return $C}})});var zC=E((Eme,XH)=>{XH.exports={name:"mongodb",version:"3.7.4",description:"The official MongoDB driver for Node.js",main:"index.js",files:["index.js","lib"],repository:{type:"git",url:"git@github.com:mongodb/node-mongodb-native.git"},keywords:["mongodb","driver","official"],author:{name:"The MongoDB NodeJS Team",email:"dbx-node@mongodb.com"},peerDependenciesMeta:{kerberos:{optional:!0},"mongodb-client-encryption":{optional:!0},"mongodb-extjson":{optional:!0},snappy:{optional:!0},"bson-ext":{optional:!0},aws4:{optional:!0}},dependencies:{bl:"^2.2.1",bson:"^1.1.4",denque:"^1.4.1","optional-require":"^1.1.8","safe-buffer":"^5.1.2"},devDependencies:{"@types/chai":"^4.2.16","@types/mocha":"^8.2.2","@types/node":"^14.14.37","array-includes":"^3.1.3",chai:"^4.1.1","chai-subset":"^1.6.0",chalk:"^2.4.2",co:"4.6.0",eslint:"^7.10.0","eslint-config-prettier":"^6.11.0","eslint-plugin-es":"^3.0.1","eslint-plugin-prettier":"^3.1.3",jsdoc:"^3.5.5","lodash.camelcase":"^4.3.0",mocha:"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1",nyc:"^15.1.0","object.entries":"^1.1.3",prettier:"^1.19.1",semver:"^5.5.0",sinon:"^4.3.0","sinon-chai":"^3.2.0",snappy:"^6.3.4","spec-xunit-file":"0.0.1-3","standard-version":"^9.2.0",tslib:"^2.2.0",typescript:"^4.2.4","util.promisify":"^1.0.1","worker-farm":"^1.5.0",wtfnode:"^0.8.0",yargs:"^14.2.0"},license:"Apache-2.0",engines:{node:">=4"},bugs:{url:"https://jira.mongodb.org/projects/NODE/issues/"},scripts:{"build:evergreen":"node .evergreen/generate_evergreen_tasks.js","build:unified":"tsc -p test/functional/unified-spec-runner/tsconfig.unified.json","check:atlas":"mocha --opts '{}' ./test/manual/atlas_connectivity.test.js","check:bench":"node test/benchmarks/driverBench/","check:coverage":"nyc npm run check:test","check:kerberos":"mocha --opts '{}' -t 60000 test/manual/kerberos.test.js","check:ldap":"mocha --opts '{}' test/manual/ldap.test.js","check:lint":"eslint -v && eslint lib test","check:test":"mocha --recursive test/functional test/unit","check:tls":"mocha --opts '{}' test/manual/tls_support.test.js",format:"npm run check:lint -- --fix",release:"standard-version -i HISTORY.md",test:"npm run check:lint && mocha --recursive test/functional test/unit"},homepage:"https://github.com/mongodb/node-mongodb-native",optionalDependencies:{saslprep:"^1.0.0"}}});var ce=E((Tme,YC)=>{"use strict";var aS=require("os"),JH=require("crypto"),HC=rh()(require),ZH=s(()=>{let e=JH.randomBytes(16);return e[6]=e[6]&15|64,e[8]=e[8]&63|128,e},"uuidV4");function QH(e,t,r){r.forEach(n=>e.on(n,i=>t.emit(n,i)))}s(QH,"relayEvents");function eV(){let e;try{e=HC("kerberos")}catch(t){throw t.code==="MODULE_NOT_FOUND"?new Error("The `kerberos` module was not found. Please install it and try again."):t}return e}s(eV,"retrieveKerberos");var ha=s(function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")},"noEJSONError");function tV(){let e=HC("mongodb-extjson");return e||(e={parse:ha,deserialize:ha,serialize:ha,stringify:ha,setBSONModule:ha,BSON:ha}),e}s(tV,"retrieveEJSON");function VC(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if(typeof e.lastIsMaster=="function"){let t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}s(VC,"maxWireVersion");function rV(e,t){return t&&t.collation&&VC(e)<5}s(rV,"collationNotSupported");function nV(e){return e&&typeof e.then=="function"}s(nV,"isPromiseLike");function iV(e,t,r){e=e||[];let n=0,i=0;for(n=0;nr===t[n])}s(aV,"arrayStrictEqual");function uV(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>t[i]===e[i])}s(uV,"tagsStrictEqual");function cV(e,t){return e===t?!0:!(e==null&&t!=null||e!=null&&t==null||e.constructor.name!==t.constructor.name||e.message!==t.message)}s(cV,"errorStrictEqual");function fV(e){return s(function(r,n){let i=e[r.s.state];if(i&&i.indexOf(n)<0)throw new TypeError(`illegal state transition from [${r.s.state}] => [${n}], allowed: [${i}]`);r.emit("stateChanged",r.s.state,n),r.s.state=n},"stateTransition")}s(fV,"makeStateMachine");function lV(e){e=e||{};let t={driver:{name:"nodejs",version:zC().version},os:{type:aS.type(),name:process.platform,architecture:process.arch,version:aS.release()},platform:`'Node.js ${process.version}, ${aS.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){let r=Buffer.from(e.appname);t.application={name:r.length>128?r.slice(0,128).toString("utf8"):e.appname}}return t}s(lV,"makeClientMetadata");var hV=s(()=>{},"noop");YC.exports={uuidV4:ZH,relayEvents:QH,collationNotSupported:rV,retrieveEJSON:tV,retrieveKerberos:eV,maxWireVersion:VC,isPromiseLike:nV,eachAsync:iV,eachAsyncSeries:sV,isUnifiedTopology:oV,arrayStrictEqual:aV,tagsStrictEqual:uV,errorStrictEqual:cV,makeStateMachine:fV,makeClientMetadata:lV,noop:hV}});var ro=E((bme,kC)=>{"use strict";var dV=Object.freeze({HostUnreachable:6,HostNotFound:7,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotMaster:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotMasterNoSlaveOk:13435,NotMasterOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernFailed:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,DuplicateKey:11e3,CannotCreateIndex:67,IndexOptionsConflict:85,IndexKeySpecsConflict:86,InvalidIndexSpecificationOption:197});kC.exports=Object.freeze({MONGODB_ERROR_CODES:dV})});var X=E((Ame,XC)=>{"use strict";var He=ro().MONGODB_ERROR_CODES,_i=Symbol("errorLabels"),oh=class oh extends Error{constructor(t){if(t instanceof Error)super(t.message),this.stack=t.stack;else{if(typeof t=="string")super(t);else{super(t.message||t.errmsg||t.$err||"n/a"),t.errorLabels&&(this[_i]=new Set(t.errorLabels));for(var r in t)r==="errorLabels"||r==="errmsg"||(this[r]=t[r])}Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(t){return new oh(t)}hasErrorLabel(t){return this[_i]==null?!1:this[_i].has(t)}addErrorLabel(t){this[_i]==null&&(this[_i]=new Set),this[_i].add(t)}get errorLabels(){return this[_i]?Array.from(this[_i]):[]}};s(oh,"MongoError");var no=oh,GC=Symbol("beforeHandshake");function pV(e){return e[GC]===!0}s(pV,"isNetworkErrorBeforeHandshake");var lS=class lS extends no{constructor(t,r){super(t),this.name="MongoNetworkError",r&&typeof r.beforeHandshake=="boolean"&&(this[GC]=r.beforeHandshake)}};s(lS,"MongoNetworkError");var _c=lS,hS=class hS extends _c{constructor(t,r){super(t,r),this.name="MongoNetworkTimeoutError"}};s(hS,"MongoNetworkTimeoutError");var cS=hS,dS=class dS extends no{constructor(t){super(t),this.name="MongoParseError"}};s(dS,"MongoParseError");var nh=dS,pS=class pS extends no{constructor(t,r){r&&r.error?super(r.error.message||r.error):super(t),this.name="MongoTimeoutError",r&&(this.reason=r)}};s(pS,"MongoTimeoutError");var ih=pS,mS=class mS extends ih{constructor(t,r){super(t,r),this.name="MongoServerSelectionError"}};s(mS,"MongoServerSelectionError");var fS=mS;function mV(e){let t=Object.assign({},e);return t.ok===0&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}s(mV,"makeWriteConcernResultObject");var gS=class gS extends no{constructor(t,r){super(t),this.name="MongoWriteConcernError",r&&Array.isArray(r.errorLabels)&&(this[_i]=new Set(r.errorLabels)),r!=null&&(this.result=mV(r))}};s(gS,"MongoWriteConcernError");var sh=gS,gV=new Set([He.HostUnreachable,He.HostNotFound,He.NetworkTimeout,He.ShutdownInProgress,He.PrimarySteppedDown,He.SocketException,He.NotMaster,He.InterruptedAtShutdown,He.InterruptedDueToReplStateChange,He.NotMasterNoSlaveOk,He.NotMasterOrSecondary]),uS=new Set([He.InterruptedAtShutdown,He.InterruptedDueToReplStateChange,He.NotMaster,He.NotMasterNoSlaveOk,He.NotMasterOrSecondary,He.PrimarySteppedDown,He.ShutdownInProgress,He.HostNotFound,He.HostUnreachable,He.NetworkTimeout,He.SocketException,He.ExceededTimeLimit]);function yV(e){return e.hasErrorLabel("RetryableWriteError")}s(yV,"isRetryableEndTransactionError");function SV(e){return e instanceof sh?uS.has(e.code)||uS.has(e.result.code):uS.has(e.code)}s(SV,"isRetryableWriteError");function _V(e){return gV.has(e.code)||e instanceof _c||e.message.match(/not master/)||e.message.match(/node is recovering/)}s(_V,"isRetryableError");var wV=new Set([He.ShutdownInProgress,He.PrimarySteppedDown,He.InterruptedAtShutdown,He.InterruptedDueToReplStateChange,He.NotMasterOrSecondary]),vV=new Set([He.NotMaster,He.NotMasterNoSlaveOk,He.LegacyNotPrimary]),OV=new Set([He.InterruptedAtShutdown,He.ShutdownInProgress]);function KC(e){return typeof e.code=="number"?wV.has(e.code):/not master or secondary/.test(e.message)||/node is recovering/.test(e.message)}s(KC,"isRecoveringError");function EV(e){return typeof e.code=="number"?vV.has(e.code):KC(e)?!1:/not master/.test(e.message)}s(EV,"isNotMasterError");function TV(e){return e.code&&OV.has(e.code)}s(TV,"isNodeShuttingDownError");function NV(e){return e instanceof nh||e==null?!0:KC(e)||EV(e)}s(NV,"isSDAMUnrecoverableError");XC.exports={MongoError:no,MongoNetworkError:_c,MongoNetworkTimeoutError:cS,MongoParseError:nh,MongoTimeoutError:ih,MongoServerSelectionError:fS,MongoWriteConcernError:sh,isRetryableError:_V,isSDAMUnrecoverableError:NV,isNodeShuttingDownError:TV,isRetryableWriteError:SV,isNetworkErrorBeforeHandshake:pV,isRetryableEndTransactionError:yV}});var wi=E((Ime,JC)=>{"use strict";var bV=new Set(["w","wtimeout","j","journal","fsync"]),yS,da=class da{constructor(t,r,n,i){t!=null&&(this.w=t),r!=null&&(this.wtimeout=r),n!=null&&(this.j=n),i!=null&&(this.fsync=i)}static fromOptions(t){if(!(t==null||t.writeConcern==null&&t.w==null&&t.wtimeout==null&&t.j==null&&t.journal==null&&t.fsync==null))return t.writeConcern?typeof t.writeConcern=="string"?new da(t.writeConcern):Object.keys(t.writeConcern).some(r=>bV.has(r))?new da(t.writeConcern.w,t.writeConcern.wtimeout,t.writeConcern.j||t.writeConcern.journal,t.writeConcern.fsync):void 0:(yS||(yS=x()),yS.emitWarningOnce("Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead."),new da(t.w,t.wtimeout,t.j||t.journal,t.fsync))}};s(da,"WriteConcern");var SS=da;JC.exports=SS});var _S=E(ZC=>{"use strict";function AV(){let e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}s(AV,"asyncIterator");ZC.asyncIterator=AV});var x=E((uh,s1)=>{"use strict";var ls=X().MongoError,CV=wi(),IV=s(function(e){var t={};for(var r in e)t[r]=e[r];return t},"shallowClone"),BV=s(function(e,t,r){Object.defineProperty(e,t,{enumerable:!0,get:function(){return r}})},"getSingleProperty"),RV=uh.formatSortValue=function(e){var t=(""+e).toLowerCase();switch(t){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},xV=uh.formattedOrderClause=function(e){var t=new Map;if(e==null)return null;if(Array.isArray(e)){if(e.length===0)return null;for(var r=0;r{if(e==null)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(r))throw new TypeError("This method requires an array of arguments to apply");n=n||{};let i=e.s.promiseLibrary,a=r[r.length-1],u,f,l;if(!n.skipSessions&&e.hasSessionSupport()){if(f=r[r.length-2],f==null||f.session==null){l=Symbol(),u=e.startSession({owner:l});let m=r.length-2;r[m]=Object.assign({},r[m],{session:u})}else if(f.session&&f.session.hasEnded)throw new ls("Use of expired sessions is not permitted")}let h=s((m,p)=>s(function(w,O){if(u&&u.owner===l&&!n.returnsCursor)u.endSession(()=>{if(delete f.session,w)return p(w);m(O)});else{if(w)return p(w);m(O)}},"executeCallback"),"makeExecuteCallback");if(typeof a=="function"){a=r.pop();let m=h(p=>a(null,p),p=>a(p,null));r.push(m);try{return t.apply(null,r)}catch(p){throw m(p),p}}if(r[r.length-1]!=null)throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new i(function(m,p){let g=h(m,p);r[r.length-1]=g;try{return t.apply(null,r)}catch(w){g(w)}})},"executeLegacyOperation");function VV(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e}s(VV,"applyRetryableWrites");function YV(e,t,r){r=r||{};let n=t.db,i=t.collection;if(r.session&&r.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;let a=CV.fromOptions(r);return a?Object.assign(e,{writeConcern:a}):i&&i.writeConcern?Object.assign(e,{writeConcern:Object.assign({},i.writeConcern)}):n&&n.writeConcern?Object.assign(e,{writeConcern:Object.assign({},n.writeConcern)}):e}s(YV,"applyWriteConcern");function kV(e){return e&&typeof e.then=="function"}s(kV,"isPromiseLike");function GV(e,t,r){let n=t.s&&t.s.topology||t.topology;if(!n)throw new TypeError('parameter "target" is missing a topology');let i=n.capabilities();if(r.collation&&typeof r.collation=="object")if(i&&i.commandsTakeCollation)e.collation=r.collation;else throw new ls("Current topology does not support collation")}s(GV,"decorateWithCollation");function KV(e,t,r){if(r&&r.session&&r.session.inTransaction())return;let n=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(n,t.s.readConcern),Object.keys(n).length>0&&Object.assign(e,{readConcern:n})}s(KV,"decorateWithReadConcern");function XV(e,t){return e.explain?e:{explain:e,verbosity:t.verbosity}}s(XV,"decorateWithExplain");var t1=+process.version.split(".")[0].substring(1),JV=s(e=>t1<=6?process.emitWarning(e,"DeprecationWarning",pa):process.emitWarning(e,{type:"DeprecationWarning",code:pa}),"emitProcessWarning"),ZV=s(e=>console.error(e),"emitConsoleWarning"),r1=process.emitWarning?JV:ZV;function QV(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}s(QV,"defaultMsgHandler");function eY(e,t){if(process.noDeprecation===!0)return t;let r=e.msgHandler?e.msgHandler:QV,n=new Set;function i(){let a=arguments[e.optionsIndex];return!ah(a)||Object.keys(a).length===0?t.apply(this,arguments):(e.deprecatedOptions.forEach(u=>{if(Object.prototype.hasOwnProperty.call(a,u)&&!n.has(u)){n.add(u);let f=r(e.name,u);if(r1(f),this&&this.getLogger){let l=this.getLogger();l&&l.warn(f)}}}),t.apply(this,arguments))}return s(i,"deprecated"),Object.setPrototypeOf(i,t),t.prototype&&(i.prototype=t.prototype),i}s(eY,"deprecateOptions");var wS={};try{_S(),wS.ASYNC_ITERATOR=!0}catch{wS.ASYNC_ITERATOR=!1}var wc=class wc{constructor(t,r){this.db=t,this.collection=r}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(t){return new wc(this.db,t)}static fromString(t){if(!t)throw new Error(`Cannot parse namespace from "${t}"`);let r=t.indexOf(".");return new wc(t.substring(0,r),t.substring(r+1))}};s(wc,"MongoDBNamespace");var vS=wc;function*tY(e){let t=e||0;for(;;){let r=t;t+=1,yield r}}s(tY,"makeCounter");function rY(e,t,r){let n=e&&e.s&&e.s.promiseLibrary||Promise,i;return typeof t!="function"&&(i=new n((a,u)=>{t=s((f,l)=>{if(f)return u(f);a(l)},"callback")})),r(function(a,u){if(a!=null){try{t(a)}catch(f){return process.nextTick(()=>{throw f})}return}t(a,u)}),i}s(rY,"maybePromise");function ES(){let e=process.hrtime();return Math.floor(e[0]*1e3+e[1]/1e6)}s(ES,"now");function nY(e){if(typeof e!="number")throw TypeError("numeric value required to calculate duration");let t=ES()-e;return t<0?0:t}s(nY,"calculateDurationInMs");function iY(e,t){let r,n,i,a=!1;t=t||{};let u=t.interval||1e3,f=t.minInterval||500,l=typeof t.immediate=="boolean"?t.immediate:!1,h=typeof t.clock=="function"?t.clock:ES;function m(){let O=h(),N=O-i,A=O-n,M=u-A;i=O,!(Nf&&g(f),M<0&&w())}s(m,"wake");function p(){a=!0,r&&(clearTimeout(r),r=null),n=0,i=0}s(p,"stop");function g(O){a||(clearTimeout(r),r=setTimeout(w,O||u))}s(g,"reschedule");function w(){i=0,n=h(),e(O=>{if(O)throw O;g(u)})}return s(w,"executeAndReschedule"),l?w():(n=h(),g()),{wake:m,stop:p}}s(iY,"makeInterruptableAsyncInterval");function n1(e){return Array.isArray(e)?e.reduce((t,r)=>t||n1(r),null):Object.keys(typeof e.toBSON!="function"?e:e.toBSON()).map(t=>t[0]).indexOf("$")>=0}s(n1,"hasAtomicOperators");var pa="MONGODB DRIVER";function i1(e){return process.emitWarning?t1<=6?process.emitWarning(e,void 0,pa):process.emitWarning(e,{code:pa}):console.error(`[${pa}] Warning:`,e)}s(i1,"emitWarning");var e1=new Set;function sY(e){if(!e1.has(e))return e1.add(e),i1(e)}s(sY,"emitWarningOnce");function oY(e,t){e=Array.isArray(e)?new Set(e):e,t=Array.isArray(t)?new Set(t):t;for(let r of t)if(!e.has(r))return!1;return!0}s(oY,"isSuperset");function aY(e,t){let r=Object.prototype.toString,n=Object.prototype.hasOwnProperty,i=s(u=>r.call(u)==="[object Object]","isObject");if(!i(e))return!1;let a=e.constructor;if(a&&a.prototype&&(!i(a.prototype)||!n.call(a.prototype,"isPrototypeOf")))return!1;if(t){let u=Object.keys(e);return oY(u,t)}return!0}s(aY,"isRecord");function OS(e){if(e==null)return e;if(Array.isArray(e))return e.map(r=>OS(r));if(aY(e)){let r={};for(let n in e)r[n]=OS(e[n]);return r}let t=e.constructor;if(t)switch(t.name.toLowerCase()){case"date":return new t(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return Buffer.from(e)}return e}s(OS,"deepCopy");function uY(e){let t=e.version.split(".").map(r=>Number.parseInt(r,10));return{major:t[0],minor:t[1],patch:t[2]}}s(uY,"parsePackageVersion");s1.exports={filterOptions:$V,mergeOptions:WV,translateOptions:FV,shallowClone:IV,getSingleProperty:BV,checkCollectionName:MV,toError:qV,formattedOrderClause:xV,parseIndexOptions:LV,normalizeHintField:PV,handleCallback:DV,decorateCommand:jV,isObject:ah,debugOptions:UV,MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:zV,executeLegacyOperation:HV,applyRetryableWrites:VV,applyWriteConcern:YV,isPromiseLike:kV,decorateWithCollation:GV,decorateWithReadConcern:KV,decorateWithExplain:XV,deprecateOptions:eY,SUPPORTS:wS,MongoDBNamespace:vS,emitDeprecationWarning:r1,makeCounter:tY,maybePromise:rY,now:ES,calculateDurationInMs:nY,makeInterruptableAsyncInterval:iY,hasAtomicOperators:n1,MONGODB_WARNING_CODE:pa,emitWarning:i1,emitWarningOnce:sY,deepCopy:OS,parsePackageVersion:uY}});var jt=E((Dme,u1)=>{"use strict";var o1=x().parsePackageVersion,cY=X().MongoError,fh=rh()(require);function fY(e,t){let r={};return e.forEach(function(n){r[n]=t[n]}),r}s(fY,"debugOptions");function lY(){let e=th();e.native=!1;let t=fh("bson-ext"),r=o1(fh("bson-ext/package.json")||{version:"0.0.0"});if(t){if(r.major>=4)throw new cY("bson-ext version 4 and above does not work with the 3.x version of the mongodb driver");return t.native=!0,t}return e}s(lY,"retrieveBSON");function ch(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}s(ch,"noSnappyWarning");var a1=Symbol("kPkgVersion");function hY(){let e=fh("snappy");if(!e)return{compress:ch,uncompress:ch,compressSync:ch,uncompressSync:ch};let t=fh("snappy/package.json")||{version:"0.0.0"},r=o1(t);if(e[a1]=r,r.major>=7){let n=e.compress,i=e.uncompress;e.compress=(a,u)=>{n(a).then(f=>u(void 0,f)).catch(f=>u(f))},e.uncompress=(a,u)=>{i(a).then(f=>u(void 0,f)).catch(f=>u(f))}}return e}s(hY,"retrieveSnappy");u1.exports={PKG_VERSION:a1,debugOptions:fY,retrieveBSON:lY,retrieveSnappy:hY}});var Vt=E((Pme,c1)=>{"use strict";var dY=x().emitWarningOnce,Oe=s(function(e,t,r){if(!Oe.isValid(e))throw new TypeError(`Invalid read preference mode ${e}`);if(t&&!Array.isArray(t)){dY("ReadPreference tags must be an array, this will change in the next major version");let n=typeof t.maxStalenessSeconds<"u",i=typeof t.hedge<"u";n||i?(r=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=r&&r.hedge,r=r||{},r.maxStalenessSeconds!=null){if(r.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=r.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===Oe.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}},"ReadPreference");Object.defineProperty(Oe.prototype,"preference",{enumerable:!0,get:function(){return this.mode}});Oe.PRIMARY="primary";Oe.PRIMARY_PREFERRED="primaryPreferred";Oe.SECONDARY="secondary";Oe.SECONDARY_PREFERRED="secondaryPreferred";Oe.NEAREST="nearest";var pY=[Oe.PRIMARY,Oe.PRIMARY_PREFERRED,Oe.SECONDARY,Oe.SECONDARY_PREFERRED,Oe.NEAREST,null];Oe.fromOptions=function(e){if(!e)return null;let t=e.readPreference;if(!t)return null;let r=e.readPreferenceTags,n=e.maxStalenessSeconds;if(typeof t=="string")return new Oe(t,r);if(!(t instanceof Oe)&&typeof t=="object"){let i=t.mode||t.preference;if(i&&typeof i=="string")return new Oe(i,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||n,hedge:t.hedge})}return t};Oe.resolve=function(e,t){t=t||{};let r=t.session,n=e&&e.readPreference,i;return t.readPreference?i=Oe.fromOptions(t):r&&r.inTransaction()&&r.transaction.options.readPreference?i=r.transaction.options.readPreference:n!=null?i=n:i=Oe.primary,typeof i=="string"?new Oe(i):i};Oe.translate=function(e){if(e.readPreference==null)return e;let t=e.readPreference;if(typeof t=="string")e.readPreference=new Oe(t);else if(t&&!(t instanceof Oe)&&typeof t=="object"){let r=t.mode||t.preference;r&&typeof r=="string"&&(e.readPreference=new Oe(r,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}else if(!(t instanceof Oe))throw new TypeError("Invalid read preference: "+t);return e};Oe.isValid=function(e){return pY.indexOf(e)!==-1};Oe.prototype.isValid=function(e){return Oe.isValid(typeof e=="string"?e:this.mode)};var mY=["primaryPreferred","secondary","secondaryPreferred","nearest"];Oe.prototype.slaveOk=function(){return mY.indexOf(this.mode)!==-1};Oe.prototype.equals=function(e){return e.mode===this.mode};Oe.prototype.toJSON=function(){let e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e};Oe.primary=new Oe("primary");Oe.primaryPreferred=new Oe("primaryPreferred");Oe.secondary=new Oe("secondary");Oe.secondaryPreferred=new Oe("secondaryPreferred");Oe.nearest=new Oe("nearest");c1.exports=Oe});var tr=E((Ume,l1)=>{"use strict";var gY="closing",yY="closed",SY="connecting",_Y="connected",f1={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"},wY={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};function vY(e){let t=e.s.description||e.s.serverDescription;return t.topologyType===f1.Single?t.servers[0].type:t.type}s(vY,"serverType");var OY={useUnifiedTopology:!0,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500};function EY(e){e.forEach(clearTimeout),e.clear()}s(EY,"drainTimerQueue");function TY(e,t){return clearTimeout(e),t.delete(e)}s(TY,"clearAndRemoveTimerFrom");l1.exports={STATE_CLOSING:gY,STATE_CLOSED:yY,STATE_CONNECTING:SY,STATE_CONNECTED:_Y,TOPOLOGY_DEFAULTS:OY,TopologyType:f1,ServerType:wY,serverType:vY,drainTimerQueue:EY,clearAndRemoveTimerFrom:TY}});var io=E((Wme,p1)=>{"use strict";var NY=ce().arrayStrictEqual,bY=ce().tagsStrictEqual,AY=ce().errorStrictEqual,Yt=tr().ServerType,CY=x().now,IY=new Set([Yt.RSPrimary,Yt.Standalone,Yt.Mongos]),BY=new Set([Yt.RSPrimary,Yt.RSSecondary,Yt.Mongos,Yt.Standalone]),RY=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"],NS=class NS{constructor(t,r,n){n=n||{},r=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},r),r.isWritablePrimary!=null&&(r.ismaster=r.isWritablePrimary),this.address=t,this.error=n.error,this.roundTripTime=n.roundTripTime||-1,this.lastUpdateTime=CY(),this.lastWriteDate=r.lastWrite?r.lastWrite.lastWriteDate:null,this.opTime=r.lastWrite?r.lastWrite.opTime:null,this.type=h1(r),this.topologyVersion=n.topologyVersion||r.topologyVersion,RY.forEach(i=>{typeof r[i]<"u"&&(this[i]=r[i])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(i=>i.toLowerCase()),this.passives=this.passives.map(i=>i.toLowerCase()),this.arbiters=this.arbiters.map(i=>i.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===Yt.RSSecondary||this.isWritable}get isDataBearing(){return BY.has(this.type)}get isWritable(){return IY.has(this.type)}get host(){let t=`:${this.port}`.length;return this.address.slice(0,-t)}get port(){let t=this.address.split(":").pop();return t&&Number.parseInt(t,10)}equals(t){let r=this.topologyVersion===t.topologyVersion||d1(this.topologyVersion,t.topologyVersion)===0;return t!=null&&AY(this.error,t.error)&&this.type===t.type&&this.minWireVersion===t.minWireVersion&&this.me===t.me&&NY(this.hosts,t.hosts)&&bY(this.tags,t.tags)&&this.setName===t.setName&&this.setVersion===t.setVersion&&(this.electionId?t.electionId&&this.electionId.equals(t.electionId):this.electionId===t.electionId)&&this.primary===t.primary&&this.logicalSessionTimeoutMinutes===t.logicalSessionTimeoutMinutes&&r}};s(NS,"ServerDescription");var TS=NS;function h1(e){return!e||!e.ok?Yt.Unknown:e.isreplicaset?Yt.RSGhost:e.msg&&e.msg==="isdbgrid"?Yt.Mongos:e.setName?e.hidden?Yt.RSOther:e.ismaster?Yt.RSPrimary:e.secondary?Yt.RSSecondary:e.arbiterOnly?Yt.RSArbiter:Yt.RSOther:Yt.Standalone}s(h1,"parseServerType");function d1(e,t){return e==null||t==null?-1:e.processId.equals(t.processId)?e.counter===t.counter?0:e.counter{"use strict";var xY="2.6",MY="5.0";m1.exports={MIN_SUPPORTED_SERVER_VERSION:xY,MAX_SUPPORTED_SERVER_VERSION:MY,MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:13}});var CS=E((zme,_1)=>{"use strict";var pt=tr().ServerType,ga=io().ServerDescription,lh=bS(),_r=tr().TopologyType,DY=lh.MIN_SUPPORTED_SERVER_VERSION,qY=lh.MAX_SUPPORTED_SERVER_VERSION,g1=lh.MIN_SUPPORTED_WIRE_VERSION,y1=lh.MAX_SUPPORTED_WIRE_VERSION,ma=class ma{constructor(t,r,n,i,a,u,f){f=f||{},this.type=t||_r.Unknown,this.setName=n||null,this.maxSetVersion=i||null,this.maxElectionId=a||null,this.servers=r||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=f.heartbeatFrequencyMS||0,this.localThresholdMS=f.localThresholdMS||0,this.commonWireVersion=u||null,Object.defineProperty(this,"options",{value:f,enumberable:!1});for(let l of this.servers.values())if(l.type!==pt.Unknown&&(l.minWireVersion>y1&&(this.compatible=!1,this.compatibilityError=`Server at ${l.address} requires wire version ${l.minWireVersion}, but this version of the driver only supports up to ${y1} (MongoDB ${qY})`),l.maxWireVersion=0&&h.delete(r),l===pt.RSPrimary){let m=S1(h,i,t,a,u);n=m[0],i=m[1],a=m[2],u=m[3]}else if([pt.RSSecondary,pt.RSArbiter,pt.RSOther].indexOf(l)>=0){let m=jY(h,i,t);n=m[0],i=m[1]}}if(n===_r.ReplicaSetWithPrimary)if([pt.Standalone,pt.Mongos].indexOf(l)>=0)h.delete(r),n=ya(h);else if(l===pt.RSPrimary){let m=S1(h,i,t,a,u);n=m[0],i=m[1],a=m[2],u=m[3]}else[pt.RSSecondary,pt.RSArbiter,pt.RSOther].indexOf(l)>=0?n=UY(h,i,t):n=ya(h);return new ma(n,h,i,a,u,f,this.options)}get error(){let t=Array.from(this.servers.values()).filter(r=>r.error);if(t.length>0)return t[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(t=>t.type!==pt.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(t=>t.isDataBearing)}hasServer(t){return this.servers.has(t)}};s(ma,"TopologyDescription");var AS=ma;function PY(e){return e===pt.Standalone?_r.Single:e===pt.Mongos?_r.Sharded:e===pt.RSPrimary?_r.ReplicaSetWithPrimary:e===pt.RSGhost||e===pt.Unknown?_r.Unknown:_r.ReplicaSetNoPrimary}s(PY,"topologyTypeForServerType");function LY(e,t){if(e==null)return-1;if(t==null)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){let i=e.id,a=t.id;return i.compare(a)}let r=e.toString(),n=t.toString();return r.localeCompare(n)}s(LY,"compareObjectId");function S1(e,t,r,n,i){if(t=t||r.setName,t!==r.setName)return e.delete(r.address),[ya(e),t,n,i];let a=r.electionId?r.electionId:null;if(r.setVersion&&a){if(n&&i&&(n>r.setVersion||LY(i,a)>0))return e.set(r.address,new ga(r.address)),[ya(e),t,n,i];i=r.electionId}r.setVersion!=null&&(n==null||r.setVersion>n)&&(n=r.setVersion);for(let l of e.keys()){let h=e.get(l);if(h.type===pt.RSPrimary&&h.address!==r.address){e.set(l,new ga(h.address));break}}r.allHosts.forEach(l=>{e.has(l)||e.set(l,new ga(l))});let u=Array.from(e.keys()),f=r.allHosts;return u.filter(l=>f.indexOf(l)===-1).forEach(l=>{e.delete(l)}),[ya(e),t,n,i]}s(S1,"updateRsFromPrimary");function UY(e,t,r){if(t==null)throw new TypeError("setName is required");return(t!==r.setName||r.me&&r.address!==r.me)&&e.delete(r.address),ya(e)}s(UY,"updateRsWithPrimaryFromMember");function jY(e,t,r){let n=_r.ReplicaSetNoPrimary;return t=t||r.setName,t!==r.setName?(e.delete(r.address),[n,t]):(r.allHosts.forEach(i=>{e.has(i)||e.set(i,new ga(i))}),r.me&&r.address!==r.me&&e.delete(r.address),[n,t])}s(jY,"updateRsNoPrimaryFromMember");function ya(e){for(let t of e.keys())if(e.get(t).type===pt.RSPrimary)return _r.ReplicaSetWithPrimary;return _r.ReplicaSetNoPrimary}s(ya,"checkHasPrimary");_1.exports={TopologyDescription:AS}});var et=E((Vme,v1)=>{"use strict";var IS=Vt(),WY=X().MongoError,w1=tr().ServerType,FY=CS().TopologyDescription,$Y=16,zY=9,HY={OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},VY=s(function(e,t){var r=e.readPreference||new IS("primary");if(t.readPreference&&(r=t.readPreference),typeof r=="string"&&(r=new IS(r)),!(r instanceof IS))throw new WY("read preference must be a ReadPreference instance");return r},"getReadPreference"),YY=s(function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},"parseHeader");function kY(e,t){return Object.assign(e,{raw:typeof t.raw=="boolean"?t.raw:!1,promoteLongs:typeof t.promoteLongs=="boolean"?t.promoteLongs:!0,promoteValues:typeof t.promoteValues=="boolean"?t.promoteValues:!0,promoteBuffers:typeof t.promoteBuffers=="boolean"?t.promoteBuffers:!1,bsonRegExp:typeof t.bsonRegExp=="boolean"?t.bsonRegExp:!1,monitoring:typeof t.monitoring=="boolean"?t.monitoring:!1,fullResult:typeof t.fullResult=="boolean"?t.fullResult:!1}),typeof t.socketTimeout=="number"&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),typeof t.documentsReturnedIn=="string"&&(e.documentsReturnedIn=t.documentsReturnedIn),e}s(kY,"applyCommonQueryOptions");function GY(e){return e.type==="mongos"||e.description&&e.description.type===w1.Mongos?!0:e.description&&e.description instanceof FY?Array.from(e.description.servers.values()).some(r=>r.type===w1.Mongos):!1}s(GY,"isSharded");function KY(e){return e.split(".")[0]}s(KY,"databaseNamespace");function XY(e){return e.split(".").slice(1).join(".")}s(XY,"collectionNamespace");v1.exports={getReadPreference:VY,MESSAGE_HEADER_SIZE:$Y,COMPRESSION_DETAILS_SIZE:zY,opcodes:HY,parseHeader:YY,applyCommonQueryOptions:kY,isSharded:GY,databaseNamespace:KY,collectionNamespace:XY}});var vi=E((kme,T1)=>{"use strict";var O1=jt().retrieveSnappy(),E1=require("zlib"),hh={snappy:1,zlib:2},JY=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);function ZY(e,t,r){switch(e.options.agreedCompressor){case"snappy":O1.compress(t,r);break;case"zlib":var n={};e.options.zlibCompressionLevel&&(n.level=e.options.zlibCompressionLevel),E1.deflate(t,n,r);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}}s(ZY,"compress");function QY(e,t,r){if(e<0||e>hh.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case hh.snappy:O1.uncompress(t,r);break;case hh.zlib:E1.inflate(t,r);break;default:r(null,t)}}s(QY,"decompress");T1.exports={compressorIDs:hh,uncompressibleCommands:JY,compress:ZY,decompress:QY}});var qn=E((BS,b1)=>{var dh=require("buffer"),kn=dh.Buffer;function N1(e,t){for(var r in e)t[r]=e[r]}s(N1,"copyProps");kn.from&&kn.alloc&&kn.allocUnsafe&&kn.allocUnsafeSlow?b1.exports=dh:(N1(dh,BS),BS.Buffer=so);function so(e,t,r){return kn(e,t,r)}s(so,"SafeBuffer");so.prototype=Object.create(kn.prototype);N1(kn,so);so.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return kn(e,t,r)};so.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=kn(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};so.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return kn(e)};so.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return dh.SlowBuffer(e)}});var Xr=E((Xme,I1)=>{"use strict";var ek=jt().retrieveBSON,tk=ek(),rk=tk.Long,vc=qn().Buffer,Oc=0,pn=et().opcodes,nk=2,ik=4,sk=8,ok=16,ak=32,uk=64,ck=128,fk=1,lk=2,hk=4,dk=8,Sa=s(function(e,t,r,n){var i=this;if(t==null)throw new Error("ns must be specified for query");if(r==null)throw new Error("query must be specified for query");if(t.indexOf("\0")!==-1)throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=r,this.numberToSkip=n.numberToSkip||0,this.numberToReturn=n.numberToReturn||0,this.returnFieldSelector=n.returnFieldSelector||null,this.requestId=Sa.getRequestId(),this.pre32Limit=n.pre32Limit,this.serializeFunctions=typeof n.serializeFunctions=="boolean"?n.serializeFunctions:!1,this.ignoreUndefined=typeof n.ignoreUndefined=="boolean"?n.ignoreUndefined:!1,this.maxBsonSize=n.maxBsonSize||1024*1024*16,this.checkKeys=typeof n.checkKeys=="boolean"?n.checkKeys:!0,this.batchSize=i.numberToReturn,this.tailable=!1,this.slaveOk=typeof n.slaveOk=="boolean"?n.slaveOk:!1,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1},"Query");Sa.prototype.incRequestId=function(){this.requestId=Oc++};Sa.nextRequestId=function(){return Oc+1};Sa.prototype.toBin=function(){var e=this,t=[],r=null,n=0;this.tailable&&(n|=nk),this.slaveOk&&(n|=ik),this.oplogReplay&&(n|=sk),this.noCursorTimeout&&(n|=ok),this.awaitData&&(n|=ak),this.exhaust&&(n|=uk),this.partial&&(n|=ck),e.batchSize!==e.numberToReturn&&(e.numberToReturn=e.batchSize);var i=vc.alloc(4*4+4+vc.byteLength(e.ns)+1+4+4);t.push(i);var a=e.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(a),e.returnFieldSelector&&Object.keys(e.returnFieldSelector).length>0&&(r=e.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),t.push(r));var u=i.length+a.length+(r?r.length:0),f=4;return i[3]=u>>24&255,i[2]=u>>16&255,i[1]=u>>8&255,i[0]=u&255,i[f+3]=this.requestId>>24&255,i[f+2]=this.requestId>>16&255,i[f+1]=this.requestId>>8&255,i[f]=this.requestId&255,f=f+4,i[f+3]=0,i[f+2]=0,i[f+1]=0,i[f]=0,f=f+4,i[f+3]=pn.OP_QUERY>>24&255,i[f+2]=pn.OP_QUERY>>16&255,i[f+1]=pn.OP_QUERY>>8&255,i[f]=pn.OP_QUERY&255,f=f+4,i[f+3]=n>>24&255,i[f+2]=n>>16&255,i[f+1]=n>>8&255,i[f]=n&255,f=f+4,f=f+i.write(this.ns,f,"utf8")+1,i[f-1]=0,i[f+3]=this.numberToSkip>>24&255,i[f+2]=this.numberToSkip>>16&255,i[f+1]=this.numberToSkip>>8&255,i[f]=this.numberToSkip&255,f=f+4,i[f+3]=this.numberToReturn>>24&255,i[f+2]=this.numberToReturn>>16&255,i[f+1]=this.numberToReturn>>8&255,i[f]=this.numberToReturn&255,f=f+4,t};Sa.getRequestId=function(){return++Oc};var A1=s(function(e,t,r,n){n=n||{},this.numberToReturn=n.numberToReturn||0,this.requestId=Oc++,this.bson=e,this.ns=t,this.cursorId=r},"GetMore");A1.prototype.toBin=function(){var e=4+vc.byteLength(this.ns)+1+4+8+16,t=0,r=vc.alloc(e);return r[t+3]=e>>24&255,r[t+2]=e>>16&255,r[t+1]=e>>8&255,r[t]=e&255,t=t+4,r[t+3]=this.requestId>>24&255,r[t+2]=this.requestId>>16&255,r[t+1]=this.requestId>>8&255,r[t]=this.requestId&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,r[t+3]=pn.OP_GETMORE>>24&255,r[t+2]=pn.OP_GETMORE>>16&255,r[t+1]=pn.OP_GETMORE>>8&255,r[t]=pn.OP_GETMORE&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,t=t+r.write(this.ns,t,"utf8")+1,r[t-1]=0,r[t+3]=this.numberToReturn>>24&255,r[t+2]=this.numberToReturn>>16&255,r[t+1]=this.numberToReturn>>8&255,r[t]=this.numberToReturn&255,t=t+4,r[t+3]=this.cursorId.getLowBits()>>24&255,r[t+2]=this.cursorId.getLowBits()>>16&255,r[t+1]=this.cursorId.getLowBits()>>8&255,r[t]=this.cursorId.getLowBits()&255,t=t+4,r[t+3]=this.cursorId.getHighBits()>>24&255,r[t+2]=this.cursorId.getHighBits()>>16&255,r[t+1]=this.cursorId.getHighBits()>>8&255,r[t]=this.cursorId.getHighBits()&255,t=t+4,r};var C1=s(function(e,t,r){this.ns=t,this.requestId=Oc++,this.cursorIds=r},"KillCursor");C1.prototype.toBin=function(){var e=24+this.cursorIds.length*8,t=0,r=vc.alloc(e);r[t+3]=e>>24&255,r[t+2]=e>>16&255,r[t+1]=e>>8&255,r[t]=e&255,t=t+4,r[t+3]=this.requestId>>24&255,r[t+2]=this.requestId>>16&255,r[t+1]=this.requestId>>8&255,r[t]=this.requestId&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,r[t+3]=pn.OP_KILL_CURSORS>>24&255,r[t+2]=pn.OP_KILL_CURSORS>>16&255,r[t+1]=pn.OP_KILL_CURSORS>>8&255,r[t]=pn.OP_KILL_CURSORS&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,r[t+3]=this.cursorIds.length>>24&255,r[t+2]=this.cursorIds.length>>16&255,r[t+1]=this.cursorIds.length>>8&255,r[t]=this.cursorIds.length&255,t=t+4;for(var n=0;n>24&255,r[t+2]=this.cursorIds[n].getLowBits()>>16&255,r[t+1]=this.cursorIds[n].getLowBits()>>8&255,r[t]=this.cursorIds[n].getLowBits()&255,t=t+4,r[t+3]=this.cursorIds[n].getHighBits()>>24&255,r[t+2]=this.cursorIds[n].getHighBits()>>16&255,r[t+1]=this.cursorIds[n].getHighBits()>>8&255,r[t]=this.cursorIds[n].getHighBits()&255,t=t+4;return r};var RS=s(function(e,t,r,n,i){i=i||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.parsed=!1,this.raw=t,this.data=n,this.bson=e,this.opts=i,this.length=r.length,this.requestId=r.requestId,this.responseTo=r.responseTo,this.opCode=r.opCode,this.fromCompressed=r.fromCompressed,this.responseFlags=n.readInt32LE(0),this.cursorId=new rk(n.readInt32LE(4),n.readInt32LE(8)),this.startingFrom=n.readInt32LE(12),this.numberReturned=n.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=(this.responseFlags&fk)!==0,this.queryFailure=(this.responseFlags&lk)!==0,this.shardConfigStale=(this.responseFlags&hk)!==0,this.awaitCapable=(this.responseFlags&dk)!==0,this.promoteLongs=typeof i.promoteLongs=="boolean"?i.promoteLongs:!0,this.promoteValues=typeof i.promoteValues=="boolean"?i.promoteValues:!0,this.promoteBuffers=typeof i.promoteBuffers=="boolean"?i.promoteBuffers:!1,this.bsonRegExp=typeof i.bsonRegExp=="boolean"?i.bsonRegExp:!1},"Response");RS.prototype.isParsed=function(){return this.parsed};RS.prototype.parse=function(e){if(!this.parsed){e=e||{};var t=e.raw||!1,r=e.documentsReturnedIn||null,n=typeof e.promoteLongs=="boolean"?e.promoteLongs:this.opts.promoteLongs,i=typeof e.promoteValues=="boolean"?e.promoteValues:this.opts.promoteValues,a=typeof e.promoteBuffers=="boolean"?e.promoteBuffers:this.opts.promoteBuffers,u=typeof e.bsonRegExp=="boolean"?e.bsonRegExp:this.opts.bsonRegExp,f,l;l={promoteLongs:n,promoteValues:i,promoteBuffers:a,bsonRegExp:u},this.index=20;for(var h=0;h{"use strict";var B1=qn().Buffer,pk=et().opcodes,mk=et().databaseNamespace,gk=Vt(),yk=X().MongoError,xS=0,R1=1,x1=2,M1=65536,mh=class mh{constructor(t,r,n,i){if(n==null)throw new Error("query must be specified for query");this.bson=t,this.ns=r,this.command=n,this.command.$db=mk(r),i.readPreference&&i.readPreference.mode!==gk.PRIMARY&&(this.command.$readPreference=i.readPreference.toJSON()),this.options=i||{},this.requestId=i.requestId?i.requestId:mh.getRequestId(),this.serializeFunctions=typeof i.serializeFunctions=="boolean"?i.serializeFunctions:!1,this.ignoreUndefined=typeof i.ignoreUndefined=="boolean"?i.ignoreUndefined:!1,this.checkKeys=typeof i.checkKeys=="boolean"?i.checkKeys:!1,this.maxBsonSize=i.maxBsonSize||1024*1024*16,this.checksumPresent=!1,this.moreToCome=i.moreToCome||!1,this.exhaustAllowed=typeof i.exhaustAllowed=="boolean"?i.exhaustAllowed:!1}toBin(){let t=[],r=0;this.checksumPresent&&(r|=R1),this.moreToCome&&(r|=x1),this.exhaustAllowed&&(r|=M1);let n=B1.alloc(4*4+4);t.push(n);let i=n.length,a=this.command;return i+=this.makeDocumentSegment(t,a),n.writeInt32LE(i,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(pk.OP_MSG,12),n.writeUInt32LE(r,16),t}makeDocumentSegment(t,r){let n=B1.alloc(1);n[0]=0;let i=this.serializeBson(r);return t.push(n),t.push(i),n.length+i.length}serializeBson(t){return this.bson.serialize(t,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}};s(mh,"Msg");var ph=mh;ph.getRequestId=function(){return xS=xS+1&2147483647,xS};var DS=class DS{constructor(t,r,n,i,a){a=a||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.parsed=!1,this.raw=r,this.data=i,this.bson=t,this.opts=a,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=i.readInt32LE(0),this.checksumPresent=(this.responseFlags&R1)!==0,this.moreToCome=(this.responseFlags&x1)!==0,this.exhaustAllowed=(this.responseFlags&M1)!==0,this.promoteLongs=typeof a.promoteLongs=="boolean"?a.promoteLongs:!0,this.promoteValues=typeof a.promoteValues=="boolean"?a.promoteValues:!0,this.promoteBuffers=typeof a.promoteBuffers=="boolean"?a.promoteBuffers:!1,this.bsonRegExp=typeof a.bsonRegExp=="boolean"?a.bsonRegExp:!1,this.documents=[]}isParsed(){return this.parsed}parse(t){if(this.parsed)return;t=t||{},this.index=4;let r=t.raw||!1,n=t.documentsReturnedIn||null,i=typeof t.promoteLongs=="boolean"?t.promoteLongs:this.opts.promoteLongs,a=typeof t.promoteValues=="boolean"?t.promoteValues:this.opts.promoteValues,u=typeof t.promoteBuffers=="boolean"?t.promoteBuffers:this.opts.promoteBuffers,f=typeof t.bsonRegExp=="boolean"?t.bsonRegExp:this.opts.bsonRegExp,l={promoteLongs:i,promoteValues:a,promoteBuffers:u,bsonRegExp:f};for(;this.index{"use strict";var Ec=require("util").format,Sk=X().MongoError,Tc={},rr={},Jr=null,hs=process.pid,Oi=null,nr=s(function(e,t){if(!(this instanceof nr))return new nr(e,t);t=t||{},this.className=e,t.logger?Oi=t.logger:Oi==null&&(Oi=console.log),t.loggerLevel&&(Jr=t.loggerLevel||"error"),rr[this.className]==null&&(Tc[this.className]=!0)},"Logger");nr.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(rr).length>0&&rr[this.className]||Object.keys(rr).length===0&&Tc[this.className])){var r=new Date().getTime(),n=Ec("[%s-%s:%s] %s %s","DEBUG",this.className,hs,r,e),i={type:"debug",message:e,className:this.className,pid:hs,date:r};t&&(i.meta=t),Oi(n,i)}};nr.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(rr).length>0&&rr[this.className]||Object.keys(rr).length===0&&Tc[this.className])){var r=new Date().getTime(),n=Ec("[%s-%s:%s] %s %s","WARN",this.className,hs,r,e),i={type:"warn",message:e,className:this.className,pid:hs,date:r};t&&(i.meta=t),Oi(n,i)}},nr.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(rr).length>0&&rr[this.className]||Object.keys(rr).length===0&&Tc[this.className])){var r=new Date().getTime(),n=Ec("[%s-%s:%s] %s %s","INFO",this.className,hs,r,e),i={type:"info",message:e,className:this.className,pid:hs,date:r};t&&(i.meta=t),Oi(n,i)}},nr.prototype.error=function(e,t){if(this.isError()&&(Object.keys(rr).length>0&&rr[this.className]||Object.keys(rr).length===0&&Tc[this.className])){var r=new Date().getTime(),n=Ec("[%s-%s:%s] %s %s","ERROR",this.className,hs,r,e),i={type:"error",message:e,className:this.className,pid:hs,date:r};t&&(i.meta=t),Oi(n,i)}},nr.prototype.isInfo=function(){return Jr==="info"||Jr==="debug"},nr.prototype.isError=function(){return Jr==="error"||Jr==="info"||Jr==="debug"},nr.prototype.isWarn=function(){return Jr==="error"||Jr==="warn"||Jr==="info"||Jr==="debug"},nr.prototype.isDebug=function(){return Jr==="debug"};nr.reset=function(){Jr="error",rr={}};nr.currentLogger=function(){return Oi};nr.setCurrentLogger=function(e){if(typeof e!="function")throw new Sk("current logger must be a function");Oi=e};nr.filter=function(e,t){e==="class"&&Array.isArray(t)&&(rr={},t.forEach(function(r){rr[r]=!0}))};nr.setLevel=function(e){if(e!=="info"&&e!=="error"&&e!=="debug"&&e!=="warn")throw new Error(Ec("%s is an illegal logging level",e));Jr=e};q1.exports=nr});var gh=E((rge,P1)=>{"use strict";var qS=s(function(e,t,r){this.result=e,this.connection=t,this.message=r},"CommandResult");qS.prototype.toJSON=function(){let e=Object.assign({},this,this.result);return delete e.message,e};qS.prototype.toString=function(){return JSON.stringify(this.toJSON())};P1.exports=qS});var FS=E((ige,$1)=>{"use strict";var _k=require("events").EventEmitter,wk=require("crypto"),vk=jt().debugOptions,Ok=et().parseHeader,Ek=vi().decompress,L1=Xr().Response,U1=oo().BinMsg,F1=X().MongoNetworkError,Tk=X().MongoNetworkTimeoutError,US=X().MongoError,Nk=mn(),bk=et().opcodes.OP_COMPRESSED,j1=et().opcodes.OP_MSG,W1=et().MESSAGE_HEADER_SIZE,Gn=qn().Buffer,Ak=Xr().Query,Ck=gh(),Ik=0,Bk=1024*1024*16*4,Rk=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","checkServerIdentity"],_a,ao=!1,yh={},WS=class WS extends _k{constructor(t,r){if(super(),r=r||{},!r.bson)throw new TypeError("must pass in valid bson parser");this.id=Ik++,this.options=r,this.logger=Nk("Connection",r),this.bson=r.bson,this.tag=r.tag,this.maxBsonMessageSize=r.maxBsonMessageSize||Bk,this.helloOk=void 0,this.port=r.port||27017,this.host=r.host||"localhost",this.socketTimeout=typeof r.socketTimeout=="number"?r.socketTimeout:0,this.keepAlive=typeof r.keepAlive=="boolean"?r.keepAlive:!0,this.keepAliveInitialDelay=typeof r.keepAliveInitialDelay=="number"?r.keepAliveInitialDelay:12e4,this.connectionTimeout=typeof r.connectionTimeout=="number"?r.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(vk(Rk,r))}]`),this.responseOptions={promoteLongs:typeof r.promoteLongs=="boolean"?r.promoteLongs:!0,promoteValues:typeof r.promoteValues=="boolean"?r.promoteValues:!0,promoteBuffers:typeof r.promoteBuffers=="boolean"?r.promoteBuffers:!1,bsonRegExp:typeof r.bsonRegExp=="boolean"?r.bsonRegExp:!1},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;let n=wk.createHash("sha1");n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=t,this.socket.once("error",Mk(this)),this.socket.once("timeout",Dk(this)),this.socket.once("close",qk(this)),this.socket.on("data",Pk(this)),ao&&xk(this.id,this)}setSocketTimeout(t){this.socket&&this.socket.setTimeout(t)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(t){t&&(_a=t),ao=!0,yh={}}static disableConnectionAccounting(){ao=!1,_a=void 0}static connections(){return yh}get address(){return`${this.host}:${this.port}`}unref(){if(this.socket==null){this.once("connect",()=>this.socket.unref());return}this.socket.unref()}flush(t){for(;this.workItems.length>0;){let r=this.workItems.shift();r.cb&&r.cb(t)}}destroy(t,r){if(typeof t=="function"&&(r=t,t={}),t=Object.assign({force:!1},t),ao&&Sh(this.id),this.socket==null){this.destroyed=!0;return}if(t.force||this.timedOut){this.socket.destroy(),this.destroyed=!0,typeof r=="function"&&r(null,null);return}this.socket.end(n=>{this.destroyed=!0,typeof r=="function"&&r(n,null)})}write(t){if(this.logger.isDebug())if(!Array.isArray(t))this.logger.debug(`writing buffer [ ${t.length} ] to ${this.address}`);else for(let r=0;r{},"noop");function m(w,O){i(w,O),i=h}s(m,"_callback");function p(w){a.resetSocketTimeout(),PS.forEach(O=>a.removeListener(O,p)),a.removeListener("message",g),w==null&&(w=new US(`runCommand failed for connection to '${a.address}'`)),a.on("error",h),m(w)}s(p,"errorHandler");function g(w){if(w.responseTo!==l.requestId)return;a.resetSocketTimeout(),PS.forEach(N=>a.removeListener(N,p)),a.removeListener("message",g),w.parse({promoteValues:!0});let O=w.documents[0];if(O.ok===0||O.$err||O.errmsg||O.code){m(new US(O));return}m(void 0,new Ck(O,this,w))}s(g,"messageHandler"),a.setSocketTimeout(u),PS.forEach(w=>a.once(w,p)),a.on("message",g),a.write(l.toBin())}};s(WS,"Connection");var jS=WS,PS=["error","close","timeout","parseError"];function Sh(e){delete yh[e],_a&&_a.deleteConnection(e)}s(Sh,"deleteConnection");function xk(e,t){yh[e]=t,_a&&_a.addConnection(e,t)}s(xk,"addConnection");function Mk(e){return function(t){ao&&Sh(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] errored out with [${JSON.stringify(t)}]`),e.emit("error",new F1(t),e)}}s(Mk,"errorHandler");function Dk(e){return function(){ao&&Sh(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new Tk(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:e.ismaster==null}),e)}}s(Dk,"timeoutHandler");function qk(e){return function(t){ao&&Sh(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new F1(`connection ${e.id} to ${e.address} closed`),e)}}s(qk,"closeHandler");function LS(e,t){let r=Ok(t);if(r.opCode!==bk){let a=r.opCode===j1?U1:L1;e.emit("message",new a(e.bson,t,r,t.slice(W1),e.responseOptions),e);return}r.fromCompressed=!0;let n=W1;r.opCode=t.readInt32LE(n),n+=4,r.length=t.readInt32LE(n),n+=4;let i=t[n];n++,Ek(i,t.slice(n),(a,u)=>{if(a){e.emit("error",a);return}if(u.length!==r.length){e.emit("error",new US("Decompressing a compressed message from the server failed. The message is corrupt."));return}let f=r.opCode===j1?U1:L1;e.emit("message",new f(e.bson,t,r,u,e.responseOptions),e)})}s(LS,"processMessage");function Pk(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){let r=e.sizeOfMessage-e.bytesRead;if(r>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=Gn.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,r),t=t.slice(r);let n=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,LS(e,n)}}else if(e.stubBuffer!=null&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){let r=Gn.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0),t.copy(r,e.stubBuffer.length),t=r,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{let r=Gn.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0),t.copy(r,e.stubBuffer.length),t=Gn.alloc(0)}else if(t.length>4){let r=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(r<0||r>e.maxBsonMessageSize){let n={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:r,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};e.emit("parseError",n,e);return}if(r>4&&rt.length)e.buffer=Gn.alloc(r),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=r,e.stubBuffer=null,t=Gn.alloc(0);else if(r>4&&re.maxBsonMessageSize){let n={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:r,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",n,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=Gn.alloc(0)}else{let n=t.slice(0,r);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(r),LS(e,n)}}else e.stubBuffer=Gn.alloc(t.length),t.copy(e.stubBuffer,0),t=Gn.alloc(0)}}s(Pk,"dataHandler");$1.exports=jS});var uo=E((oge,V1)=>{"use strict";var Lk=oo().Msg,Uk=Xr().KillCursor,jk=Xr().GetMore,wa=x().deepCopy,Wk=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),Fk=new Set(["hello","ismaster","isMaster"]),z1={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},H1={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},$k=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],$S=s(e=>e.ns.split(".")[1],"collectionName"),zk=s((e,t)=>Wk.has(e)||Fk.has(e)&&!!t.speculativeAuthenticate,"shouldRedactCommand"),Hk=s(e=>{let t;if(e instanceof jk)t={getMore:wa(e.cursorId),collection:$S(e),batchSize:e.numberToReturn};else if(e instanceof Uk)t={killCursors:$S(e),cursors:wa(e.cursorIds)};else if(e instanceof Lk)t=wa(e.command);else if(e.query&&e.query.$query){let n;e.ns==="admin.$cmd"?n=Object.assign({},e.query.$query):(n={find:$S(e)},Object.keys(z1).forEach(i=>{typeof e.query[i]<"u"&&(n[z1[i]]=wa(e.query[i]))})),Object.keys(H1).forEach(i=>{typeof e[i]<"u"&&(n[H1[i]]=wa(e[i]))}),$k.forEach(i=>{e[i]&&(n[i]=e[i])}),typeof e.pre32Limit<"u"&&(n.limit=e.pre32Limit),e.query.$explain?t={explain:n}:t=n}else t=wa(e.query||e);let r=Object.keys(t)[0];return{cmd:t,name:r,shouldRedact:zk(r,t)}},"extractCommand");V1.exports={extractCommand:Hk}});var JS=E((uge,G1)=>{"use strict";var Vk=Xr().KillCursor,Yk=Xr().GetMore,k1=x().calculateDurationInMs,YS=uo().extractCommand,Y1=s(e=>e.ns,"namespace"),kk=s(e=>e.ns.split(".")[0],"databaseName"),Gk=s(e=>e.options?`${e.options.host}:${e.options.port}`:e.address,"generateConnectionId"),Kk=s(e=>e.s&&e.queue,"isLegacyPool"),Xk=s((e,t)=>e instanceof Yk?{ok:1,cursor:{id:t.message.cursorId,ns:Y1(e),nextBatch:t.message.documents}}:e instanceof Vk?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&typeof e.query.$query<"u"?{ok:1,cursor:{id:t.message.cursorId,ns:Y1(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,"extractReply"),kS=s(e=>{if(Kk(e))return{connectionId:Gk(e)};let t=e;return{address:t.address,connectionId:t.id}},"extractConnectionDetails"),GS=class GS{constructor(t,r){let n=YS(r),i=n.name,a=kS(t);Object.assign(this,a,{requestId:r.requestId,databaseName:kk(r),commandName:i,command:n.shouldRedact?{}:n.cmd})}};s(GS,"CommandStartedEvent");var zS=GS,KS=class KS{constructor(t,r,n,i){let a=YS(r),u=a.name,f=kS(t);Object.assign(this,f,{requestId:r.requestId,commandName:u,duration:k1(i),reply:a.shouldRedact?{}:Xk(r,n)})}};s(KS,"CommandSucceededEvent");var HS=KS,XS=class XS{constructor(t,r,n,i){let a=YS(r),u=a.name,f=kS(t);Object.assign(this,f,{requestId:r.requestId,commandName:u,duration:k1(i),failure:a.shouldRedact?{}:n})}};s(XS,"CommandFailedEvent");var VS=XS;G1.exports={CommandStartedEvent:zS,CommandSucceededEvent:HS,CommandFailedEvent:VS}});var ds=E((fge,K1)=>{"use strict";var e0=class e0{constructor(t,r,n){this.connection=t,this.credentials=r,this.options=n}};s(e0,"AuthContext");var ZS=e0,t0=class t0{constructor(t){this.bson=t}prepare(t,r,n){n(void 0,t)}auth(t,r){r(new TypeError("`auth` method must be overridden by subclass"))}};s(t0,"AuthProvider");var QS=t0;K1.exports={AuthContext:ZS,AuthProvider:QS}});var i0=E((hge,J1)=>{"use strict";var X1=require("crypto"),Jk=ds().AuthProvider,n0=class n0 extends Jk{auth(t,r){let n=t.connection,i=t.credentials,a=i.username,u=i.password,f=i.source;n.command(`${f}.$cmd`,{getnonce:1},(l,h)=>{let m=null,p=null;if(l==null){m=h.result.nonce;let O=X1.createHash("md5");O.update(a+":mongo:"+u,"utf8");let N=O.digest("hex");O=X1.createHash("md5"),O.update(m+a+N,"utf8"),p=O.digest("hex")}let g={authenticate:1,user:a,nonce:m,key:p};n.command(`${f}.$cmd`,g,r)})}};s(n0,"MongoCR");var r0=n0;J1.exports=r0});var a0=E((pge,Q1)=>{"use strict";var Zk=ds().AuthProvider,o0=class o0 extends Zk{prepare(t,r,n){let i=r.credentials;Object.assign(t,{speculativeAuthenticate:Z1(i)}),n(void 0,t)}auth(t,r){let n=t.connection,i=t.credentials;if(t.response.speculativeAuthenticate)return r();n.command("$external.$cmd",Z1(i),r)}};s(o0,"X509");var s0=o0;function Z1(e){let t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.assign(t,{user:e.username}),t}s(Z1,"x509AuthenticateCommand");Q1.exports=s0});var f0=E((gge,eI)=>{"use strict";var Qk=jt().retrieveBSON,eG=ds().AuthProvider,tG=Qk(),rG=tG.Binary,c0=class c0 extends eG{auth(t,r){let n=t.connection,i=t.credentials,a=i.username,u=i.password,l={saslStart:1,mechanism:"PLAIN",payload:new rG(`\0${a}\0${u}`),autoAuthorize:1};n.command("$external.$cmd",l,r)}};s(c0,"Plain");var u0=c0;eI.exports=u0});var p0=E((Sge,rI)=>{"use strict";var nG=require("dns"),iG=ds().AuthProvider,sG=ce().retrieveKerberos,_h=X().MongoError,l0,d0=class d0 extends iG{auth(t,r){let n=t.connection,i=t.credentials;if(i==null)return r(new _h("credentials required"));let a=i.username;function u(f,l){return n.command("$external.$cmd",f,l)}s(u,"externalCommand"),oG(t,(f,l)=>{if(f)return r(f);if(l==null)return r(new _h("gssapi client missing"));l.step("",(h,m)=>{if(h)return r(h);u(aG(m),(p,g)=>{if(p)return r(p);let w=g.result;tI(l,10,w.payload,(O,N)=>{if(O)return r(O);u(uG(N,w.conversationId),(A,M)=>{if(A)return r(A);let L=M.result;cG(l,a,L.payload,(I,R)=>{if(I)return r(I);u({saslContinue:1,conversationId:L.conversationId,payload:R},(Y,W)=>{if(Y)return r(Y);r(void 0,W)})})})})})})})}};s(d0,"GSSAPI");var h0=d0;rI.exports=h0;function oG(e,t){let r=e.options.host,n=e.options.port,i=e.credentials;if(!r||!n||!i)return t(new _h(`Connection must specify: ${r?"host":""}, ${n?"port":""}, ${i?"host":"credentials"}.`));if(l0==null)try{l0=sG()}catch(h){return t(h)}let a=i.username,u=i.password,f=i.mechanismProperties,l=f.gssapiservicename||f.gssapiServiceName||"mongodb";fG(r,f,(h,m)=>{if(h)return t(h);let p={};u!=null&&Object.assign(p,{user:a,password:u}),l0.initializeClient(`${l}${process.platform==="win32"?"/":"@"}${m}`,p,(g,w)=>{if(g)return t(new _h(g));t(null,w)})})}s(oG,"makeKerberosClient");function aG(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}s(aG,"saslStart");function uG(e,t){return{saslContinue:1,conversationId:t,payload:e}}s(uG,"saslContinue");function tI(e,t,r,n){e.step(r,(i,a)=>{if(i&&t===0)return n(i);if(i)return tI(e,t-1,r,n);n(void 0,a||"")})}s(tI,"negotiate");function cG(e,t,r,n){e.unwrap(r,(i,a)=>{if(i)return n(i);e.wrap(a||"",{user:t},(u,f)=>{if(u)return n(u);n(void 0,f)})})}s(cG,"finalize");function fG(e,t,r){if(!(typeof t.gssapiCanonicalizeHostName=="boolean"?t.gssapiCanonicalizeHostName:!1))return r(void 0,e);nG.resolveCname(e,(i,a)=>{if(i)return r(i);if(Array.isArray(a)&&a.length>0)return r(void 0,a[0]);r(void 0,e)})}s(fG,"performGssapiCanonicalizeHostName")});var sI=E((wge,iI)=>{iI.exports=Ei;function Ei(e,t){if(!(this instanceof Ei))return new Ei(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?wh(this.deduplicate.length):null}s(Ei,"Pager");Ei.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}e.updated||!this.updates||(e.updated=!0,this.updates.push(e))};Ei.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e};Ei.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;lG(this,e)}pG(e,this.path);for(var r=this.pages,n=this.level;n>0;n--){var i=this.path[n],a=r[i];if(!a){if(t)return;a=r[i]=new Array(32768)}r=a}return r};Ei.prototype.get=function(e,t){var r=this._array(e,t),n=this.path[0],i=r&&r[n];return!i&&!t&&(i=r[n]=new nI(e,wh(this.pageSize)),e>=this.length&&(this.length=e+1)),i&&i.buffer===this.deduplicate&&this.deduplicate&&!t&&(i.buffer=dG(i.buffer),i.deduplicate=0),i};Ei.prototype.set=function(e,t){var r=this._array(e,!1),n=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=void 0;return}this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=r[n],a=hG(t,this.pageSize);i?i.buffer=a:r[n]=new nI(e,a)};Ei.prototype.toBuffer=function(){for(var e=new Array(this.length),t=wh(this.pageSize),r=0;rt)return e.slice(0,t);var r=wh(t);return e.copy(r),r}s(hG,"truncate");function wh(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}s(wh,"alloc");function dG(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);return e.copy(t),t}s(dG,"copy");function nI(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}s(nI,"Page");function pG(e,t){e=(e-(t[0]=e&32767))/32768,e=(e-(t[1]=e&32767))/32768,t[3]=(e-(t[2]=e&32767))/32768&32767}s(pG,"factor")});var aI=E((Oge,oI)=>{var mG=sI();oI.exports=ps;function ps(e){if(!(this instanceof ps))return new ps(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||mG(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,!yG(this.pageSize))throw new Error("The page size should be a power of two");if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var t=0;t>t)};ps.prototype.getByte=function(e){var t=e&this._pageMask,r=(e-t)/this.pageSize,n=this.pages.get(r,!0);return n?n.buffer[t+this.pageOffset]:0};ps.prototype.set=function(e,t){var r=e&7,n=(e-r)/8,i=this.getByte(n);return this.setByte(n,t?i|128>>r:i&(255^128>>r))};ps.prototype.toBuffer=function(){for(var e=gG(this.pages.length*this.pageSize),t=0;t=this.byteLength&&(this.byteLength=e+1,this.length=this.byteLength*8),this._trackUpdates&&this.pages.updated(i),!0)};function gG(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}s(gG,"alloc");function yG(e){return!(e&e-1)}s(yG,"powerOfTwo")});var fI=E((Tge,cI)=>{"use strict";var SG=require("fs"),_G=require("path"),wG=aI(),uI=SG.readFileSync(_G.resolve(__dirname,"../code-points.mem")),Nc=0;function va(){let e=uI.readUInt32BE(Nc);Nc+=4;let t=uI.slice(Nc,Nc+e);return Nc+=e,wG({buffer:t})}s(va,"read");var vG=va(),OG=va(),EG=va(),TG=va(),NG=va(),bG=va();cI.exports={unassigned_code_points:vG,commonly_mapped_to_nothing:OG,non_ASCII_space_characters:EG,prohibited_characters:TG,bidirectional_r_al:NG,bidirectional_l:bG}});var pI=E((bge,dI)=>{"use strict";var{unassigned_code_points:AG,commonly_mapped_to_nothing:CG,non_ASCII_space_characters:IG,prohibited_characters:BG,bidirectional_r_al:m0,bidirectional_l:RG}=fI();dI.exports=PG;var xG=IG,MG=CG,lI=s(e=>e.codePointAt(0),"getCodePoint"),DG=s(e=>e[0],"first"),qG=s(e=>e[e.length-1],"last");function hI(e){let t=[],r=e.length;for(let n=0;n=55296&&i<=56319&&r>n+1){let a=e.charCodeAt(n+1);if(a>=56320&&a<=57343){t.push((i-55296)*1024+a-56320+65536),n+=1;continue}}t.push(i)}return t}s(hI,"toCodePoints");function PG(e,t={}){if(typeof e!="string")throw new TypeError("Expected string.");if(e.length===0)return"";let r=hI(e).map(m=>xG.get(m)?32:m).filter(m=>!MG.get(m)),n=String.fromCodePoint.apply(null,r).normalize("NFKC"),i=hI(n);if(i.some(m=>BG.get(m)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(t.allowUnassigned!==!0&&i.some(p=>AG.get(p)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5");let u=i.some(m=>m0.get(m)),f=i.some(m=>RG.get(m));if(u&&f)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");let l=m0.get(lI(DG(n))),h=m0.get(lI(qG(n)));if(u&&!(l&&h))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return n}s(PG,"saslprep")});var bc=E((Cge,vI)=>{"use strict";var fo=require("crypto"),kt=qn().Buffer,LG=jt().retrieveBSON,co=X().MongoError,UG=ds().AuthProvider,jG=x().emitWarning,WG=LG(),g0=WG.Binary,Eh;try{Eh=pI()}catch{}var w0=class w0 extends UG{constructor(t,r){super(t),this.cryptoMethod=r||"sha1"}prepare(t,r,n){let i=this.cryptoMethod;i==="sha256"&&typeof Eh!="function"&&jG("Warning: no saslprep library specified. Passwords will not be sanitized"),fo.randomBytes(24,(a,u)=>{if(a)return n(a);Object.assign(r,{nonce:u});let f=r.credentials,l=Object.assign({},t,{speculativeAuthenticate:Object.assign(SI(i,f,u),{db:f.source})});n(void 0,l)})}auth(t,r){let n=t.response;if(n&&n.speculativeAuthenticate){_I(this.cryptoMethod,n.speculativeAuthenticate,t,r);return}FG(this.cryptoMethod,t,r)}};s(w0,"ScramSHA");var Th=w0;function gI(e){return e.replace("=","=3D").replace(",","=2C")}s(gI,"cleanUsername");function yI(e,t){return kt.concat([kt.from("n=","utf8"),kt.from(e,"utf8"),kt.from(",r=","utf8"),kt.from(t.toString("base64"),"utf8")])}s(yI,"clientFirstMessageBare");function SI(e,t,r){let n=gI(t.username);return{saslStart:1,mechanism:e==="sha1"?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new g0(kt.concat([kt.from("n,,","utf8"),yI(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}s(SI,"makeFirstMessage");function FG(e,t,r){let n=t.connection,i=t.credentials,a=t.nonce,u=i.source,f=SI(e,i,a);n.command(`${u}.$cmd`,f,(l,h)=>{let m=wI(l,h);if(m)return r(m);_I(e,h.result,t,r)})}s(FG,"executeScram");function _I(e,t,r,n){let i=r.connection,a=r.credentials,u=r.nonce,f=a.source,l=gI(a.username),h=a.password,m;if(e==="sha256")m=typeof Eh=="function"?Eh(h):h;else try{m=$G(l,h)}catch(ne){return n(ne)}let p=kt.isBuffer(t.payload)?new g0(t.payload):t.payload,g=mI(p.value()),w=parseInt(g.i,10);if(w&&w<4096){n(new co(`Server returned an invalid iteration count ${w}`),!1);return}let O=g.s,N=g.r;if(N.startsWith("nonce")){n(new co(`Server returned an invalid nonce: ${N}`),!1);return}let A=`c=biws,r=${N}`,M=kG(m,kt.from(O,"base64"),w,e),L=vh(e,M,"Client Key"),I=vh(e,M,"Server Key"),R=HG(e,L),Y=[yI(l,u),p.value().toString("base64"),A].join(","),W=vh(e,R,Y),ee=`p=${zG(L,W)}`,Ee=[A,ee].join(","),V=vh(e,I,Y),fe={saslContinue:1,conversationId:t.conversationId,payload:new g0(kt.from(Ee))};i.command(`${f}.$cmd`,fe,(ne,J)=>{let K=wI(ne,J);if(K)return n(K);let ue=J.result,me=mI(ue.payload.value());if(!GG(kt.from(me.v,"base64"),V)){n(new co("Server returned an invalid signature"));return}if(!ue||ue.done!==!1)return n(K,ue);let oe={saslContinue:1,conversationId:ue.conversationId,payload:kt.alloc(0)};i.command(`${f}.$cmd`,oe,n)})}s(_I,"continueScramConversation");function mI(e){let t={},r=e.split(",");for(let n=0;n=200&&VG(),Oh[i]=a,y0+=1,a}s(kG,"HI");function GG(e,t){if(e.length!==t.length)return!1;if(typeof fo.timingSafeEqual=="function")return fo.timingSafeEqual(e,t);let r=0;for(let n=0;n{"use strict";function KG(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}s(KG,"getDefaultAuthMechanism");var Nh=class Nh{constructor(t){t=t||{},this.username=t.username,this.password=t.password,this.source=t.source||t.db,this.mechanism=t.mechanism||"default",this.mechanismProperties=t.mechanismProperties||{},/MONGODB-AWS/i.test(this.mechanism)&&(!this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),!this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),this.mechanismProperties.AWS_SESSION_TOKEN==null&&process.env.AWS_SESSION_TOKEN!=null&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(t){return this.mechanism===t.mechanism&&this.username===t.username&&this.password===t.password&&this.source===t.source}resolveAuthMechanism(t){return/DEFAULT/i.test(this.mechanism)?new Nh({username:this.username,password:this.password,source:this.source,mechanism:KG(t),mechanismProperties:this.mechanismProperties}):this}};s(Nh,"MongoCredentials");var E0=Nh;OI.exports={MongoCredentials:E0}});var NI=E((xge,TI)=>{"use strict";var XG=ds().AuthProvider,JG=T0().MongoCredentials,lo=X().MongoError,ZG=require("crypto"),QG=require("http"),eK=ce().maxWireVersion,tK=require("url"),b0;try{b0=require("aws4")}catch{}var rK=110,nK="http://169.254.170.2",N0="http://169.254.169.254",EI="/latest/meta-data/iam/security-credentials",C0=class C0 extends XG{auth(t,r){let n=t.connection,i=t.credentials;if(eK(n)<9){r(new lo("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));return}if(b0==null){r(new lo("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));return}if(i.username==null){iK(i,(p,g)=>{if(p)return r(p);t.credentials=g,this.auth(t,r)});return}let a=i.source,u=this.bson,f=i.username,l=i.password,h=i.mechanismProperties.AWS_SESSION_TOKEN,m=f&&l&&h?{accessKeyId:f,secretAccessKey:l,sessionToken:h}:f&&l?{accessKeyId:f,secretAccessKey:l}:void 0;ZG.randomBytes(32,(p,g)=>{if(p){r(p);return}let w={saslStart:1,mechanism:"MONGODB-AWS",payload:u.serialize({r:g,p:rK})};n.command(`${a}.$cmd`,w,(O,N)=>{if(O)return r(O);let A=N.result,M=u.deserialize(A.payload.buffer),L=M.h,I=M.s.buffer;if(I.length!==64){r(new lo(`Invalid server nonce length ${I.length}, expected 64`));return}if(I.compare(g,0,g.length,0,g.length)!==0){r(new lo("Server nonce does not begin with client nonce"));return}if(L.length<1||L.length>255||L.indexOf("..")!==-1){r(new lo(`Server returned an invalid host: "${L}"`));return}let R="Action=GetCallerIdentity&Version=2011-06-15",Y=b0.sign({method:"POST",host:L,region:sK(M.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":R.length,"X-MongoDB-Server-Nonce":I.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:R},m),W=Y.headers.Authorization,ee=Y.headers["X-Amz-Date"],Ee={a:W,d:ee};h&&(Ee.t=h);let V={saslContinue:1,conversationId:1,payload:u.serialize(Ee)};n.command(`${a}.$cmd`,V,fe=>{if(fe)return r(fe);r()})})})}};s(C0,"MongoDBAWS");var A0=C0;function iK(e,t){function r(n){if(n.AccessKeyId==null||n.SecretAccessKey==null||n.Token==null){t(new lo("Could not obtain temporary MONGODB-AWS credentials"));return}t(void 0,new JG({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}}))}if(s(r,"done"),process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI){bh(`${nK}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,void 0,(n,i)=>{if(n)return t(n);r(i)});return}bh(`${N0}/latest/api/token`,{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(n,i)=>{if(n)return t(n);bh(`${N0}/${EI}`,{json:!1,headers:{"X-aws-ec2-metadata-token":i}},(a,u)=>{if(a)return t(a);bh(`${N0}/${EI}/${u}`,{headers:{"X-aws-ec2-metadata-token":i}},(f,l)=>{if(f)return t(f);r(l)})})})}s(iK,"makeTempCredentials");function sK(e){let t=e.split(".");return t.length===1||t[1]==="amazonaws"?"us-east-1":t[1]}s(sK,"deriveRegion");function bh(e,t,r){t=Object.assign({method:"GET",timeout:1e4,json:!0},tK.parse(e),t);let n=QG.request(t,i=>{i.setEncoding("utf8");let a="";i.on("data",u=>a+=u),i.on("end",()=>{if(t.json===!1){r(void 0,a);return}try{let u=JSON.parse(a);r(void 0,u)}catch{r(new lo(`Invalid JSON response: "${a}"`))}})});n.on("error",i=>r(i)),n.end()}s(bh,"request");TI.exports=A0});var I0=E((Dge,bI)=>{"use strict";var oK=i0(),aK=a0(),uK=f0(),cK=p0(),fK=bc().ScramSHA1,lK=bc().ScramSHA256,hK=NI();function dK(e){return{"mongodb-aws":new hK(e),mongocr:new oK(e),x509:new aK(e),plain:new uK(e),gssapi:new cK(e),"scram-sha-1":new fK(e),"scram-sha-256":new lK(e)}}s(dK,"defaultAuthProviders");bI.exports={defaultAuthProviders:dK}});var Ih=E((Pge,xI)=>{"use strict";var II=require("net"),pK=require("tls"),BI=FS(),Ac=X().MongoError,Ah=X().MongoNetworkError,mK=X().MongoNetworkTimeoutError,gK=I0().defaultAuthProviders,yK=ds().AuthContext,Ch=bS(),SK=ce().makeClientMetadata,AI=Ch.MAX_SUPPORTED_WIRE_VERSION,_K=Ch.MAX_SUPPORTED_SERVER_VERSION,CI=Ch.MIN_SUPPORTED_WIRE_VERSION,wK=Ch.MIN_SUPPORTED_SERVER_VERSION,Oa;function vK(e,t,r){typeof t=="function"&&(r=t,t=void 0);let n=e&&e.connectionType?e.connectionType:BI;Oa==null&&(Oa=gK(e.bson));let i=e.family!==void 0?e.family:0;CK(i,e,t,(a,u)=>{if(a){r(a,u);return}TK(new n(u,e),e,r)})}s(vK,"connect");function OK(e){return!(e instanceof BI)}s(OK,"isModernConnectionType");function EK(e,t){let r=e&&typeof e.maxWireVersion=="number"&&e.maxWireVersion>=CI,n=e&&typeof e.minWireVersion=="number"&&e.minWireVersion<=AI;if(r){if(n)return null;let a=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${AI} (MongoDB ${_K})`;return new Ac(a)}let i=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${CI} (MongoDB ${wK})`;return new Ac(i)}s(EK,"checkSupportedServer");function TK(e,t,r){let n=s(function(u,f){u&&e&&e.destroy(),r(u,f)},"callback"),i=t.credentials;if(i&&!i.mechanism.match(/DEFAULT/i)&&!Oa[i.mechanism]){n(new Ac(`authMechanism '${i.mechanism}' not supported`));return}let a=new yK(e,i,t);NK(a,(u,f)=>{if(u)return n(u);let l=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(l.socketTimeout=t.connectTimeoutMS||t.connectionTimeout),f.helloOk=!!t.useUnifiedTopology;let h=new Date().getTime();e.command("admin.$cmd",f,l,(m,p)=>{if(m){n(m);return}let g=p.result;if(g.ok===0){n(new Ac(g));return}"isWritablePrimary"in g&&(g.ismaster=g.isWritablePrimary),t.useUnifiedTopology&&g.helloOk&&(e.helloOk=!0);let w=EK(g,t);if(w){n(w);return}if(!OK(e)&&g.compression){let O=f.compression.filter(N=>g.compression.indexOf(N)!==-1);O.length&&(e.agreedCompressor=O[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=g,e.lastIsMasterMS=new Date().getTime()-h,!g.arbiterOnly&&i){Object.assign(a,{response:g});let O=i.resolveAuthMechanism(g);Oa[O.mechanism].auth(a,A=>{if(A)return n(A);n(void 0,e)});return}n(void 0,e)})})}s(TK,"performInitialHandshake");function NK(e,t){let r=e.options,n=e.connection.serverApi,i=r.compression&&r.compression.compressors?r.compression.compressors:[],a={[n?"hello":"ismaster"]:!0,client:r.metadata||SK(r),compression:i},u=e.credentials;if(u){if(u.mechanism.match(/DEFAULT/i)&&u.username){Object.assign(a,{saslSupportedMechs:`${u.source}.${u.username}`}),Oa["scram-sha-256"].prepare(a,e,t);return}let f=Oa[u.mechanism];if(f==null)return t(new Ac(`No AuthProvider for ${u.mechanism} defined.`));f.prepare(a,e,t);return}t(void 0,a)}s(NK,"prepareHandshakeDocument");var bK=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function RI(e,t){let r=typeof t.host=="string"?t.host:"localhost";return r.indexOf("/")!==-1?{path:r}:{family:e,host:r,port:typeof t.port=="number"?t.port:27017,rejectUnauthorized:!1}}s(RI,"parseConnectOptions");function AK(e,t){let r=RI(e,t);for(let n in t)t[n]!=null&&bK.indexOf(n)!==-1&&(r[n]=t[n]);return t.checkServerIdentity===!1?r.checkServerIdentity=function(){}:typeof t.checkServerIdentity=="function"&&(r.checkServerIdentity=t.checkServerIdentity),r.servername==null&&!II.isIP(r.host)&&(r.servername=r.host),r}s(AK,"parseSslOptions");var B0=new Set(["error","close","timeout","parseError"]);function CK(e,t,r,n){let i=typeof t.ssl=="boolean"?t.ssl:!1,a=typeof t.keepAlive=="boolean"?t.keepAlive:!0,u=typeof t.keepAliveInitialDelay=="number"?t.keepAliveInitialDelay:12e4,f=typeof t.noDelay=="boolean"?t.noDelay:!0,l=typeof t.connectionTimeout=="number"?t.connectionTimeout:typeof t.connectTimeoutMS=="number"?t.connectTimeoutMS:3e4,h=typeof t.socketTimeoutMS=="number"?t.socketTimeoutMS:typeof t.socketTimeout=="number"?t.socketTimeout:0,m=typeof t.rejectUnauthorized=="boolean"?t.rejectUnauthorized:!0;u>h&&(u=Math.round(h/2));let p,g=s(function(M,L){M&&p&&p.destroy(),n(M,L)},"callback");try{i?(p=pK.connect(AK(e,t)),typeof p.disableRenegotiation=="function"&&p.disableRenegotiation()):p=II.createConnection(RI(e,t))}catch(M){return g(M)}p.setKeepAlive(a,u),p.setTimeout(l),p.setNoDelay(f);let w=i?"secureConnect":"connect",O;function N(M){return L=>{B0.forEach(I=>p.removeAllListeners(I)),O&&r.removeListener("cancel",O),p.removeListener(w,A),g(IK(M,L))}}s(N,"errorHandler");function A(){if(B0.forEach(M=>p.removeAllListeners(M)),O&&r.removeListener("cancel",O),p.authorizationError&&m)return g(p.authorizationError);p.setTimeout(h),g(null,p)}s(A,"connectHandler"),B0.forEach(M=>p.once(M,N(M))),r&&(O=N("cancel"),r.once("cancel",O)),p.once(w,A)}s(CK,"makeConnection");function IK(e,t){switch(e){case"error":return new Ah(t);case"timeout":return new mK("connection timed out");case"close":return new Ah("connection closed");case"cancel":return new Ah("connection establishment was cancelled");default:return new Ah("unknown network error")}}s(IK,"connectionFailureError");xI.exports=vK});var ho=E((Uge,MI)=>{"use strict";var Ea=class Ea{constructor(t){t!=null&&(this.level=t)}static fromOptions(t){if(t!=null){if(t.readConcern)return t.readConcern instanceof Ea?t.readConcern:new Ea(t.readConcern.level);if(t.level)return new Ea(t.level)}}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}};s(Ea,"ReadConcern");var R0=Ea;MI.exports=R0});var Ta=E((Wge,PI)=>{"use strict";var DI=X().MongoError,BK=Vt(),RK=ho(),xK=wi(),ms,qI;(()=>{let e="NO_TRANSACTION",t="STARTING_TRANSACTION",r="TRANSACTION_IN_PROGRESS",n="TRANSACTION_COMMITTED",i="TRANSACTION_COMMITTED_EMPTY",a="TRANSACTION_ABORTED";ms={NO_TRANSACTION:e,STARTING_TRANSACTION:t,TRANSACTION_IN_PROGRESS:r,TRANSACTION_COMMITTED:n,TRANSACTION_COMMITTED_EMPTY:i,TRANSACTION_ABORTED:a},qI={[e]:[e,t],[t]:[r,n,i,a],[r]:[r,n,a],[n]:[n,i,t,e],[a]:[t,e],[i]:[i,e]}})();var M0=class M0{constructor(t){t=t||{},this.state=ms.NO_TRANSACTION,this.options={};let r=xK.fromOptions(t);if(r){if(r.w<=0)throw new DI("Transactions do not support unacknowledged write concern");this.options.writeConcern=r}t.readConcern&&(this.options.readConcern=RK.fromOptions(t)),t.readPreference&&(this.options.readPreference=BK.fromOptions(t)),t.maxCommitTimeMS&&(this.options.maxTimeMS=t.maxCommitTimeMS),this._pinnedServer=void 0,this._recoveryToken=void 0}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return[ms.STARTING_TRANSACTION,ms.TRANSACTION_IN_PROGRESS].indexOf(this.state)!==-1}transition(t){let r=qI[this.state];if(r&&r.indexOf(t)!==-1){this.state=t,(this.state===ms.NO_TRANSACTION||this.state===ms.STARTING_TRANSACTION||this.state===ms.TRANSACTION_ABORTED)&&this.unpinServer();return}throw new DI(`Attempted illegal state transition from [${this.state}] to [${t}]`)}pinServer(t){this.isActive&&(this._pinnedServer=t)}unpinServer(){this._pinnedServer=void 0}};s(M0,"Transaction");var x0=M0;function MK(e){return!!(e.commitTransaction||e.abortTransaction)}s(MK,"isTransactionCommand");PI.exports={TxnState:ms,Transaction:x0,isTransactionCommand:MK}});var vt=E(($ge,zI)=>{"use strict";var DK=ro().MONGODB_ERROR_CODES,qK=Vt(),Bh=tr().TopologyType,UI=X().MongoError,PK=X().isRetryableWriteError,LK=ce().maxWireVersion,UK=X().MongoNetworkError,jK=DK.IllegalOperation;function D0(e,t,r){e.listeners(t).length>0&&e.emit(t,r)}s(D0,"emitSDAMEvent");function WK(e){return!e.compression||!e.compression.compressors?[]:(e.compression.compressors.forEach(function(t){if(t!=="snappy"&&t!=="zlib")throw new Error("compressors must be at least one of snappy or zlib")}),e.compression.compressors)}s(WK,"createCompressionInfo");function FK(e){return JSON.parse(JSON.stringify(e))}s(FK,"clone");var $K=s(function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},"getPreviousDescription"),jI=s(function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:$K(e),newDescription:t}),e.s.serverDescription=t)},"emitServerDescriptionChanged"),zK=s(function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},"getPreviousTopologyDescription"),HK=s(function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:zK(e),newDescription:t}),e.s.serverDescription=t)},"emitTopologyDescriptionChanged"),VK=s(function(e,t,r){var n=Rh(e,t),i=Rh(e,r);return i!==n},"changedIsMaster"),Rh=s(function(e,t){return t||(t=e.ismaster),t?t.ismaster&&t.msg==="isdbgrid"?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},"getTopologyType"),WI=s(function(e){return function(t){if(e.s.state!=="destroyed"){var r=new Date().getTime();D0(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},function(n,i){if(n)D0(e,"serverHeartbeatFailed",{durationMS:a,failure:n,connectionId:e.name});else{e.emit("ismaster",i,e);var a=new Date().getTime()-r;D0(e,"serverHeartbeatSucceeded",{durationMS:a,reply:i.result,connectionId:e.name}),VK(e,e.s.ismaster,i.result)&&jI(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?Rh(e):"Standalone"}),e.s.ismaster=i.result,e.s.isMasterLatencyMS=a}if(typeof t=="function")return t(n,i);e.s.inquireServerStateTimeout=setTimeout(WI(e),e.s.haInterval)})}}},"inquireServerState"),YK=s(function(e){var t={};for(var r in e)t[r]=e[r];return t},"cloneOptions");function kK(e,t){var r=!1;this.start=function(){return this.isRunning()||(r=setInterval(e,t)),this},this.stop=function(){return clearInterval(r),r=!1,this},this.isRunning=function(){return r!==!1}}s(kK,"Interval");function GK(e,t){var r=!1,n=s(()=>{r&&(clearTimeout(r),r=!1,e())},"func");this.start=function(){return this.isRunning()||(r=setTimeout(n,t)),this},this.stop=function(){return clearTimeout(r),r=!1,this},this.isRunning=function(){return r!==!1}}s(GK,"Timeout");function KK(e,t){var r={servers:[]};e||(e={servers:[]});for(var n=0;n{typeof t=="function"&&t()})}};function FI(e){return e.description?e.description.type:e.type==="mongos"?Bh.Sharded:e.type==="replset"?Bh.ReplicaSetWithPrimary:Bh.Single}s(FI,"topologyType");var ZK=6,$I=s(function(e){return!(e.lastIsMaster().maxWireVersion{"use strict";var t5=jt().retrieveBSON,r5=require("events"),GI=t5(),HI=GI.Binary,n5=ce().uuidV4,Pn=X().MongoError,i5=X().isRetryableError,s5=X().isRetryableEndTransactionError,o5=X().MongoNetworkError,a5=X().MongoWriteConcernError,VI=Ta().Transaction,Ot=Ta().TxnState,u5=ce().isPromiseLike,c5=Vt(),q0=x().maybePromise,f5=Ta().isTransactionCommand,l5=vt().resolveClusterTime,h5=et().isSharded,d5=ce().maxWireVersion,L0=x().now,KI=x().calculateDurationInMs,p5=8;function XI(e,t){if(e.serverSession==null){let r=new Pn("Cannot use a session that has ended");if(typeof t=="function")return t(r,null),!1;throw r}return!0}s(XI,"assertAlive");var Cc=Symbol("serverSession"),Dh=class Dh extends r5{constructor(t,r,n,i){if(super(),t==null)throw new Error("ClientSession requires a topology");if(r==null||!(r instanceof Mh))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},i=i||{},this.topology=t,this.sessionPool=r,this.hasEnded=!1,this.clientOptions=i,this[Cc]=void 0,this.supports={causalConsistency:typeof n.causalConsistency<"u"?n.causalConsistency:!0},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new VI}get id(){return this.serverSession.id}get serverSession(){return this[Cc]==null&&(this[Cc]=this.sessionPool.acquire()),this[Cc]}endSession(t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=this;return q0(this,r,i=>{if(n.hasEnded)return i();function a(){n.sessionPool.release(n.serverSession),n[Cc]=void 0,n.hasEnded=!0,n.emit("ended",n),i()}if(s(a,"completeEndSession"),n.serverSession&&n.inTransaction()){n.abortTransaction(u=>{if(u)return i(u);a()});return}a()})}advanceOperationTime(t){if(this.operationTime==null){this.operationTime=t;return}t.greaterThan(this.operationTime)&&(this.operationTime=t)}equals(t){return t instanceof Dh?this.id.id.buffer.equals(t.id.id.buffer):!1}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(t){if(XI(this),this.inTransaction())throw new Pn("Transaction already in progress");let r=d5(this.topology);if(h5(this.topology)&&r!=null&&rkI(this,"commitTransaction",r))}abortTransaction(t){return q0(this,t,r=>kI(this,"abortTransaction",r))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(t,r){let n=L0();return U0(this,n,t,r)}};s(Dh,"ClientSession");var P0=Dh,JI=12e4,m5=100,g5=79,YI=50,y5=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function ZI(e,t){return KI(e){if(i instanceof Pn&&ZI(t,JI)&&!qh(i)){if(i.hasErrorLabel("UnknownTransactionCommitResult"))return QI(e,t,r,n);if(i.hasErrorLabel("TransientTransactionError"))return U0(e,t,r,n)}throw i})}s(QI,"attemptTransactionCommit");var _5=new Set([Ot.NO_TRANSACTION,Ot.TRANSACTION_COMMITTED,Ot.TRANSACTION_ABORTED]);function w5(e){return _5.has(e.transaction.state)}s(w5,"userExplicitlyEndedTransaction");function U0(e,t,r,n){e.startTransaction(n);let i;try{i=r(e)}catch(a){i=Promise.reject(a)}if(!u5(i))throw e.abortTransaction(),new TypeError("Function provided to `withTransaction` must return a Promise");return i.then(()=>{if(!w5(e))return QI(e,t,r,n)}).catch(a=>{function u(f){if(f instanceof Pn&&f.hasErrorLabel("TransientTransactionError")&&ZI(t,JI))return U0(e,t,r,n);throw qh(f)&&f.addErrorLabel("UnknownTransactionCommitResult"),f}return s(u,"maybeRetryOrThrow"),e.transaction.isActive?e.abortTransaction().then(()=>u(a)):u(a)})}s(U0,"attemptTransaction");function kI(e,t,r){if(!XI(e,r))return;let n=e.transaction.state;if(n===Ot.NO_TRANSACTION){r(new Pn("No transaction started"));return}if(t==="commitTransaction"){if(n===Ot.STARTING_TRANSACTION||n===Ot.TRANSACTION_COMMITTED_EMPTY){e.transaction.transition(Ot.TRANSACTION_COMMITTED_EMPTY),r(null,null);return}if(n===Ot.TRANSACTION_ABORTED){r(new Pn("Cannot call commitTransaction after calling abortTransaction"));return}}else{if(n===Ot.STARTING_TRANSACTION){e.transaction.transition(Ot.TRANSACTION_ABORTED),r(null,null);return}if(n===Ot.TRANSACTION_ABORTED){r(new Pn("Cannot call abortTransaction twice"));return}if(n===Ot.TRANSACTION_COMMITTED||n===Ot.TRANSACTION_COMMITTED_EMPTY){r(new Pn("Cannot call abortTransaction after calling commitTransaction"));return}}let i={[t]:1},a;e.transaction.options.writeConcern?a=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(a={w:e.clientOptions.w}),n===Ot.TRANSACTION_COMMITTED&&(a=Object.assign({wtimeout:1e4},a,{w:"majority"})),a&&Object.assign(i,{writeConcern:a}),t==="commitTransaction"&&e.transaction.options.maxTimeMS&&Object.assign(i,{maxTimeMS:e.transaction.options.maxTimeMS});function u(l,h){t==="commitTransaction"?(e.transaction.transition(Ot.TRANSACTION_COMMITTED),l&&(l instanceof o5||l instanceof a5||i5(l)||qh(l)?S5(l)&&(l.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer()):l.hasErrorLabel("TransientTransactionError")&&e.transaction.unpinServer())):e.transaction.transition(Ot.TRANSACTION_ABORTED),r(l,h)}s(u,"commandHandler");function f(l){return t==="commitTransaction"?l:null}s(f,"transactionError"),e.transaction.recoveryToken&&v5(e)&&(i.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",i,{session:e},(l,h)=>{if(l&&s5(l))return i.commitTransaction&&(e.transaction.unpinServer(),i.writeConcern=Object.assign({wtimeout:1e4},i.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",i,{session:e},(m,p)=>u(f(m),p));u(f(l),h)})}s(kI,"endTransaction");function v5(e){return!!e.topology.s.options.useRecoveryToken}s(v5,"supportsRecoveryToken");var j0=class j0{constructor(){this.id={id:new HI(n5(),HI.SUBTYPE_UUID)},this.lastUse=L0(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(t){return Math.round(KI(this.lastUse)%864e5%36e5/6e4)>t-1}};s(j0,"ServerSession");var xh=j0,W0=class W0{constructor(t){if(t==null)throw new Error("ServerSessionPool requires a topology");this.topology=t,this.sessions=[]}endAllPooledSessions(t){if(this.sessions.length){this.topology.endSessions(this.sessions.map(r=>r.id),()=>{this.sessions=[],typeof t=="function"&&t()});return}typeof t=="function"&&t()}acquire(){let t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){let r=this.sessions.shift();if(!r.hasTimedOut(t))return r}return new xh}release(t){let r=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length&&this.sessions[this.sessions.length-1].hasTimedOut(r);)this.sessions.pop();if(!t.hasTimedOut(r)){if(t.isDirty)return;this.sessions.unshift(t)}}};s(W0,"ServerSessionPool");var Mh=W0;function eB(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch||e.mapReduce&&t&&t.out&&(t.out.inline===1||t.out==="inline"))}s(eB,"commandSupportsReadConcern");function O5(e,t,r){if(e.hasEnded)return new Pn("Cannot use a session that has ended");if(r&&r.writeConcern&&r.writeConcern.w===0)return;let n=e.serverSession;n.lastUse=L0(),t.lsid=n.id;let i=e.inTransaction()||f5(t),a=r.willRetryWrite,u=eB(t,r);if(n.txnNumber&&(a||i)&&(t.txnNumber=GI.Long.fromNumber(n.txnNumber)),!i){e.transaction.state!==Ot.NO_TRANSACTION&&e.transaction.transition(Ot.NO_TRANSACTION),e.supports.causalConsistency&&e.operationTime&&u&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}));return}if(r.readPreference&&!r.readPreference.equals(c5.primary))return new Pn(`Read preference in a transaction must be primary, not: ${r.readPreference.mode}`);if(t.autocommit=!1,e.transaction.state===Ot.STARTING_TRANSACTION){e.transaction.transition(Ot.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;let f=e.transaction.options.readConcern||e.clientOptions.readConcern;f&&(t.readConcern=f),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}}s(O5,"applySession");function E5(e,t){t.$clusterTime&&l5(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)}s(E5,"updateSessionFromResponse");tB.exports={ClientSession:P0,ServerSession:xh,ServerSessionPool:Mh,TxnState:Ot,applySession:O5,updateSessionFromResponse:E5,commandSupportsReadConcern:eB}});var hB=E((Yge,lB)=>{"use strict";var T5=require("util").inherits,z0=require("events").EventEmitter,gn=X().MongoError,N5=X().MongoTimeoutError,b5=X().MongoWriteConcernError,A5=mn(),C5=require("util").format,I5=oo().Msg,B5=gh(),F0=et().MESSAGE_HEADER_SIZE,rB=et().COMPRESSION_DETAILS_SIZE,R5=et().opcodes,x5=vi().compress,M5=vi().compressorIDs,D5=vi().uncompressibleCommands,Ph=JS(),$0=qn().Buffer,q5=Ih(),P5=gs().updateSessionFromResponse,sB=ce().eachAsync,L5=ce().makeStateMachine,U5=x().now,Ss="disconnected",Na="connecting",Ic="connected",ys="draining",Zr="destroying",wr="destroyed",ba=L5({[Ss]:[Na,ys,Ss],[Na]:[Na,Ic,ys,Ss],[Ic]:[Ic,Ss,ys],[ys]:[ys,Zr,wr],[Zr]:[Zr,wr],[wr]:[wr]}),oB=new Set(["error","close","timeout","parseError","connect","message"]),j5=0,It=s(function(e,t){if(z0.call(this),this.topology=e,this.s={state:Ss,cancellationToken:new z0},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=j5++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&(typeof t.bson.serialize!="function"||typeof t.bson.deserialize!="function"))throw new Error("must pass in valid bson parser");this.logger=A5("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;let r=this;this._messageHandler=W5(this),this._connectionCloseHandler=function(n){Lh(r,"close",n,this)},this._connectionErrorHandler=function(n){Lh(r,"error",n,this)},this._connectionTimeoutHandler=function(n){Lh(r,"timeout",n,this)},this._connectionParseErrorHandler=function(n){Lh(r,"parseError",n,this)}},"Pool");T5(It,z0);Object.defineProperty(It.prototype,"size",{enumerable:!0,get:function(){return this.options.size}});Object.defineProperty(It.prototype,"minSize",{enumerable:!0,get:function(){return this.options.minSize}});Object.defineProperty(It.prototype,"connectionTimeout",{enumerable:!0,get:function(){return this.options.connectionTimeout}});Object.defineProperty(It.prototype,"socketTimeout",{enumerable:!0,get:function(){return this.options.socketTimeout}});Object.defineProperty(It.prototype,"state",{enumerable:!0,get:function(){return this.s.state}});function aB(e){e.inUseConnections=[],e.availableConnections=[],e.connectingConnections=0,e.executing=!1,e.numberOfConsecutiveTimeouts=0,e.connectionIndex=0,e.retriesLeft=e.options.reconnectTries,e.reconnectId=null}s(aB,"resetPoolState");function Lh(e,t,r,n){if(n){if(n._connectionFailHandled)return;n._connectionFailHandled=!0,n.destroy(),H0(e,n),n.flush(r)}if(t==="timeout"&&(e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1,e.numberOfConsecutiveTimeouts>e.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);e.socketCount()===0&&(e.state!==wr&&e.state!==Zr&&e.state!==ys&&e.options.reconnect&&ba(e,Ss),t=t==="error"?"close":t,e.emit(t,r)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=r,e.reconnectId=setTimeout(uB(e),e.options.reconnectInterval)),fB(e){r==null&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),typeof t=="function"&&t(r,n)})}}s(uB,"attemptReconnect");function cB(e,t,r){var n=t.indexOf(e);n!==-1&&(t.splice(n,1),r.push(e))}s(cB,"moveConnectionBetween");function W5(e){return function(t,r){for(var n=null,i=0;i{if(t){if(typeof e=="function"){this.destroy(),e(t);return}this.state===Na&&this.emit("error",t),this.destroy();return}if(ba(this,Ic),this.minSize)for(let n=0;n{for(let u of oB)i.removeAllListeners(u);i.on("error",()=>{}),i.destroy(r,a)},i=>{if(i){typeof n=="function"&&n(i,null);return}aB(e),e.queue=[],ba(e,wr),typeof n=="function"&&n(null,null)})}s(nB,"destroy");It.prototype.destroy=function(e,t){var r=this;if(typeof e=="function"&&(t=e,e=!1),this.state===wr||r.state===Zr){typeof t=="function"&&t(null,null);return}if(ba(this,ys),e){for(var n=r.availableConnections.concat(r.inUseConnections);r.queue.length>0;){var i=r.queue.shift();typeof i.cb=="function"&&i.cb(new gn("Pool was force destroyed"))}return nB(r,n,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId);function a(){if(r.state===wr||r.state===Zr){typeof t=="function"&&t();return}if(Uh(r.queue),r.queue.length===0){for(var u=r.availableConnections.concat(r.inUseConnections),f=0;f0)return setTimeout(a,1);nB(r,u,{force:!1},t)}else Aa(r)(),setTimeout(a,1)}s(a,"checkStatus"),a()};It.prototype.reset=function(e){if(this.s.state!==Ic){typeof e=="function"&&e(new gn("pool is not connected, reset aborted"));return}this.s.cancellationToken.emit("cancel");let t=this.availableConnections.concat(this.inUseConnections);sB(t,(r,n)=>{for(let i of oB)r.removeAllListeners(i);r.destroy({force:!0},n)},r=>{if(r&&typeof e=="function"){e(r,null);return}aB(this),_s(this,()=>{typeof e=="function"&&e(null,null)})})};function F5(e,t,r){let n=t.toBin();if(!!!e.options.agreedCompressor||!$5(t))return r(null,n);let a=$0.concat(n),u=a.slice(F0),f=a.readInt32LE(12);x5(e,u,function(l,h){if(l)return r(l,null);let m=$0.alloc(F0);m.writeInt32LE(F0+rB+h.length,0),m.writeInt32LE(t.requestId,4),m.writeInt32LE(0,8),m.writeInt32LE(R5.OP_COMPRESSED,12);let p=$0.alloc(rB);return p.writeInt32LE(f,0),p.writeInt32LE(u.length,4),p.writeUInt8(M5[e.options.agreedCompressor],8),r(null,[m,p,h])})}s(F5,"serializeCommand");It.prototype.write=function(e,t,r){var n=this;if(typeof t=="function"&&(r=t),t=t||{},typeof r!="function"&&!t.noResponse)throw new gn("write method must provide a callback");if(this.state===wr||this.state===Zr){r(new gn("pool destroyed"));return}if(this.state===ys){r(new gn("pool is draining, new operations prohibited"));return}if(this.options.domainsEnabled&&process.domain&&typeof r=="function"){var i=r;r=process.domain.bind(function(){for(var u=new Array(arguments.length),f=0;f{u?n.emit("commandFailed",new Ph.CommandFailedEvent(this,e,u,a.started)):f&&f.result&&(f.result.ok===0||f.result.$err)?n.emit("commandFailed",new Ph.CommandFailedEvent(this,e,f.result,a.started)):n.emit("commandSucceeded",new Ph.CommandSucceededEvent(this,e,f,a.started)),typeof r=="function"&&r(u,f)}),F5(n,e,(u,f)=>{if(u)throw u;a.buffer=f,t.monitoring?n.queue.unshift(a):n.queue.push(a),n.executing||process.nextTick(function(){Aa(n)()})})};function $5(e){let t=e instanceof I5?e.command:e.query,r=Object.keys(t)[0];return!D5.has(r)}s($5,"canCompress");function iB(e,t){for(var r=0;r{if(e.connectingConnections--,r){if(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(r)}]`),!e.reconnectId&&e.options.reconnect){if(e.state===Na&&e.options.legacyCompatMode){t(r);return}e.reconnectError=r,e.reconnectId=setTimeout(uB(e,t),e.options.reconnectInterval);return}typeof t=="function"&&t(r);return}if(e.state===wr||e.state===Zr){typeof t=="function"&&t(new gn("Pool was destroyed after connection creation")),n.destroy();return}n.on("error",e._connectionErrorHandler),n.on("close",e._connectionCloseHandler),n.on("timeout",e._connectionTimeoutHandler),n.on("parseError",e._connectionParseErrorHandler),n.on("message",e._messageHandler),e.availableConnections.push(n),typeof t=="function"&&t(null,n),Aa(e)()})}s(_s,"createConnection");function Uh(e){for(var t=0;t0){e.executing=!1;return}for(;;){let u=fB(e);if(e.availableConnections.length===0){Uh(e.queue),u0&&_s(e);break}if(e.queue.length===0)break;var t=null;let f=e.availableConnections.filter(l=>l.workItems.length===0);if(f.length===0?t=e.availableConnections[e.connectionIndex++%e.availableConnections.length]:t=f[e.connectionIndex++%f.length],!t.isConnected()){H0(e,t),Uh(e.queue);break}var r=e.queue.shift();if(r.monitoring){var n=!1;for(let l=0;l0&&_s(e),setTimeout(()=>Aa(e)(),10);break}}if(u0){e.queue.unshift(r),_s(e);break}var i=r.buffer;r.monitoring&&cB(t,e.availableConnections,e.inUseConnections),r.noResponse||t.workItems.push(r),!r.immediateRelease&&typeof r.socketTimeout=="number"&&t.setSocketTimeout(r.socketTimeout);var a=!0;if(Array.isArray(i))for(let l=0;l{"use strict";var z5=Xr().Query,H5=oo().Msg,V0=X().MongoError,V5=et().getReadPreference,Y5=et().isSharded,k5=et().databaseNamespace,G5=Ta().isTransactionCommand,K5=gs().applySession,X5=X().MongoNetworkError,dB=ce().maxWireVersion;function J5(e){return dB(e)&&e.autoEncrypter}s(J5,"isClientEncryptionEnabled");function Z5(e,t,r,n,i){if(typeof n=="function"&&(i=n,n={}),n=n||{},r==null)return i(new V0(`command ${JSON.stringify(r)} does not return a cursor`));if(!J5(e)){pB(e,t,r,n,i);return}let a=dB(e);if(typeof a!="number"||a<8){i(new V0("Auto-encryption requires a minimum MongoDB version of 4.2"));return}t7(e,t,r,n,i)}s(Z5,"command");function pB(e,t,r,n,i){let a=e.s.bson,u=e.s.pool,f=V5(r,n),l=e7(e),h=n.session,m=e.clusterTime,p=m,g=Object.assign({},r),w=n.serverApi;if(w&&(g.apiVersion=w.version||w,w.strict!=null&&(g.apiStrict=w.strict),w.deprecationErrors!=null&&(g.apiDeprecationErrors=w.deprecationErrors)),Q5(e)&&h){let I=h.clusterTime;m&&m.clusterTime&&I&&I.clusterTime&&I.clusterTime.greaterThan(m.clusterTime)&&(p=I),!h.transaction.isActive&&h.transaction.isPinned&&!g.startTransaction&&!g.commitTransaction&&h.transaction.unpinServer();let R=K5(h,g,n);if(R)return i(R)}p&&(g.$clusterTime=p),Y5(e)&&!l&&f&&f.mode!=="primary"&&(g={$query:g,$readPreference:f.toJSON()});let O=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},n);O.slaveOk=f.slaveOk();let N=`${k5(t)}.$cmd`,A=l?new H5(a,N,g,O):new z5(a,N,g,O),L=h&&(h.inTransaction()||G5(g))?function(I){return I&&I instanceof X5&&!I.hasErrorLabel("TransientTransactionError")&&I.addErrorLabel("TransientTransactionError"),!r.commitTransaction&&I&&I instanceof V0&&I.hasErrorLabel("TransientTransactionError")&&h.transaction.unpinServer(),i.apply(null,arguments)}:i;try{u.write(A,O,L)}catch(I){L(I)}}s(pB,"_command");function Q5(e){return e==null?!1:e.description?e.description.maxWireVersion>=6:e.ismaster==null?!1:e.ismaster.maxWireVersion>=6}s(Q5,"hasSessionSupport");function e7(e){let t=e.ismaster?e.ismaster:e.description;return t==null?!1:t.maxWireVersion>=6&&t.__nodejs_mock_server__==null}s(e7,"supportsOpMsg");function t7(e,t,r,n,i){let a=e.autoEncrypter;function u(f,l){if(f||l==null){i(f,l);return}a.decrypt(l.result,n,(h,m)=>{if(h){i(h,null);return}l.result=m,l.message.documents=[m],i(null,l)})}s(u,"commandResponseHandler"),a.encrypt(t,r,n,(f,l)=>{if(f){i(f,null);return}pB(e,t,l,n,u)})}s(t7,"_cryptCommand");mB.exports=Z5});var Bc=E((Xge,gB)=>{"use strict";var r7=X().MongoError,jh=class jh{constructor(t){typeof t=="boolean"?this.verbosity=t?"allPlansExecution":"queryPlanner":this.verbosity=t}static fromOptions(t){if(t==null||t.explain===void 0)return;let r=t.explain;if(typeof r=="boolean"||typeof r=="string")return new jh(t.explain);throw new r7("explain must be a string or a boolean")}};s(jh,"Explain");var Y0=jh;gB.exports={Explain:Y0}});var SB=E((Zge,yB)=>{"use strict";var n7=X().MongoError,i7=et().collectionNamespace,s7=Ca(),o7=x().decorateWithExplain,a7=Bc().Explain;function u7(e,t,r,n,i,a,u){if(i.length===0)throw new n7(`${t} must contain at least one document`);typeof a=="function"&&(u=a,a={}),a=a||{};let f=typeof a.ordered=="boolean"?a.ordered:!0,l=a.writeConcern,h={};if(h[t]=i7(n),h[r]=i,h.ordered=f,l&&Object.keys(l).length>0&&(h.writeConcern=l),a.collation)for(let g=0;g{"use strict";var c7=Xr().KillCursor,f7=X().MongoError,l7=X().MongoNetworkError,h7=et().collectionNamespace,d7=ce().maxWireVersion,p7=ce().emitWarning,m7=Ca();function g7(e,t,r,n,i){typeof n=="function"&&(i=n,n={}),i=typeof i=="function"?i:()=>{};let a=r.cursorId;if(d7(e)<4){let l=e.s.bson,h=e.s.pool,m=new c7(l,t,[a]),p={immediateRelease:!0,noResponse:!0};if(typeof r.session=="object"&&(p.session=r.session),h&&h.isConnected())try{h.write(m,p,i)}catch(g){typeof i=="function"?i(g,null):p7(g)}return}let u={killCursors:h7(t),cursors:[a]},f=n||{};typeof r.session=="object"&&(f.session=r.session),m7(e,t,u,f,(l,h)=>{if(l)return i(l);let m=h.message;if(m.cursorNotFound)return i(new l7("cursor killed or timed out"),null);if(!Array.isArray(m.documents)||m.documents.length===0)return i(new f7(`invalid killCursors result returned for cursor id ${a}`));i(null,m.documents[0])})}s(g7,"killCursors");_B.exports=g7});var OB=E((rye,vB)=>{"use strict";var y7=Xr().GetMore,S7=jt().retrieveBSON,_7=X().MongoError,w7=X().MongoNetworkError,v7=S7(),Wh=v7.Long,O7=et().collectionNamespace,E7=ce().maxWireVersion,T7=et().applyCommonQueryOptions,N7=Ca();function b7(e,t,r,n,i,a){i=i||{};let u=E7(e);function f(p,g){if(p)return a(p);let w=g.message;if(w.cursorNotFound)return a(new w7("cursor killed or timed out"),null);if(u<4){let N=typeof w.cursorId=="number"?Wh.fromNumber(w.cursorId):w.cursorId;r.documents=w.documents,r.cursorId=N,a(null,null,w.connection);return}if(w.documents[0].ok===0)return a(new _7(w.documents[0]));let O=typeof w.documents[0].cursor.id=="number"?Wh.fromNumber(w.documents[0].cursor.id):w.documents[0].cursor.id;r.documents=w.documents[0].cursor.nextBatch,r.cursorId=O,a(null,w.documents[0],w.connection)}if(s(f,"queryCallback"),u<4){let p=e.s.bson,g=new y7(p,t,r.cursorId,{numberToReturn:n}),w=T7({},r);e.s.pool.write(g,w,f);return}let h={getMore:r.cursorId instanceof Wh?r.cursorId:Wh.fromNumber(r.cursorId),collection:O7(t),batchSize:Math.abs(n)};r.cmd.tailable&&typeof r.cmd.maxAwaitTimeMS=="number"&&(h.maxTimeMS=r.cmd.maxAwaitTimeMS);let m=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},i);r.session&&(m.session=r.session),N7(e,t,h,m,f)}s(b7,"getMore");vB.exports=b7});var bB=E((iye,NB)=>{"use strict";var A7=Xr().Query,EB=X().MongoError,TB=et().getReadPreference,C7=et().collectionNamespace,I7=et().isSharded,B7=ce().maxWireVersion,R7=et().applyCommonQueryOptions,x7=Ca(),M7=x().decorateWithExplain,D7=Bc().Explain;function q7(e,t,r,n,i,a){if(i=i||{},n.cursorId!=null)return a();if(r==null)return a(new EB(`command ${JSON.stringify(r)} does not return a cursor`));if(B7(e)<4){let h=L7(e,t,r,n,i),m=R7({},n);typeof h.documentsReturnedIn=="string"&&(m.documentsReturnedIn=h.documentsReturnedIn),e.s.pool.write(h,m,a);return}let u=TB(r,i),f=P7(e,t,r,n,i);try{let h=D7.fromOptions(i);h&&(f=M7(f,h))}catch(h){return a(h)}r.virtual=!1;let l=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:u.slaveOk()},i);r.readPreference&&(l.readPreference=u),n.session&&(l.session=n.session),x7(e,t,f,l,a)}s(q7,"query");function P7(e,t,r,n){n.batchSize=r.batchSize||n.batchSize;let i={find:C7(t)};r.query&&(r.query.$query?i.filter=r.query.$query:i.filter=r.query);let a=r.sort;if(Array.isArray(a)){let u={};if(a.length>0&&!Array.isArray(a[0])){let f=a[1];f==="asc"?f=1:f==="desc"&&(f=-1),u[a[0]]=f}else for(let f=0;f0&&n.batchSize===0?f=n.limit:f=n.batchSize;let l=n.skip||0,h={};if(I7(e)&&u&&(h.$readPreference=u.toJSON()),r.sort&&(h.$orderby=r.sort),r.hint&&(h.$hint=r.hint),r.snapshot&&(h.$snapshot=r.snapshot),typeof r.returnKey<"u"&&(h.$returnKey=r.returnKey),r.maxScan&&(h.$maxScan=r.maxScan),r.min&&(h.$min=r.min),r.max&&(h.$max=r.max),typeof r.showDiskLoc<"u"&&(h.$showDiskLoc=r.showDiskLoc),r.comment&&(h.$comment=r.comment),r.maxTimeMS&&(h.$maxTimeMS=r.maxTimeMS),i.explain!==void 0&&(f=-Math.abs(r.limit||0),h.$explain=!0),h.$query=r.query,r.readConcern&&r.readConcern.level!=="local")throw new EB(`server find command does not support a readConcern level of ${r.readConcern.level}`);r.readConcern&&(r=Object.assign({},r),delete r.readConcern);let m=typeof i.serializeFunctions=="boolean"?i.serializeFunctions:!1,p=typeof i.ignoreUndefined=="boolean"?i.ignoreUndefined:!1,g=new A7(a,t,h,{numberToSkip:l,numberToReturn:f,pre32Limit:typeof r.limit<"u"?r.limit:void 0,checkKeys:!1,returnFieldSelector:r.fields,serializeFunctions:m,ignoreUndefined:p});return typeof r.tailable=="boolean"&&(g.tailable=r.tailable),typeof r.oplogReplay=="boolean"&&(g.oplogReplay=r.oplogReplay),typeof r.noCursorTimeout=="boolean"&&(g.noCursorTimeout=r.noCursorTimeout),typeof r.awaitData=="boolean"&&(g.awaitData=r.awaitData),typeof r.partial=="boolean"&&(g.partial=r.partial),g.slaveOk=u.slaveOk(),g}s(L7,"prepareLegacyFindQuery");NB.exports=q7});var G0=E((oye,AB)=>{"use strict";var k0=SB();AB.exports={insert:s(function(t,r,n,i,a){k0(t,"insert","documents",r,n,i,a)},"insert"),update:s(function(t,r,n,i,a){k0(t,"update","updates",r,n,i,a)},"update"),remove:s(function(t,r,n,i,a){k0(t,"delete","deletes",r,n,i,a)},"remove"),killCursors:wB(),getMore:OB(),query:bB(),command:Ca()}});var k=E((uye,IB)=>{"use strict";var U7=Bc().Explain,j7=X().MongoError,CB={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS"),EXPLAINABLE:Symbol("EXPLAINABLE")},X0=class X0{constructor(t){if(this.options=Object.assign({},t),this.hasAspect(CB.EXPLAINABLE))this.explain=U7.fromOptions(t);else if(this.options.explain!==void 0)throw new j7("explain is not supported on this command")}hasAspect(t){return this.constructor.aspects==null?!1:this.constructor.aspects.has(t)}set session(t){Object.assign(this.options,{session:t})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}};s(X0,"OperationBase");var K0=X0;function W7(e,t){return!Array.isArray(t)&&!(t instanceof Set)&&(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t}s(W7,"defineAspects");IB.exports={Aspect:CB,defineAspects:W7,OperationBase:K0}});var Ia=E((fye,MB)=>{"use strict";var F7=x().maybePromise,J0=X().MongoError,RB=k().Aspect,$7=k().OperationBase,Z0=Vt(),z7=X().isRetryableError,H7=ce().maxWireVersion,V7=ce().isUnifiedTopology;function xB(e,t,r){if(e==null)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof $7))throw new TypeError("This method requires a valid operation instance");return F7(e,r,n=>{if(V7(e)&&e.shouldCheckForSessionSupport())return k7(e,t,n);let i,a;if(e.hasSessionSupport()){if(t.session==null)a=Symbol(),i=e.startSession({owner:a}),t.session=i;else if(t.session.hasEnded)return n(new J0("Use of expired sessions is not permitted"))}else if(t.session)return n(new J0("Current topology does not support sessions"));function u(f,l){i&&i.owner===a&&(i.endSession(),t.session===i&&t.clearSession()),n(f,l)}s(u,"executeCallback");try{t.hasAspect(RB.EXECUTE_WITH_SELECTION)?Y7(e,t,u):t.execute(u)}catch(f){i&&i.owner===a&&(i.endSession(),t.session===i&&t.clearSession()),n(f)}})}s(xB,"executeOperation");function BB(e){return H7(e)>=6}s(BB,"supportsRetryableReads");function Y7(e,t,r){let n=t.readPreference||Z0.primary,i=t.session&&t.session.inTransaction();if(i&&!n.equals(Z0.primary)){r(new J0(`Read preference in a transaction must be primary, not: ${n.mode}`));return}let a={readPreference:n,session:t.session};function u(f,l){if(f==null)return r(null,l);if(!z7(f))return r(f);e.selectServer(a,(h,m)=>{if(h||!BB(m)){r(h,null);return}t.execute(m,r)})}s(u,"callbackWithRetry"),e.selectServer(a,(f,l)=>{if(f){r(f,null);return}let h=e.s.options.retryReads!==!1&&t.session&&!i&&BB(l)&&t.canRetryRead;if(t.hasAspect(RB.RETRYABLE)&&h){t.execute(l,u);return}t.execute(l,r)})}s(Y7,"executeWithServerSelection");function k7(e,t,r){e.selectServer(Z0.primaryPreferred,n=>{if(n)return r(n);xB(e,t,r)})}s(k7,"selectServerForSessionSupport");MB.exports=xB});var yn=E((hye,LB)=>{"use strict";var G7=mn(),K7=jt().retrieveBSON,Ti=X().MongoError,DB=X().MongoNetworkError,X7=ce().collationNotSupported,J7=Vt(),Z7=ce().isUnifiedTopology,Q7=Ia(),e9=require("stream").Readable,t9=x().SUPPORTS,r9=x().MongoDBNamespace,n9=x().mergeOptions,i9=k().OperationBase,s9=K7(),Kn=s9.Long,qB={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function po(e,t,r){try{e(t,r)}catch(n){process.nextTick(function(){throw n})}}s(po,"handleCallback");var Q0=class Q0 extends e9{constructor(t,r,n,i){super({objectMode:!0}),i=i||{},r instanceof i9&&(this.operation=r,r=this.operation.ns.toString(),i=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=i.disconnectHandler,this.bson=t.s.bson,this.ns=r,this.namespace=r9.fromString(r),this.cmd=n,this.options=i,this.topology=t,this.cursorState={cursorId:null,cmd:n,documents:i.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:i.limit||n.limit||0,skip:i.skip||n.skip||0,batchSize:i.batchSize||n.batchSize||1e3,currentLimit:0,transforms:i.transforms,raw:i.raw||n&&n.raw},typeof i.session=="object"&&(this.cursorState.session=i.session);let a=t.s.options;typeof a.promoteLongs=="boolean"?this.cursorState.promoteLongs=a.promoteLongs:typeof i.promoteLongs=="boolean"&&(this.cursorState.promoteLongs=i.promoteLongs),typeof a.promoteValues=="boolean"?this.cursorState.promoteValues=a.promoteValues:typeof i.promoteValues=="boolean"&&(this.cursorState.promoteValues=i.promoteValues),typeof a.promoteBuffers=="boolean"?this.cursorState.promoteBuffers=a.promoteBuffers:typeof i.promoteBuffers=="boolean"&&(this.cursorState.promoteBuffers=i.promoteBuffers),typeof a.bsonRegExp=="boolean"?this.cursorState.bsonRegExp=a.bsonRegExp:typeof i.bsonRegExp=="boolean"&&(this.cursorState.bsonRegExp=i.bsonRegExp),a.reconnect&&(this.cursorState.reconnect=a.reconnect),this.logger=G7("Cursor",a),typeof n=="number"?(this.cursorState.cursorId=Kn.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof Kn&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(t){this.cursorState.batchSize=t}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(t){this.cursorState.limit=t}cursorLimit(){return this.cursorState.limit}setCursorSkip(t){this.cursorState.skip=t}cursorSkip(){return this.cursorState.skip}_next(t){Fh(this,t)}clone(){let t=n9({},this.options);return delete t.session,this.topology.cursor(this.ns,this.cmd,t)}isDead(){return this.cursorState.dead===!0}isKilled(){return this.cursorState.killed===!0}isNotified(){return this.cursorState.notified===!0}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(t){let r=this.cursorState.documents.length-this.cursorState.cursorIndex,n=t0&&this.cursorState.currentLimit+i.length>this.cursorState.limit&&(i=i.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+i.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+i.length,i}kill(t){if(this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],this.cursorState.cursorId==null||this.cursorState.cursorId.isZero()||this.cursorState.init===!1){t&&t(null,null);return}this.server.killCursors(this.ns,this.cursorState,t)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===qB.CLOSED||this.isDead())return this.push(null);this._next((t,r)=>{if(t)return this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",t),this.isDead()||this.close(),this.emit("end"),this.emit("finish");if(this.cursorState.streamOptions&&typeof this.cursorState.streamOptions.transform=="function"&&r!=null)return this.push(this.cursorState.streamOptions.transform(r));this.push(r),r===null&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")})})}_endSession(t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=this.cursorState.session;return n&&(t.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(r),!0):(r&&r(),!1)}_getMore(t){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let r=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+r>this.cursorState.limit&&(r=this.cursorState.limit-this.cursorState.currentLimit);let n=this.cursorState;this.server.getMore(this.ns,n,r,this.options,(i,a,u)=>{(i||n.cursorId&&n.cursorId.isZero())&&this._endSession(),t(i,a,u)})}_initializeCursor(t){let r=this;if(Z7(r.topology)&&r.topology.shouldCheckForSessionSupport()){r.topology.selectServer(J7.primaryPreferred,u=>{if(u){t(u);return}this._initializeCursor(t)});return}function n(u,f){let l=r.cursorState;if((u||l.cursorId&&l.cursorId.isZero())&&r._endSession(),l.documents.length===0&&l.cursorId&&l.cursorId.isZero()&&!r.cmd.tailable&&!r.cmd.awaitData)return zh(r,t);t(u,f)}s(n,"done");let i=s((u,f)=>{if(u)return n(u);let l=f.message;if(Array.isArray(l.documents)&&l.documents.length===1){let m=l.documents[0];if(l.queryFailure)return n(new Ti(m),null);if(!r.cmd.find||r.cmd.find&&r.cmd.virtual===!1){if(m.$err||m.errmsg)return n(new Ti(m),null);if(m.cursor!=null&&typeof m.cursor!="string"){let p=m.cursor.id;return m.cursor.ns&&(r.ns=m.cursor.ns),r.cursorState.cursorId=typeof p=="number"?Kn.fromNumber(p):p,r.cursorState.lastCursorId=r.cursorState.cursorId,r.cursorState.operationTime=m.operationTime,Array.isArray(m.cursor.firstBatch)&&(r.cursorState.documents=m.cursor.firstBatch),n(null,l)}}}let h=l.cursorId||0;r.cursorState.cursorId=h instanceof Kn?h:Kn.fromNumber(h),r.cursorState.documents=l.documents,r.cursorState.lastCursorId=l.cursorId,r.cursorState.transforms&&typeof r.cursorState.transforms.query=="function"&&(r.cursorState.documents=r.cursorState.transforms.query(l)),n(null,l)},"queryCallback");if(r.operation){r.logger.isDebug()&&r.logger.debug(`issue initial query [${JSON.stringify(r.cmd)}] with flags [${JSON.stringify(r.query)}]`),Q7(r.topology,r.operation,(u,f)=>{if(u){n(u);return}if(r.server=r.operation.server,r.cursorState.init=!0,r.cursorState.cursorId!=null)return n();i(u,f)});return}let a={};return r.cursorState.session&&(a.session=r.cursorState.session),r.operation?a.readPreference=r.operation.readPreference:r.options.readPreference&&(a.readPreference=r.options.readPreference),r.topology.selectServer(a,(u,f)=>{if(u){let h=r.disconnectHandler;return h!=null?h.addObjectAndMethod("cursor",r,"next",[t],t):t(u)}if(r.server=f,r.cursorState.init=!0,X7(r.server,r.cmd))return t(new Ti(`server ${r.server.name} does not support collation`));if(r.cursorState.cursorId!=null)return n();if(r.logger.isDebug()&&r.logger.debug(`issue initial query [${JSON.stringify(r.cmd)}] with flags [${JSON.stringify(r.query)}]`),r.cmd.find!=null){f.query(r.ns,r.cmd,r.cursorState,r.options,i);return}let l=Object.assign({session:r.cursorState.session},r.options);f.command(r.ns,r.cmd,l,i)})}};s(Q0,"CoreCursor");var $h=Q0;t9.ASYNC_ITERATOR&&($h.prototype[Symbol.asyncIterator]=_S().asyncIterator);function o9(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;let r=new DB(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return PB(e,()=>t(r)),!0}return!1}s(o9,"isConnectionDead");function a9(e,t){return e.cursorState.dead&&!e.cursorState.killed?(e.cursorState.killed=!0,zh(e,t),!0):!1}s(a9,"isCursorDeadButNotkilled");function u9(e,t){return e.cursorState.dead&&e.cursorState.killed?(po(t,new Ti("cursor is dead")),!0):!1}s(u9,"isCursorDeadAndKilled");function c9(e,t){return e.cursorState.killed?(zh(e,t),!0):!1}s(c9,"isCursorKilled");function Rc(e,t){e.cursorState.dead=!0,zh(e,t)}s(Rc,"setCursorDeadAndNotified");function zh(e,t){PB(e,()=>po(t,null,null))}s(zh,"setCursorNotified");function PB(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,e.cursorState.session){e._endSession(t);return}return t()}s(PB,"_setCursorNotifiedImpl");function Fh(e,t){if(e.cursorState.notified)return t(new Error("cursor is exhausted"));if(!c9(e,t)&&!a9(e,t)&&!u9(e,t)){if(!e.cursorState.init){if(!e.topology.isConnected(e.options)){if(e.topology._type==="server"&&!e.topology.s.options.reconnect)return t(new Ti("no connection available"));if(e.disconnectHandler!=null){if(e.topology.isDestroyed())return t(new Ti("Topology was destroyed"));e.disconnectHandler.addObjectAndMethod("cursor",e,"next",[t],t);return}}e._initializeCursor((r,n)=>{if(r||n===null){t(r,n);return}Fh(e,t)});return}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit)e.kill(()=>Rc(e,t));else if(e.cursorState.cursorIndex===e.cursorState.documents.length&&!Kn.ZERO.equals(e.cursorState.cursorId)){if(e.cursorState.documents=[],e.cursorState.cursorIndex=0,e.topology.isDestroyed())return t(new DB("connection destroyed, not possible to instantiate cursor"));if(o9(e,t))return;e._getMore(function(r,n,i){if(r)return po(t,r);if(e.connection=i,e.cursorState.documents.length===0&&e.cmd.tailable&&Kn.ZERO.equals(e.cursorState.cursorId))return po(t,new Ti({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}));if(e.cursorState.documents.length===0&&e.cmd.tailable&&!Kn.ZERO.equals(e.cursorState.cursorId))return Fh(e,t);if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit)return Rc(e,t);Fh(e,t)})}else{if(e.cursorState.documents.length===e.cursorState.cursorIndex&&e.cmd.tailable&&Kn.ZERO.equals(e.cursorState.cursorId))return po(t,new Ti({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}));if(e.cursorState.documents.length===e.cursorState.cursorIndex&&Kn.ZERO.equals(e.cursorState.cursorId))Rc(e,t);else{if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill(()=>Rc(e,t));return}e.cursorState.currentLimit+=1;let r=e.cursorState.documents[e.cursorState.cursorIndex++];if(!r||r.$err){e.kill(()=>Rc(e,function(){po(t,new Ti(r?r.$err:void 0))}));return}e.cursorState.transforms&&typeof e.cursorState.transforms.doc=="function"&&(r=e.cursorState.transforms.doc(r)),po(t,null,r)}}}}s(Fh,"nextFunction");LB.exports={CursorState:qB,CoreCursor:$h}});var kh=E((pye,WB)=>{"use strict";var f9=require("util").inherits,go=require("util").format,UB=require("events").EventEmitter,l9=Vt(),h9=mn(),d9=jt().debugOptions,p9=jt().retrieveBSON,m9=hB(),vs=X().MongoError,g9=X().MongoNetworkError,yo=G0(),y9=yn().CoreCursor,ws=vt(),S9=vt().createCompressionInfo,_9=vt().resolveClusterTime,w9=vt().SessionMixins,v9=uo().extractCommand,O9=ce().relayEvents,e_=ce().collationNotSupported,E9=ce().makeClientMetadata,T9=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"],N9=0,xc=!1,Mc={},ir=p9();function Hh(e){return e.s.parent==null?e.id:e.s.parent.id}s(Hh,"topologyId");var ke=s(function(e){e=e||{},UB.call(this),this.id=N9++,this.s={options:Object.assign({metadata:E9(e)},e),logger:h9("Server",e),Cursor:e.cursorFactory||y9,bson:e.bson||new ir([ir.Binary,ir.Code,ir.DBRef,ir.Decimal128,ir.Double,ir.Int32,ir.Long,ir.Map,ir.MaxKey,ir.MinKey,ir.ObjectId,ir.BSONRegExp,ir.Symbol,ir.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:typeof e.monitoring=="boolean"?e.monitoring:!0,inTopology:!!e.parent,monitoringInterval:typeof e.monitoringInterval=="number"?e.monitoringInterval:5e3,compression:{compressors:S9(e)},parent:e.parent},this.s.parent||(this.s.clusterTime=null),this.ismaster=null,this.lastIsMasterMS=-1,this.monitoringProcessId=null,this.initialConnect=!0,this._type="server",this.lastUpdateTime=0,this.lastWriteDate=0,this.staleness=0},"Server");f9(ke,UB);Object.assign(ke.prototype,w9);Object.defineProperty(ke.prototype,"type",{enumerable:!0,get:function(){return this._type}});Object.defineProperty(ke.prototype,"parserType",{enumerable:!0,get:function(){return ir.native?"c++":"js"}});Object.defineProperty(ke.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});Object.defineProperty(ke.prototype,"clientMetadata",{enumerable:!0,get:function(){return this.s.options.metadata}});Object.defineProperty(ke.prototype,"clusterTime",{enumerable:!0,set:function(e){let t=this.s.parent?this.s.parent:this.s;_9(t,e)},get:function(){return(this.s.parent?this.s.parent:this.s).clusterTime||null}});ke.enableServerAccounting=function(){xc=!0,Mc={}};ke.disableServerAccounting=function(){xc=!1};ke.servers=function(){return Mc};Object.defineProperty(ke.prototype,"name",{enumerable:!0,get:function(){return this.s.options.host+":"+this.s.options.port}});function Vh(e,t,r,n,i,a){if(!e.s.pool.isConnected()&&e.s.options.reconnect&&e.s.disconnectHandler!=null&&!i.monitoring)return e.s.disconnectHandler.add(t,r,n,i,a),!0;if(!e.s.pool.isConnected())return a(new vs(go("no connection available to server %s",e.name))),!0}s(Vh,"disconnectHandler");function jB(e){return function(){if(!e.s.pool.isDestroyed()){e.emit("monitoring",e);var t=new Date().getTime();e.command("admin.$cmd",{ismaster:!0},{socketTimeout:typeof e.s.options.connectionTimeout!="number"?2e3:e.s.options.connectionTimeout,monitoring:!0},(r,n)=>{e.lastIsMasterMS=new Date().getTime()-t,!e.s.pool.isDestroyed()&&(n&&(e.ismaster=n.result),e.monitoringProcessId=setTimeout(jB(e),e.s.monitoringInterval))})}}}s(jB,"monitoringProcess");var mo=s(function(e,t){return function(r,n){if(e.s.logger.isInfo()){var i=r instanceof vs?JSON.stringify(r):{};e.s.logger.info(go("server %s fired event %s out with message %s",e.name,t,i))}if(t==="connect"){if(e.initialConnect=!1,e.ismaster=n.ismaster,e.lastIsMasterMS=n.lastIsMasterMS,n.agreedCompressor&&(e.s.pool.options.agreedCompressor=n.agreedCompressor),n.zlibCompressionLevel&&(e.s.pool.options.zlibCompressionLevel=n.zlibCompressionLevel),n.ismaster.$clusterTime){let a=n.ismaster.$clusterTime;e.clusterTime=a}e.ismaster.msg==="isdbgrid"&&(e._type="mongos"),e.s.monitoring&&(e.monitoringProcessId=setTimeout(jB(e),e.s.monitoringInterval)),ws.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:ws.getTopologyType(e)}),e.s.inTopology||ws.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:ws.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info(go("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else if(t==="error"||t==="parseError"||t==="close"||t==="timeout"||t==="reconnect"||t==="attemptReconnect"||t==="reconnectFailed"){if(xc&&["close","timeout","error","parseError","reconnectFailed"].indexOf(t)!==-1&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete Mc[e.id]),t==="close"&&ws.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),t==="reconnectFailed"){e.emit("reconnectFailed",r),e.listeners("error").length>0&&e.emit("error",r);return}if(["disconnected","connecting"].indexOf(e.s.pool.state)!==-1&&e.initialConnect&&["close","timeout","error","parseError"].indexOf(t)!==-1)return e.initialConnect=!1,e.emit("error",new g9(go("failed to connect to server [%s] on first connect [%s]",e.name,r)));if(t==="reconnect")return ws.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:ws.getTopologyType(e)}),e.emit(t,e);e.emit(t,r)}}},"eventHandler");ke.prototype.connect=function(e){var t=this;if(e=e||{},xc&&(Mc[this.id]=this),t.s.pool&&!t.s.pool.isDisconnected()&&!t.s.pool.isDestroyed())throw new vs(go("server instance in invalid state %s",t.s.pool.state));t.s.pool=new m9(this,Object.assign(t.s.options,e,{bson:this.s.bson})),t.s.pool.on("close",mo(t,"close")),t.s.pool.on("error",mo(t,"error")),t.s.pool.on("timeout",mo(t,"timeout")),t.s.pool.on("parseError",mo(t,"parseError")),t.s.pool.on("connect",mo(t,"connect")),t.s.pool.on("reconnect",mo(t,"reconnect")),t.s.pool.on("reconnectFailed",mo(t,"reconnectFailed")),O9(t.s.pool,t,["commandStarted","commandSucceeded","commandFailed"]),t.s.inTopology||this.emit("topologyOpening",{topologyId:Hh(t)}),t.emit("serverOpening",{topologyId:Hh(t),address:t.name}),t.s.pool.connect()};ke.prototype.auth=function(e,t){typeof t=="function"&&t(null,null)};ke.prototype.getDescription=function(){var e=this.ismaster||{},t={type:ws.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t};ke.prototype.lastIsMaster=function(){return this.ismaster};ke.prototype.unref=function(){this.s.pool.unref()};ke.prototype.isConnected=function(){return this.s.pool?this.s.pool.isConnected():!1};ke.prototype.isDestroyed=function(){return this.s.pool?this.s.pool.isDestroyed():!1};function Yh(e){if(!e.s.pool)return new vs("server instance is not connected");if(e.s.pool.isDestroyed())return new vs("server instance pool was destroyed")}s(Yh,"basicWriteValidations");function b9(e,t){if(Yh(e,t),t.readPreference&&!(t.readPreference instanceof l9))throw new Error("readPreference must be an instance of ReadPreference")}s(b9,"basicReadValidations");ke.prototype.command=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var a=b9(i,r);if(a)return n(a);if(r=Object.assign({},r,{wireProtocolCommand:!1}),i.s.logger.isDebug()){let u=v9(t);i.s.logger.debug(go("executing command [%s] against %s",JSON.stringify({ns:e,cmd:u.shouldRedact?`${u.name} details REDACTED`:t,options:d9(T9,r)}),i.name))}if(!Vh(i,"command",e,t,r,n)){if(e_(this,t))return n(new vs(`server ${this.name} does not support collation`));yo.command(i,e,t,r,n)}};ke.prototype.query=function(e,t,r,n,i){yo.query(this,e,t,r,n,i)};ke.prototype.getMore=function(e,t,r,n,i){yo.getMore(this,e,t,r,n,i)};ke.prototype.killCursors=function(e,t,r){yo.killCursors(this,e,t,r)};ke.prototype.insert=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var a=Yh(i,r);if(a)return n(a);if(!Vh(i,"insert",e,t,r,n))return t=Array.isArray(t)?t:[t],yo.insert(i,e,t,r,n)};ke.prototype.update=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var a=Yh(i,r);if(a)return n(a);if(!Vh(i,"update",e,t,r,n))return e_(this,r)?n(new vs(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],yo.update(i,e,t,r,n))};ke.prototype.remove=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var a=Yh(i,r);if(a)return n(a);if(!Vh(i,"remove",e,t,r,n))return e_(this,r)?n(new vs(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],yo.remove(i,e,t,r,n))};ke.prototype.cursor=function(e,t,r){r=r||{};let n=r.topology||this;var i=r.cursorFactory||this.s.Cursor;return new i(n,e,t,r)};ke.prototype.equals=function(e){return typeof e=="string"?this.name.toLowerCase()===e.toLowerCase():e.name?this.name.toLowerCase()===e.name.toLowerCase():!1};ke.prototype.connections=function(){return this.s.pool.allConnections()};ke.prototype.selectServer=function(e,t,r){typeof e=="function"&&typeof r>"u"&&(r=e,e=void 0,t={}),typeof t=="function"&&(r=t,t=e,e=void 0),r(null,this)};var A9=["close","error","timeout","parseError","connect"];ke.prototype.destroy=function(e,t){if(this._destroyed){typeof t=="function"&&t(null,null);return}typeof e=="function"&&(t=e,e={}),e=e||{};var r=this;if(xc&&delete Mc[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!r.s.pool||this._destroyed){this._destroyed=!0,typeof t=="function"&&t(null,null);return}this._destroyed=!0,e.emitClose&&r.emit("close",r),e.emitDestroy&&r.emit("destroy",r),A9.forEach(function(n){r.s.pool.removeAllListeners(n)}),r.listeners("serverClosed").length>0&&r.emit("serverClosed",{topologyId:Hh(r),address:r.name}),r.listeners("topologyClosed").length>0&&!r.s.inTopology&&r.emit("topologyClosed",{topologyId:Hh(r)}),r.s.logger.isDebug()&&r.s.logger.debug(go("destroy called on server %s",r.name)),this.s.pool.destroy(e.force,t)};WB.exports=ke});var YB=E((gye,VB)=>{"use strict";var C9=require("util").inherits,FB=require("util").format,I9=vt().diff,zB=require("events").EventEmitter,B9=mn(),Os=Vt(),So=X().MongoError,Gh=qn().Buffer,it={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"},sr={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"},qr=s(function(e){e=e||{},zB.call(this),this.topologyType=e.setName?it.ReplicaSetNoPrimary:it.Unknown,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||B9("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0},"ReplSetState");C9(qr,zB);qr.prototype.hasPrimaryAndSecondary=function(){return this.primary!=null&&this.secondaries.length>0};qr.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()};qr.prototype.hasPrimary=function(){return this.primary!=null};qr.prototype.hasSecondary=function(){return this.secondaries.length>0};qr.prototype.get=function(e){for(var t=this.allServers(),r=0;r{n--,!(n>0)&&(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,Ba(this),typeof t=="function"&&t(null,null))},"serverDestroyed");if(n===0){i();return}r.forEach(a=>a.destroy(e,i))};qr.prototype.remove=function(e,t){t=t||{};var r=e.name.toLowerCase(),n=this.primary?[this.primary]:[];n=n.concat(this.secondaries),n=n.concat(this.arbiters),n=n.concat(this.passives);for(var i=0;ie.arbiterOnly&&e.setName,"isArbiter");qr.prototype.update=function(e){var t=this;let r=e.lastIsMaster();r&&r.isWritablePrimary&&(r.ismaster=r.isWritablePrimary);var n=e.name.toLowerCase();if(r){var i=Array.isArray(r.hosts)?r.hosts:[];i=i.concat(Array.isArray(r.arbiters)?r.arbiters:[]),i=i.concat(Array.isArray(r.passives)?r.passives:[]),i=i.map(function(N){return N.toLowerCase()});for(var a=0;al)return!1}else if(!p&&u&&l&&l=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=r-e.lastWriteDate+t)};qr.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&e.maxStalenessSeconds==null){var i=r_(this,e);if(i)return i}else if(n.length>0&&e.maxStalenessSeconds!=null&&(i=t_(this,e),i))return i;return e.equals(Os.secondaryPreferred)?this.primary:null}if(e.equals(Os.primaryPreferred)){if(i=null,this.primary)return this.primary;if(n.length>0&&e.maxStalenessSeconds==null?i=r_(this,e):n.length>0&&e.maxStalenessSeconds!=null&&(i=t_(this,e)),i)return i}return this.primary};var HB=s(function(e,t){if(e.tags==null)return t;for(var r=[],n=Array.isArray(e.tags)?e.tags:[e.tags],i=0;i0?r[0].lastIsMasterMS:0;if(r=r.filter(function(u){return u.lastIsMasterMS<=i+e.acceptableLatency}),r.length===0)return null;e.index=e.index%r.length;var a=r[e.index];return e.index=e.index+1,a}s(r_,"pickNearest");function Kh(e,t,r){for(var n=0;n0){var t="Unknown",r=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var n={topologyType:t,setName:r,servers:[]};if(e.hasPrimary()){var i=e.primary.getDescription();i.type="RSPrimary",n.servers.push(i)}n.servers=n.servers.concat(e.secondaries.map(function(f){var l=f.getDescription();return l.type="RSSecondary",l})),n.servers=n.servers.concat(e.arbiters.map(function(f){var l=f.getDescription();return l.type="RSArbiter",l})),n.servers=n.servers.concat(e.passives.map(function(f){var l=f.getDescription();return l.type="RSSecondary",l}));var a=I9(e.replicasetDescription,n),u={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:n,diff:a};e.emit("topologyDescriptionChanged",u),e.replicasetDescription=n}}s(Ba,"emitTopologyDescriptionChanged");VB.exports=qr});var nR=E((Sye,rR)=>{"use strict";var R9=require("util").inherits,bi=require("util").format,KB=require("events").EventEmitter,Ni=Vt(),x9=yn().CoreCursor,M9=jt().retrieveBSON,D9=mn(),Sn=X().MongoError,Zh=kh(),q9=YB(),Ra=vt().Timeout,XB=vt().Interval,P9=vt().SessionMixins,JB=vt().isRetryableWritesSupported,ZB=ce().relayEvents,or=M9(),L9=vt().getMMAPError,U9=ce().makeClientMetadata,QB=vt().legacyIsRetryableWriteError,eR=x().now,j9=x().calculateDurationInMs,_o="disconnected",wo="connecting",Xh="connected",Pr="unreferenced",Bt="destroyed";function Ts(e,t){var r={disconnected:[wo,Bt,_o],connecting:[wo,Bt,Xh,_o],connected:[Xh,_o,Bt,Pr],unreferenced:[Pr,Bt],destroyed:[Bt]},n=r[e.state];n&&n.indexOf(t)!==-1?e.state=t:e.s.logger.error(bi("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}s(Ts,"stateTransition");var W9=1,Jh=["connect","close","error","timeout","parseError"],Rt=s(function(e,t){var r=this;if(t=t||{},!Array.isArray(e))throw new Sn("seedlist must be an array");if(e.length===0)throw new Sn("seedlist must contain at least one entry");e.forEach(function(u){if(typeof u.host!="string"||typeof u.port!="number")throw new Sn("seedlist entry must contain a host and port")}),KB.call(this),this.id=W9++;var n=t.localThresholdMS||15;t.acceptableLatency&&(n=t.acceptableLatency);var i=D9("ReplSet",t);this.s={options:Object.assign({metadata:U9(t)},t),bson:t.bson||new or([or.Binary,or.Code,or.DBRef,or.Decimal128,or.Double,or.Int32,or.Long,or.Map,or.MaxKey,or.MinKey,or.ObjectId,or.BSONRegExp,or.Symbol,or.Timestamp]),Cursor:t.cursorFactory||x9,logger:i,seedlist:e,replicaSetState:new q9({id:this.id,setName:t.setName,acceptableLatency:n,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:i}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug=="boolean"?t.debug:!1},this.s.replicaSetState.on("topologyDescriptionChanged",function(u){r.emit("topologyDescriptionChanged",u)}),this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeoutw.name===h);if(p>=0)return e.s.connectingServers[p].destroy({force:!0}),e.s.connectingServers.splice(p,1),a();var g=new Zh(Object.assign({},e.s.options,{host:h.split(":")[0],port:parseInt(h.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));g.once("connect",u(e,"connect")),g.once("close",u(e,"close")),g.once("timeout",u(e,"timeout")),g.once("error",u(e,"error")),g.once("parseError",u(e,"parseError")),g.on("serverOpening",w=>e.emit("serverOpening",w)),g.on("serverDescriptionChanged",w=>e.emit("serverDescriptionChanged",w)),g.on("serverClosed",w=>e.emit("serverClosed",w)),ZB(g,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(g),g.connect(e.s.connectOptions)},m)}s(f,"execute");for(var l=0;le.emit("serverOpening",u)),i.on("serverDescriptionChanged",u=>e.emit("serverDescriptionChanged",u)),i.on("serverClosed",u=>e.emit("serverClosed",u)),ZB(i,e,["commandStarted","commandSucceeded","commandFailed"]),i.connect(e.s.connectOptions)},a)}for(s(n,"connect");t.length>0;)n(t.shift(),r++)}s(z9,"connectServers");function qc(e,t,r){e.listeners(t).length>0&&e.emit(t,r)}s(qc,"emitSDAMEvent");Rt.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},Ts(this,wo);var r=this.s.seedlist.map(function(n){return new Zh(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))});if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new Sn(bi("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));qc(this,"topologyOpening",{topologyId:this.id}),z9(t,r)};Rt.prototype.auth=function(e,t){typeof t=="function"&&t(null,null)};Rt.prototype.destroy=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=this.s.connectingServers.length+1,n=s(()=>{r--,!(r>0)&&(qc(this,"topologyClosed",{topologyId:this.id}),typeof t=="function"&&t(null,null))},"serverDestroyed");if(this.state===Bt){typeof t=="function"&&t(null,null);return}Ts(this,Bt),this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var i=0;i"u"&&(r=e,e=void 0,t={}),typeof t=="function"&&(r=t,t=e),t=t||{};let n;e instanceof Ni?n=e:n=t.readPreference||Ni.primary;let i,a=eR(),u=s(()=>{if(j9(a)>=H9){i!=null?r(i,null):r(new Sn("Server selection timed out"));return}let f=this.s.replicaSetState.pickServer(n);if(f==null){setTimeout(u,GB);return}if(!(f instanceof Zh)){i=f,setTimeout(u,GB);return}this.s.debug&&this.emit("pickedServer",t.readPreference,f),r(null,f)},"_selectServer");u()};Rt.prototype.getServers=function(){return this.s.replicaSetState.allServers()};function Qh(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.self,i=e.op,a=e.ns,u=e.ops;if(n.state===Bt)return r(new Sn(bi("topology was destroyed")));let f=!e.retrying&&!!t.retryWrites&&t.session&&JB(n)&&!t.session.inTransaction()&&t.explain===void 0;if(!n.s.replicaSetState.hasPrimary()){if(n.s.disconnectHandler)return n.s.disconnectHandler.add(i,a,u,t,r);if(!f)return r(new Sn("no primary server found"))}let l=s((h,m)=>{if(!h)return r(null,m);if(!QB(h,n))return h=L9(h),r(h);if(f){let p=Object.assign({},e,{retrying:!0});return Qh(p,t,r)}return n.s.replicaSetState.primary&&(n.s.replicaSetState.primary.destroy(),n.s.replicaSetState.remove(n.s.replicaSetState.primary,{force:!0})),r(h)},"handler");r.operationId&&(l.operationId=r.operationId),f&&(t.session.incrementTransactionNumber(),t.willRetryWrite=f),n.s.replicaSetState.primary[i](a,u,t,l)}s(Qh,"executeWriteOperation");Rt.prototype.insert=function(e,t,r,n){Qh({self:this,op:"insert",ns:e,ops:t},r,n)};Rt.prototype.update=function(e,t,r,n){Qh({self:this,op:"update",ns:e,ops:t},r,n)};Rt.prototype.remove=function(e,t,r,n){Qh({self:this,op:"remove",ns:e,ops:t},r,n)};var V9=["findAndModify","insert","update","delete"];function Y9(e){return V9.some(t=>e[t])}s(Y9,"isWriteCommand");Rt.prototype.command=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===Bt)return n(new Sn(bi("topology was destroyed")));var i=this,a=r.readPreference?r.readPreference:Ni.primary;if(a.preference==="primary"&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);if(a.preference==="secondary"&&!this.s.replicaSetState.hasSecondary()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);if(a.preference!=="primary"&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);var u=this.s.replicaSetState.pickServer(a);if(!(u instanceof Zh))return n(u);if(i.s.debug&&i.emit("pickedServer",Ni.primary,u),u==null)return n(new Sn(bi("no server found that matches the provided readPreference %s",a)));let f=!r.retrying&&!!r.retryWrites&&r.session&&JB(i)&&!r.session.inTransaction()&&Y9(t),l=s((h,m)=>{if(!h)return n(null,m);if(!QB(h,i))return n(h);if(f){let p=Object.assign({},r,{retrying:!0});return this.command(e,t,p,n)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),n(h)},"cb");f&&(r.session.incrementTransactionNumber(),r.willRetryWrite=f),u.command(e,t,r,l)};Rt.prototype.cursor=function(e,t,r){r=r||{};let n=r.topology||this;var i=r.cursorFactory||this.s.Cursor;return new i(n,e,t,r)};rR.exports=Rt});var hR=E((wye,lR)=>{"use strict";var k9=require("util").inherits,bs=require("util").format,sR=require("events").EventEmitter,G9=yn().CoreCursor,K9=mn(),X9=jt().retrieveBSON,vn=X().MongoError,oR=kh(),J9=vt().diff,Z9=vt().cloneOptions,Q9=vt().SessionMixins,aR=vt().isRetryableWritesSupported,td=ce().relayEvents,ar=X9(),eX=vt().getMMAPError,tX=ce().makeClientMetadata,uR=vt().legacyIsRetryableWriteError,ed="disconnected",xa="connecting",u_="connected",_n="unreferenced",Or="destroying",Et="destroyed";function Uc(e,t){var r={disconnected:[xa,Or,Et,ed],connecting:[xa,Or,Et,u_,ed],connected:[u_,ed,Or,Et,_n],unreferenced:[_n,Or,Et],destroyed:[Et]},n=r[e.state];n&&n.indexOf(t)!==-1?e.state=t:e.s.logger.error(bs("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}s(Uc,"stateTransition");var rX=1,rd=["connect","close","error","timeout","parseError"],xt=s(function(e,t){t=t||{},this.id=rX++,Array.isArray(e)&&(e=e.reduce((r,n)=>(r.find(i=>i.host===n.host&&i.port===n.port)||r.push(n),r),[])),this.s={options:Object.assign({metadata:tX(t)},t),bson:t.bson||new ar([ar.Binary,ar.Code,ar.DBRef,ar.Decimal128,ar.Double,ar.Int32,ar.Long,ar.Map,ar.MaxKey,ar.MinKey,ar.ObjectId,ar.BSONRegExp,ar.Symbol,ar.Timestamp]),Cursor:t.cursorFactory||G9,logger:K9("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug=="boolean"?t.debug:!1,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeout0&&e.emit(t,r)}s(Lc,"emitSDAMEvent");var nX=["serverDescriptionChanged","error","close","timeout","parseError"];function cR(e,t,r){t=t||{},nX.forEach(n=>e.removeAllListeners(n)),e.destroy(t,r)}s(cR,"destroyServer");xt.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},Uc(this,xa);var r=this.s.seedlist.map(function(n){let i=new oR(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return td(i,t,["serverDescriptionChanged"]),i});Lc(this,"topologyOpening",{topologyId:this.id}),iX(t,r)};xt.prototype.auth=function(e,t){typeof t=="function"&&t(null,null)};function Ns(e){return function(){e.state===Et||e.state===Or||(wn(e.connectedProxies,e.disconnectedProxies,this),vo(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}s(Ns,"handleEvent");function Pc(e,t){return function(){var r=this;if(e.state===Et)return vo(e),wn(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if(t==="connect")if(e.ismaster=r.lastIsMaster(),e.ismaster.msg==="isdbgrid"){for(let i=0;i0&&e.state===xa)Uc(e,u_),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(e.disconnectedProxies.length===0)return e.s.logger.isWarn()&&e.s.logger.warn(bs("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new vn("no mongos proxies found in seed list"));c_(e,{firstConnect:!0})}}}s(Pc,"handleInitialConnectEvent");function iX(e,t){e.connectingProxies=e.connectingProxies.concat(t);var r=0;function n(i,a){setTimeout(function(){e.emit("serverOpening",{topologyId:e.id,address:i.name}),vo(e),i.once("close",Pc(e,"close")),i.once("timeout",Pc(e,"timeout")),i.once("parseError",Pc(e,"parseError")),i.once("error",Pc(e,"error")),i.once("connect",Pc(e,"connect")),td(i,e,["commandStarted","commandSucceeded","commandFailed"]),i.connect(e.s.connectOptions)},a)}s(n,"connect"),t.forEach(i=>n(i,r++))}s(iX,"connectProxies");function nd(e,t){let r=t&&t.transaction;if(r&&r.server){if(r.server.isConnected())return r.server;r.unpinServer()}for(var n=e.connectedProxies.slice(0),i=Number.MAX_VALUE,a=0;a0&&e.state===xa?e.emit("error",new vn("no mongos proxy available")):e.emit("close",e),iR(e,e.disconnectedProxies,function(){e.state===Et||e.state===Or||e.state===_n||(e.state===xa&&t.firstConnect?(e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e)):e.isConnected()?e.emit("reconnect",e):!e.isConnected()&&e.listeners("close").length>0&&e.emit("close",e),c_(e))});for(var a=0;a{n--,!(n>0)&&(vo(this),Lc(this,"topologyClosed",{topologyId:this.id}),Uc(this,Et),typeof t=="function"&&t(null,null))},"serverDestroyed");if(n===0){i();return}r.forEach(a=>{this.emit("serverClosed",{topologyId:this.id,address:a.name}),cR(a,e,i),wn(this.connectedProxies,this.disconnectedProxies,a)})};xt.prototype.isConnected=function(){return this.connectedProxies.length>0};xt.prototype.isDestroyed=function(){return this.state===Et};function id(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.self,i=e.op,a=e.ns,u=e.ops,f=nd(n,t.session);if(!f)return r(new vn("no mongos proxy available"));let l=!e.retrying&&!!t.retryWrites&&t.session&&aR(n)&&!t.session.inTransaction()&&t.explain===void 0,h=s((m,p)=>{if(!m)return r(null,p);if(!uR(m,n)||!l)return m=eX(m),r(m);if(f=nd(n,t.session),!f)return r(m);let g=Object.assign({},e,{retrying:!0});return id(g,t,r)},"handler");r.operationId&&(h.operationId=r.operationId),l&&(t.session.incrementTransactionNumber(),t.willRetryWrite=l),f[i](a,u,t,h)}s(id,"executeWriteOperation");xt.prototype.insert=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===Et)return n(new vn(bs("topology was destroyed")));if(!this.isConnected()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("insert",e,t,r,n);if(!this.isConnected())return n(new vn("no mongos proxy available"));id({self:this,op:"insert",ns:e,ops:t},r,n)};xt.prototype.update=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===Et)return n(new vn(bs("topology was destroyed")));if(!this.isConnected()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("update",e,t,r,n);if(!this.isConnected())return n(new vn("no mongos proxy available"));id({self:this,op:"update",ns:e,ops:t},r,n)};xt.prototype.remove=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===Et)return n(new vn(bs("topology was destroyed")));if(!this.isConnected()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("remove",e,t,r,n);if(!this.isConnected())return n(new vn("no mongos proxy available"));id({self:this,op:"remove",ns:e,ops:t},r,n)};var sX=["findAndModify","insert","update","delete"];function oX(e){return sX.some(t=>e[t])}s(oX,"isWriteCommand");xt.prototype.command=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===Et)return n(new vn(bs("topology was destroyed")));var i=this,a=nd(i,r.session);if((a==null||!a.isConnected())&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);if(a==null)return n(new vn("no mongos proxy available"));var u=Z9(r);u.topology=i;let f=!r.retrying&&r.retryWrites&&r.session&&aR(i)&&!r.session.inTransaction()&&oX(t),l=s((h,m)=>{if(!h)return n(null,m);if(!uR(h,i))return n(h);if(f){let p=Object.assign({},u,{retrying:!0});return this.command(e,t,p,n)}return n(h)},"cb");f&&(u.session.incrementTransactionNumber(),u.willRetryWrite=f),a.command(e,t,u,l)};xt.prototype.cursor=function(e,t,r){r=r||{};let n=r.topology||this;var i=r.cursorFactory||this.s.Cursor;return new i(n,e,t,r)};xt.prototype.selectServer=function(e,t,r){typeof e=="function"&&typeof r>"u"&&(r=e,e=void 0,t={}),typeof t=="function"&&(r=t,t=e,e=void 0),t=t||{};let n=nd(this,t.session);if(n==null){r(new vn("server selection failed"));return}this.s.debug&&this.emit("pickedServer",null,n),r(null,n)};xt.prototype.connections=function(){for(var e=[],t=0;t0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var r={topologyType:t,servers:[]},n=e.disconnectedProxies.concat(e.connectingProxies);r.servers=r.servers.concat(n.map(function(u){var f=u.getDescription();return f.type="Unknown",f})),r.servers=r.servers.concat(e.connectedProxies.map(function(u){var f=u.getDescription();return f.type="Mongos",f}));var i=J9(e.topologyDescription,r),a={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:r,diff:i};i.servers.length>0&&e.emit("topologyDescriptionChanged",a),e.topologyDescription=r}}s(vo,"emitTopologyDescriptionChanged");lR.exports=xt});var sd=E((Oye,dR)=>{"use strict";function Tt(e,r){var r=r||{};this._head=0,this._tail=0,this._capacity=r.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}s(Tt,"Denque");Tt.prototype.peekAt=s(function(t){var r=t;if(r===(r|0)){var n=this.size();if(!(r>=n||r<-n))return r<0&&(r+=n),r=this._head+r&this._capacityMask,this._list[r]}},"peekAt");Tt.prototype.get=s(function(t){return this.peekAt(t)},"get");Tt.prototype.peek=s(function(){if(this._head!==this._tail)return this._list[this._head]},"peek");Tt.prototype.peekFront=s(function(){return this.peek()},"peekFront");Tt.prototype.peekBack=s(function(){return this.peekAt(-1)},"peekBack");Object.defineProperty(Tt.prototype,"length",{get:s(function(){return this.size()},"length")});Tt.prototype.size=s(function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),r}},"shift");Tt.prototype.push=s(function(t){if(t===void 0)return this.size();var r=this._tail;return this._list[r]=t,this._tail=r+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&t<=r>>>2&&this._shrinkArray(),n}},"pop");Tt.prototype.removeOne=s(function(t){var r=t;if(r===(r|0)&&this._head!==this._tail){var n=this.size(),i=this._list.length;if(!(r>=n||r<-n)){r<0&&(r+=n),r=this._head+r&this._capacityMask;var a=this._list[r],u;if(t0;u--)this._list[r]=this._list[r=r-1+i&this._capacityMask];this._list[r]=void 0,this._head=this._head+1+i&this._capacityMask}else{for(u=n-1-t;u>0;u--)this._list[r]=this._list[r=r+1+i&this._capacityMask];this._list[r]=void 0,this._tail=this._tail-1+i&this._capacityMask}return a}}},"removeOne");Tt.prototype.remove=s(function(t,r){var n=t,i,a=r;if(n===(n|0)&&this._head!==this._tail){var u=this.size(),f=this._list.length;if(!(n>=u||n<-u||r<1)){if(n<0&&(n+=u),r===1||!r)return i=new Array(1),i[0]=this.removeOne(n),i;if(n===0&&n+r>=u)return i=this.toArray(),this.clear(),i;n+r>u&&(r=u-n);var l;for(i=new Array(r),l=0;l0;l--)this._list[n=n+1+f&this._capacityMask]=void 0;return i}if(t===0){for(this._head=this._head+r+f&this._capacityMask,l=r-1;l>0;l--)this._list[n=n+1+f&this._capacityMask]=void 0;return i}if(n0;l--)this.unshift(this._list[n=n-1+f&this._capacityMask]);for(n=this._head-1+f&this._capacityMask;a>0;)this._list[n=n-1+f&this._capacityMask]=void 0,a--;t<0&&(this._tail=n)}else{for(this._tail=n,n=n+r+f&this._capacityMask,l=u-(r+t);l>0;l--)this.push(this._list[n++]);for(n=this._tail;a>0;)this._list[n=n+1+f&this._capacityMask]=void 0,a--}return this._head<2&&this._tail>1e4&&this._tail<=f>>>2&&this._shrinkArray(),i}}},"remove");Tt.prototype.splice=s(function(t,r){var n=t;if(n===(n|0)){var i=this.size();if(n<0&&(n+=i),!(n>i))if(arguments.length>2){var a,u,f,l=arguments.length,h=this._list.length,m=2;if(!i||n0&&(this._head=this._head+n+h&this._capacityMask)):(f=this.remove(n,r),this._head=this._head+n+h&this._capacityMask);l>m;)this.unshift(arguments[--l]);for(a=n;a>0;a--)this.unshift(u[a-1])}else{u=new Array(i-(n+r));var p=u.length;for(a=0;athis._tail){for(a=this._head;a>>=1,this._capacityMask>>>=1},"_shrinkArray");dR.exports=Tt});var C_=E((Tye,pR)=>{"use strict";var __=class __{constructor(t,r,n,i){Object.assign(this,{topologyId:t,address:r,previousDescription:n,newDescription:i})}};s(__,"ServerDescriptionChangedEvent");var f_=__,w_=class w_{constructor(t,r){Object.assign(this,{topologyId:t,address:r})}};s(w_,"ServerOpeningEvent");var l_=w_,v_=class v_{constructor(t,r){Object.assign(this,{topologyId:t,address:r})}};s(v_,"ServerClosedEvent");var h_=v_,O_=class O_{constructor(t,r,n){Object.assign(this,{topologyId:t,previousDescription:r,newDescription:n})}};s(O_,"TopologyDescriptionChangedEvent");var d_=O_,E_=class E_{constructor(t){Object.assign(this,{topologyId:t})}};s(E_,"TopologyOpeningEvent");var p_=E_,T_=class T_{constructor(t){Object.assign(this,{topologyId:t})}};s(T_,"TopologyClosedEvent");var m_=T_,N_=class N_{constructor(t){Object.assign(this,{connectionId:t})}};s(N_,"ServerHeartbeatStartedEvent");var g_=N_,b_=class b_{constructor(t,r,n){Object.assign(this,{connectionId:n,duration:t,reply:r})}};s(b_,"ServerHeartbeatSucceededEvent");var y_=b_,A_=class A_{constructor(t,r,n){Object.assign(this,{connectionId:n,duration:t,failure:r})}};s(A_,"ServerHeartbeatFailedEvent");var S_=A_;pR.exports={ServerDescriptionChangedEvent:f_,ServerOpeningEvent:l_,ServerClosedEvent:h_,TopologyDescriptionChangedEvent:d_,TopologyOpeningEvent:p_,TopologyClosedEvent:m_,ServerHeartbeatStartedEvent:g_,ServerHeartbeatSucceededEvent:y_,ServerHeartbeatFailedEvent:S_}});var jc=E((bye,I_)=>{"use strict";typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0?I_.exports={nextTick:aX}:I_.exports=process;function aX(e,t,r,n){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var i=arguments.length,a,u;switch(i){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(s(function(){e.call(null,t)},"afterTickOne"));case 3:return process.nextTick(s(function(){e.call(null,t,r)},"afterTickTwo"));case 4:return process.nextTick(s(function(){e.call(null,t,r,n)},"afterTickThree"));default:for(a=new Array(i-1),u=0;u{var uX={}.toString;mR.exports=Array.isArray||function(e){return uX.call(e)=="[object Array]"}});var B_=E((Iye,yR)=>{yR.exports=require("stream")});var ad=E((R_,_R)=>{var od=require("buffer"),Ai=od.Buffer;function SR(e,t){for(var r in e)t[r]=e[r]}s(SR,"copyProps");Ai.from&&Ai.alloc&&Ai.allocUnsafe&&Ai.allocUnsafeSlow?_R.exports=od:(SR(od,R_),R_.Buffer=Ma);function Ma(e,t,r){return Ai(e,t,r)}s(Ma,"SafeBuffer");SR(Ai,Ma);Ma.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return Ai(e,t,r)};Ma.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=Ai(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};Ma.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Ai(e)};Ma.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return od.SlowBuffer(e)}});var Da=E(ur=>{function cX(e){return Array.isArray?Array.isArray(e):ud(e)==="[object Array]"}s(cX,"isArray");ur.isArray=cX;function fX(e){return typeof e=="boolean"}s(fX,"isBoolean");ur.isBoolean=fX;function lX(e){return e===null}s(lX,"isNull");ur.isNull=lX;function hX(e){return e==null}s(hX,"isNullOrUndefined");ur.isNullOrUndefined=hX;function dX(e){return typeof e=="number"}s(dX,"isNumber");ur.isNumber=dX;function pX(e){return typeof e=="string"}s(pX,"isString");ur.isString=pX;function mX(e){return typeof e=="symbol"}s(mX,"isSymbol");ur.isSymbol=mX;function gX(e){return e===void 0}s(gX,"isUndefined");ur.isUndefined=gX;function yX(e){return ud(e)==="[object RegExp]"}s(yX,"isRegExp");ur.isRegExp=yX;function SX(e){return typeof e=="object"&&e!==null}s(SX,"isObject");ur.isObject=SX;function _X(e){return ud(e)==="[object Date]"}s(_X,"isDate");ur.isDate=_X;function wX(e){return ud(e)==="[object Error]"||e instanceof Error}s(wX,"isError");ur.isError=wX;function vX(e){return typeof e=="function"}s(vX,"isFunction");ur.isFunction=vX;function OX(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e>"u"}s(OX,"isPrimitive");ur.isPrimitive=OX;ur.isBuffer=require("buffer").Buffer.isBuffer;function ud(e){return Object.prototype.toString.call(e)}s(ud,"objectToString")});var wR=E((Mye,x_)=>{typeof Object.create=="function"?x_.exports=s(function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))},"inherits"):x_.exports=s(function(t,r){if(r){t.super_=r;var n=s(function(){},"TempCtor");n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}},"inherits")});var qa=E((qye,D_)=>{try{if(M_=require("util"),typeof M_.inherits!="function")throw"";D_.exports=M_.inherits}catch{D_.exports=wR()}var M_});var OR=E((Pye,q_)=>{"use strict";function EX(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}s(EX,"_classCallCheck");var vR=ad().Buffer,Wc=require("util");function TX(e,t,r){e.copy(t,r)}s(TX,"copyBuffer");q_.exports=function(){function e(){EX(this,e),this.head=null,this.tail=null,this.length=0}return s(e,"BufferList"),e.prototype.push=s(function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},"push"),e.prototype.unshift=s(function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length},"unshift"),e.prototype.shift=s(function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}},"shift"),e.prototype.clear=s(function(){this.head=this.tail=null,this.length=0},"clear"),e.prototype.join=s(function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i},"join"),e.prototype.concat=s(function(r){if(this.length===0)return vR.alloc(0);for(var n=vR.allocUnsafe(r>>>0),i=this.head,a=0;i;)TX(i.data,n,a),a+=i.data.length,i=i.next;return n},"concat"),e}();Wc&&Wc.inspect&&Wc.inspect.custom&&(q_.exports.prototype[Wc.inspect.custom]=function(){var e=Wc.inspect({length:this.length});return this.constructor.name+" "+e})});var P_=E((Uye,ER)=>{"use strict";var cd=jc();function NX(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,cd.nextTick(fd,this,e)):cd.nextTick(fd,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(a){!t&&a?r._writableState?r._writableState.errorEmitted||(r._writableState.errorEmitted=!0,cd.nextTick(fd,r,a)):cd.nextTick(fd,r,a):t&&t(a)}),this)}s(NX,"destroy");function bX(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}s(bX,"undestroy");function fd(e,t){e.emit("error",t)}s(fd,"emitErrorNT");ER.exports={destroy:NX,undestroy:bX}});var NR=E((Wye,TR)=>{TR.exports=require("util").deprecate});var U_=E((Fye,MR)=>{"use strict";var Oo=jc();MR.exports=Mt;function AR(e){var t=this;this.next=null,this.entry=null,this.finish=function(){HX(t,e)}}s(AR,"CorkedRequest");var AX=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:Oo.nextTick,Pa;Mt.WritableState=$c;var CR=Object.create(Da());CR.inherits=qa();var CX={deprecate:NR()},IR=B_(),hd=ad().Buffer,IX=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function BX(e){return hd.from(e)}s(BX,"_uint8ArrayToBuffer");function RX(e){return hd.isBuffer(e)||e instanceof IX}s(RX,"_isUint8Array");var BR=P_();CR.inherits(Mt,IR);function xX(){}s(xX,"nop");function $c(e,t){Pa=Pa||Eo(),e=e||{};var r=t instanceof Pa;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,i=e.writableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(i||i===0)?this.highWaterMark=i:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var u=e.decodeStrings===!1;this.decodeStrings=!u,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(f){jX(t,f)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new AR(this)}s($c,"WritableState");$c.prototype.getBuffer=s(function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r},"getBuffer");(function(){try{Object.defineProperty($c.prototype,"buffer",{get:CX.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var ld;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(ld=Function.prototype[Symbol.hasInstance],Object.defineProperty(Mt,Symbol.hasInstance,{value:function(e){return ld.call(this,e)?!0:this!==Mt?!1:e&&e._writableState instanceof $c}})):ld=s(function(e){return e instanceof this},"realHasInstance");function Mt(e){if(Pa=Pa||Eo(),!ld.call(Mt,this)&&!(this instanceof Pa))return new Mt(e);this._writableState=new $c(e,this),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),IR.call(this)}s(Mt,"Writable");Mt.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function MX(e,t){var r=new Error("write after end");e.emit("error",r),Oo.nextTick(t,r)}s(MX,"writeAfterEnd");function DX(e,t,r,n){var i=!0,a=!1;return r===null?a=new TypeError("May not write null values to stream"):typeof r!="string"&&r!==void 0&&!t.objectMode&&(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),Oo.nextTick(n,a),i=!1),i}s(DX,"validChunk");Mt.prototype.write=function(e,t,r){var n=this._writableState,i=!1,a=!n.objectMode&&RX(e);return a&&!hd.isBuffer(e)&&(e=BX(e)),typeof t=="function"&&(r=t,t=null),a?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=xX),n.ended?MX(this,r):(a||DX(this,n,e,r))&&(n.pendingcb++,i=PX(this,n,a,e,t,r)),i};Mt.prototype.cork=function(){var e=this._writableState;e.corked++};Mt.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&RR(this,e))};Mt.prototype.setDefaultEncoding=s(function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},"setDefaultEncoding");function qX(e,t,r){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=hd.from(t,r)),t}s(qX,"decodeChunk");Object.defineProperty(Mt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function PX(e,t,r,n,i,a){if(!r){var u=qX(t,n,i);n!==u&&(r=!0,i="buffer",n=u)}var f=t.objectMode?1:n.length;t.length+=f;var l=t.length{"use strict";var DR=jc(),VX=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};LR.exports=Ci;var qR=Object.create(Da());qR.inherits=qa();var PR=F_(),W_=U_();qR.inherits(Ci,PR);for(j_=VX(W_.prototype),dd=0;dd{var md=require("buffer"),Ii=md.Buffer;function UR(e,t){for(var r in e)t[r]=e[r]}s(UR,"copyProps");Ii.from&&Ii.alloc&&Ii.allocUnsafe&&Ii.allocUnsafeSlow?jR.exports=md:(UR(md,$_),$_.Buffer=La);function La(e,t,r){return Ii(e,t,r)}s(La,"SafeBuffer");UR(Ii,La);La.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return Ii(e,t,r)};La.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=Ii(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};La.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Ii(e)};La.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return md.SlowBuffer(e)}});var V_=E($R=>{"use strict";var H_=WR().Buffer,FR=H_.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function GX(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}s(GX,"_normalizeEncoding");function KX(e){var t=GX(e);if(typeof t!="string"&&(H_.isEncoding===FR||!FR(e)))throw new Error("Unknown encoding: "+e);return t||e}s(KX,"normalizeEncoding");$R.StringDecoder=zc;function zc(e){this.encoding=KX(e);var t;switch(this.encoding){case"utf16le":this.text=tJ,this.end=rJ,t=4;break;case"utf8":this.fillLast=ZX,t=4;break;case"base64":this.text=nJ,this.end=iJ,t=3;break;default:this.write=sJ,this.end=oJ;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=H_.allocUnsafe(t)}s(zc,"StringDecoder");zc.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}s(z_,"utf8CheckByte");function XX(e,t,r){var n=t.length-1;if(n=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}s(XX,"utf8CheckIncomplete");function JX(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}s(JX,"utf8CheckExtraBytes");function ZX(e){var t=this.lastTotal-this.lastNeed,r=JX(this,e,t);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}s(ZX,"utf8FillLast");function QX(e,t){var r=XX(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}s(QX,"utf8Text");function eJ(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}s(eJ,"utf8End");function tJ(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}s(tJ,"utf16Text");function rJ(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}s(rJ,"utf16End");function nJ(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}s(nJ,"base64Text");function iJ(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}s(iJ,"base64End");function sJ(e){return e.toString(this.encoding)}s(sJ,"simpleWrite");function oJ(e){return e&&e.length?this.write(e):""}s(oJ,"simpleEnd")});var F_=E((Kye,ex)=>{"use strict";var ja=jc();ex.exports=ht;var aJ=gR(),Hc;ht.ReadableState=KR;var Gye=require("events").EventEmitter,YR=s(function(e,t){return e.listeners(t).length},"EElistenerCount"),X_=B_(),Vc=ad().Buffer,uJ=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cJ(e){return Vc.from(e)}s(cJ,"_uint8ArrayToBuffer");function fJ(e){return Vc.isBuffer(e)||e instanceof uJ}s(fJ,"_isUint8Array");var kR=Object.create(Da());kR.inherits=qa();var Y_=require("util"),Ge=void 0;Y_&&Y_.debuglog?Ge=Y_.debuglog("stream"):Ge=s(function(){},"debug");var lJ=OR(),GR=P_(),Ua;kR.inherits(ht,X_);var k_=["error","close","destroy","pause","resume"];function hJ(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):aJ(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]}s(hJ,"prependListener");function KR(e,t){Hc=Hc||Eo(),e=e||{};var r=t instanceof Hc;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,i=e.readableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(i||i===0)?this.highWaterMark=i:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new lJ,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(Ua||(Ua=V_().StringDecoder),this.decoder=new Ua(e.encoding),this.encoding=e.encoding)}s(KR,"ReadableState");function ht(e){if(Hc=Hc||Eo(),!(this instanceof ht))return new ht(e);this._readableState=new KR(e,this),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),X_.call(this)}s(ht,"Readable");Object.defineProperty(ht.prototype,"destroyed",{get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});ht.prototype.destroy=GR.destroy;ht.prototype._undestroy=GR.undestroy;ht.prototype._destroy=function(e,t){this.push(null),t(e)};ht.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=!0:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=Vc.from(e,t),t=""),n=!0),XR(this,e,t,!1,n)};ht.prototype.unshift=function(e){return XR(this,e,null,!0,!1)};function XR(e,t,r,n,i){var a=e._readableState;if(t===null)a.reading=!1,gJ(e,a);else{var u;i||(u=dJ(a,t)),u?e.emit("error",u):a.objectMode||t&&t.length>0?(typeof t!="string"&&!a.objectMode&&Object.getPrototypeOf(t)!==Vc.prototype&&(t=cJ(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):G_(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||t.length!==0?G_(e,a,t,!1):JR(e,a)):G_(e,a,t,!1))):n||(a.reading=!1)}return pJ(a)}s(XR,"readableAddChunk");function G_(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&gd(e)),JR(e,t)}s(G_,"addChunk");function dJ(e,t){var r;return!fJ(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new TypeError("Invalid non-string/buffer chunk")),r}s(dJ,"chunkInvalid");function pJ(e){return!e.ended&&(e.needReadable||e.length=zR?e=zR:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}s(mJ,"computeNewHighWaterMark");function HR(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=mJ(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}s(HR,"howMuchToRead");ht.prototype.read=function(e){Ge("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return Ge("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?K_(this):gd(this),null;if(e=HR(e,t),e===0&&t.ended)return t.length===0&&K_(this),null;var n=t.needReadable;Ge("need readable",n),(t.length===0||t.length-e0?i=ZR(e,t):i=null,i===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&K_(this)),i!==null&&this.emit("data",i),i};function gJ(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,gd(e)}}s(gJ,"onEofChunk");function gd(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Ge("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?ja.nextTick(VR,e):VR(e))}s(gd,"emitReadable");function VR(e){Ge("emit readable"),e.emit("readable"),J_(e)}s(VR,"emitReadable_");function JR(e,t){t.readingMore||(t.readingMore=!0,ja.nextTick(yJ,e,t))}s(JR,"maybeReadMore");function yJ(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length1&&QR(n.pipes,e)!==-1)&&!h&&(Ge("false write response, pause",n.awaitDrain),n.awaitDrain++,p=!0),r.pause())}s(g,"ondata");function w(M){Ge("onerror",M),A(),e.removeListener("error",w),YR(e,"error")===0&&e.emit("error",M)}s(w,"onerror"),hJ(e,"error",w);function O(){e.removeListener("finish",N),A()}s(O,"onclose"),e.once("close",O);function N(){Ge("onfinish"),e.removeListener("close",O),A()}s(N,"onfinish"),e.once("finish",N);function A(){Ge("unpipe"),r.unpipe(e)}return s(A,"unpipe"),e.emit("pipe",r),n.flowing||(Ge("pipe resume"),r.resume()),e};function SJ(e){return function(){var t=e._readableState;Ge("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&YR(e,"data")&&(t.flowing=!0,J_(e))}}s(SJ,"pipeOnDrain");ht.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.head.data:r=t.buffer.concat(t.length),t.buffer.clear()):r=OJ(e,t.buffer,t.decoder),r}s(ZR,"fromList");function OJ(e,t,r){var n;return ea.length?a.length:e;if(u===a.length?i+=a:i+=a.slice(0,e),e-=u,e===0){u===a.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=a.slice(u));break}++n}return t.length-=n,i}s(EJ,"copyFromBufferString");function TJ(e,t){var r=Vc.allocUnsafe(e),n=t.head,i=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var a=n.data,u=e>a.length?a.length:e;if(a.copy(r,r.length-e,0,u),e-=u,e===0){u===a.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(u));break}++i}return t.length-=i,r}s(TJ,"copyFromBuffer");function K_(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,ja.nextTick(NJ,t,e))}s(K_,"endReadable");function NJ(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"))}s(NJ,"endReadableNT");function QR(e,t){for(var r=0,n=e.length;r{"use strict";nx.exports=Bi;var yd=Eo(),rx=Object.create(Da());rx.inherits=qa();rx.inherits(Bi,yd);function bJ(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";ox.exports=Yc;var ix=Z_(),sx=Object.create(Da());sx.inherits=qa();sx.inherits(Yc,ix);function Yc(e){if(!(this instanceof Yc))return new Yc(e);ix.call(this,e)}s(Yc,"PassThrough");Yc.prototype._transform=function(e,t,r){r(null,e)}});var ux=E((Gt,Sd)=>{var Xn=require("stream");process.env.READABLE_STREAM==="disable"&&Xn?(Sd.exports=Xn,Gt=Sd.exports=Xn.Readable,Gt.Readable=Xn.Readable,Gt.Writable=Xn.Writable,Gt.Duplex=Xn.Duplex,Gt.Transform=Xn.Transform,Gt.PassThrough=Xn.PassThrough,Gt.Stream=Xn):(Gt=Sd.exports=F_(),Gt.Stream=Xn||Gt,Gt.Readable=Gt,Gt.Writable=U_(),Gt.Duplex=Eo(),Gt.Transform=Z_(),Gt.PassThrough=ax())});var fx=E((tSe,cx)=>{"use strict";var Q_=ux().Duplex,CJ=require("util"),Jn=qn().Buffer;function tt(e){if(!(this instanceof tt))return new tt(e);if(this._bufs=[],this.length=0,typeof e=="function"){this._callback=e;var t=s(function(n){this._callback&&(this._callback(n),this._callback=null)},"piper").bind(this);this.on("pipe",s(function(n){n.on("error",t)},"onPipe")),this.on("unpipe",s(function(n){n.removeListener("error",t)},"onUnpipe"))}else this.append(e);Q_.call(this)}s(tt,"BufferList");CJ.inherits(tt,Q_);tt.prototype._offset=s(function(t){var r=0,n=0,i;if(t===0)return[0,0];for(;nthis.length||t<0)){var r=this._offset(t);return this._bufs[r[0]][r[1]]}},"get");tt.prototype.slice=s(function(t,r){return typeof t=="number"&&t<0&&(t+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,t,r)},"slice");tt.prototype.copy=s(function(t,r,n,i){if((typeof n!="number"||n<0)&&(n=0),(typeof i!="number"||i>this.length)&&(i=this.length),n>=this.length||i<=0)return t||Jn.alloc(0);var a=!!t,u=this._offset(n),f=i-n,l=f,h=a&&r||0,m=u[1],p,g;if(n===0&&i==this.length){if(!a)return this._bufs.length===1?this._bufs[0]:Jn.concat(this._bufs,this.length);for(g=0;gp)this._bufs[g].copy(t,h,m),h+=p;else{this._bufs[g].copy(t,h,m,m+l),h+=p;break}l-=p,m&&(m=0)}return t.length>h?t.slice(0,h):t},"copy");tt.prototype.shallowSlice=s(function(t,r){if(t=t||0,r=typeof r!="number"?this.length:r,t<0&&(t+=this.length),r<0&&(r+=this.length),t===r)return new tt;var n=this._offset(t),i=this._offset(r),a=this._bufs.slice(n[0],i[0]+1);return i[1]==0?a.pop():a[a.length-1]=a[a.length-1].slice(0,i[1]),n[1]!=0&&(a[0]=a[0].slice(n[1])),new tt(a)},"shallowSlice");tt.prototype.toString=s(function(t,r,n){return this.slice(r,n).toString(t)},"toString");tt.prototype.consume=s(function(t){if(t=Math.trunc(t),Number.isNaN(t)||t<=0)return this;for(;this._bufs.length;)if(t>=this._bufs[0].length)t-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(t),this.length-=t;break}return this},"consume");tt.prototype.duplicate=s(function(){for(var t=0,r=new tt;tthis.length?this.length:t;var n=this._offset(t),i=n[0],a=n[1];for(i;i=e.length){var l=u.indexOf(e,a);if(l!==-1)return this._reverseOffset([i,l]);a=u.length-e.length+1}else{var h=this._reverseOffset([i,a]);if(this._match(h,e))return h;a++}}a=0}return-1};tt.prototype._match=function(e,t){if(this.length-e{"use strict";var IJ=require("stream").Duplex,BJ=fx(),lx=X().MongoParseError,RJ=vi().decompress,hx=Xr().Response,dx=oo().BinMsg,xJ=X().MongoError,MJ=et().opcodes.OP_COMPRESSED,px=et().opcodes.OP_MSG,As=et().MESSAGE_HEADER_SIZE,mx=et().COMPRESSION_DETAILS_SIZE,DJ=et().opcodes,qJ=vi().compress,PJ=vi().compressorIDs,LJ=vi().uncompressibleCommands,UJ=oo().Msg,jJ=1024*1024*16*4,ew=Symbol("buffer"),nw=class nw extends IJ{constructor(t){t=t||{},super(t),this.bson=t.bson,this.maxBsonMessageSize=t.maxBsonMessageSize||jJ,this[ew]=new BJ}_write(t,r,n){this[ew].append(t),rw(this,n)}_read(){}writeCommand(t,r){if(!(r&&!!r.agreedCompressor)||!WJ(t)){let f=t.toBin();this.push(Array.isArray(f)?Buffer.concat(f):f);return}let i=Buffer.concat(t.toBin()),a=i.slice(As),u=i.readInt32LE(12);qJ({options:r},a,(f,l)=>{if(f){r.cb(f,null);return}let h=Buffer.alloc(As);h.writeInt32LE(As+mx+l.length,0),h.writeInt32LE(t.requestId,4),h.writeInt32LE(0,8),h.writeInt32LE(DJ.OP_COMPRESSED,12);let m=Buffer.alloc(mx);m.writeInt32LE(u,0),m.writeInt32LE(a.length,4),m.writeUInt8(PJ[r.agreedCompressor],8),this.push(Buffer.concat([h,m,l]))})}};s(nw,"MessageStream");var tw=nw;function WJ(e){let t=e instanceof UJ?e.command:e.query,r=Object.keys(t)[0];return!LJ.has(r)}s(WJ,"canCompress");function rw(e,t){let r=e[ew];if(r.length<4){t();return}let n=r.readInt32LE(0);if(n<0){t(new lx(`Invalid message size: ${n}`));return}if(n>e.maxBsonMessageSize){t(new lx(`Invalid message size: ${n}, max allowed: ${e.maxBsonMessageSize}`));return}if(n>r.length){t();return}let i=r.slice(0,n);r.consume(n);let a={length:i.readInt32LE(0),requestId:i.readInt32LE(4),responseTo:i.readInt32LE(8),opCode:i.readInt32LE(12)},u=a.opCode===px?dx:hx,f=e.responseOptions;if(a.opCode!==MJ){let m=i.slice(As);e.emit("message",new u(e.bson,i,a,m,f)),r.length>=4?rw(e,t):t();return}a.fromCompressed=!0,a.opCode=i.readInt32LE(As),a.length=i.readInt32LE(As+4);let l=i[As+8],h=i.slice(As+9);u=a.opCode===px?dx:hx,RJ(l,h,(m,p)=>{if(m){t(m);return}if(p.length!==a.length){t(new xJ("Decompressing a compressed message from the server failed. The message is corrupt."));return}e.emit("message",new u(e.bson,i,a,p,f)),r.length>=4?rw(e,t):t()})}s(rw,"processIncomingData");gx.exports=tw});var wx=E((sSe,_x)=>{"use strict";var Sx=io().parseServerType,FJ=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"],sw=class sw{constructor(t,r){this.address=t,this.type=Sx(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=r&&r.compression&&Array.isArray(r.compression.compressors)?r.compression.compressors:[]}receiveResponse(t){this.type=Sx(t),FJ.forEach(r=>{typeof t[r]<"u"&&(this[r]=t[r])}),t.compression&&(this.compressor=this.compressors.filter(r=>t.compression.indexOf(r)!==-1)[0])}};s(sw,"StreamDescription");var iw=sw;_x.exports={StreamDescription:iw}});var hw=E((aSe,Tx)=>{"use strict";var $J=require("events"),zJ=yx(),vx=X().MongoError,HJ=X().MongoNetworkError,VJ=X().MongoNetworkTimeoutError,YJ=X().MongoWriteConcernError,kJ=gh(),GJ=wx().StreamDescription,To=G0(),_d=JS(),KJ=gs().updateSessionFromResponse,XJ=ce().uuidV4,aw=x().now,JJ=x().calculateDurationInMs,Cs=Symbol("stream"),Ri=Symbol("queue"),Wa=Symbol("messageStream"),Ox=Symbol("generation"),ow=Symbol("lastUseTime"),fw=Symbol("clusterTime"),Is=Symbol("description"),Ex=Symbol("ismaster"),uw=Symbol("autoEncrypter"),lw=class lw extends $J{constructor(t,r){super(r),this.id=r.id,this.address=QJ(t),this.bson=r.bson,this.socketTimeout=typeof r.socketTimeout=="number"?r.socketTimeout:0,this.host=r.host||"localhost",this.port=r.port||27017,this.monitorCommands=typeof r.monitorCommands=="boolean"?r.monitorCommands:!1,this.serverApi=r.serverApi,this.closed=!1,this.destroyed=!1,this[Is]=new GJ(this.address,r),this[Ox]=r.generation,this[ow]=aw(),r.autoEncrypter&&(this[uw]=r.autoEncrypter),this[Ri]=new Map,this[Wa]=new zJ(r),this[Wa].on("message",ZJ(this)),this[Cs]=t,t.on("error",()=>{}),this[Wa].on("error",n=>this.handleIssue({destroy:n})),t.on("close",()=>this.handleIssue({isClose:!0})),t.on("timeout",()=>this.handleIssue({isTimeout:!0,destroy:!0})),t.pipe(this[Wa]),this[Wa].pipe(t)}get description(){return this[Is]}get ismaster(){return this[Ex]}set ismaster(t){this[Is].receiveResponse(t),this[Ex]=t}get generation(){return this[Ox]||0}get idleTime(){return JJ(this[ow])}get clusterTime(){return this[fw]}get stream(){return this[Cs]}markAvailable(){this[ow]=aw()}handleIssue(t){if(!this.closed){t.destroy&&this[Cs].destroy(typeof t.destroy=="boolean"?void 0:t.destroy),this.closed=!0;for(let r of this[Ri]){let n=r[1];t.isTimeout?n.cb(new VJ(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:this.ismaster==null})):t.isClose?n.cb(new HJ(`connection ${this.id} to ${this.address} closed`)):n.cb(typeof t.destroy=="boolean"?void 0:t.destroy)}this[Ri].clear(),this.emit("close")}}destroy(t,r){if(typeof t=="function"&&(r=t,t={}),t=Object.assign({force:!1},t),this[Cs]==null||this.destroyed){this.destroyed=!0,typeof r=="function"&&r();return}if(t.force){this[Cs].destroy(),this.destroyed=!0,typeof r=="function"&&r();return}this[Cs].end(n=>{this.destroyed=!0,typeof r=="function"&&r(n)})}applyApiVersion(t){return this.serverApi&&(t.serverApi=this.serverApi),t}command(t,r,n,i){typeof n=="function"&&(i=n,n={}),To.command(No(this),t,r,this.applyApiVersion(n),i)}query(t,r,n,i,a){To.query(No(this),t,r,n,this.applyApiVersion(i),a)}getMore(t,r,n,i,a){To.getMore(No(this),t,r,n,this.applyApiVersion(i),a)}killCursors(t,r,n){To.killCursors(No(this),t,r,this.applyApiVersion({}),n)}insert(t,r,n,i){To.insert(No(this),t,r,this.applyApiVersion(n),i)}update(t,r,n,i){To.update(No(this),t,r,this.applyApiVersion(n),i)}remove(t,r,n,i){To.remove(No(this),t,r,this.applyApiVersion(n),i)}};s(lw,"Connection");var cw=lw;function No(e){let t={description:e.description,clusterTime:e[fw],s:{bson:e.bson,pool:{write:eZ.bind(e),isConnected:()=>!0}}};return e[uw]&&(t.autoEncrypter=e[uw]),t}s(No,"makeServerTrampoline");function ZJ(e){return s(function(r){if(e.emit("message",r),!e[Ri].has(r.responseTo))return;let n=e[Ri].get(r.responseTo),i=n.cb;e[Ri].delete(r.responseTo),r.moreToCome?e[Ri].set(r.requestId,n):n.socketTimeoutOverride&&e[Cs].setTimeout(e.socketTimeout);try{r.parse(n)}catch(a){i(new vx(a));return}if(r.documents[0]){let a=r.documents[0],u=n.session;if(u&&KJ(u,a),a.$clusterTime&&(e[fw]=a.$clusterTime,e.emit("clusterTimeReceived",a.$clusterTime)),n.command){if(a.writeConcernError){i(new YJ(a.writeConcernError,a));return}if(a.ok===0||a.$err||a.errmsg||a.code){i(new vx(a));return}}}i(void 0,new kJ(n.fullResult?r:r.documents[0],e,r))},"messageHandler")}s(ZJ,"messageHandler");function QJ(e){return typeof e.address=="function"?`${e.remoteAddress}:${e.remotePort}`:XJ().toString("hex")}s(QJ,"streamIdentifier");function eZ(e,t,r){typeof t=="function"&&(r=t),t=t||{};let n={requestId:e.requestId,cb:r,session:t.session,fullResult:typeof t.fullResult=="boolean"?t.fullResult:!1,noResponse:typeof t.noResponse=="boolean"?t.noResponse:!1,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:typeof t.promoteLongs=="boolean"?t.promoteLongs:!0,promoteValues:typeof t.promoteValues=="boolean"?t.promoteValues:!0,promoteBuffers:typeof t.promoteBuffers=="boolean"?t.promoteBuffers:!1,bsonRegExp:typeof t.bsonRegExp=="boolean"?t.bsonRegExp:!1,raw:typeof t.raw=="boolean"?t.raw:!1};this[Is]&&this[Is].compressor&&(n.agreedCompressor=this[Is].compressor,this[Is].zlibCompressionLevel&&(n.zlibCompressionLevel=this[Is].zlibCompressionLevel)),typeof t.socketTimeout=="number"&&(n.socketTimeoutOverride=!0,this[Cs].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new _d.CommandStartedEvent(this,e)),n.started=aw(),n.cb=(i,a)=>{i?this.emit("commandFailed",new _d.CommandFailedEvent(this,e,i,n.started)):a&&a.result&&(a.result.ok===0||a.result.$err)?this.emit("commandFailed",new _d.CommandFailedEvent(this,e,a.result,n.started)):this.emit("commandSucceeded",new _d.CommandSucceededEvent(this,e,a,n.started)),typeof r=="function"&&r(i,a)}),n.noResponse||this[Ri].set(n.requestId,n);try{this[Wa].writeCommand(e,n)}catch(i){if(!n.noResponse){this[Ri].delete(n.requestId),n.cb(i);return}}n.noResponse&&n.cb()}s(eZ,"write");Tx.exports={Connection:cw}});var Ax=E((cSe,bx)=>{"use strict";var Nx=X().MongoError,mw=class mw extends Nx{constructor(t){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=t.address}};s(mw,"PoolClosedError");var dw=mw,gw=class gw extends Nx{constructor(t){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=t.address}};s(gw,"WaitQueueTimeoutError");var pw=gw;bx.exports={PoolClosedError:dw,WaitQueueTimeoutError:pw}});var kc=E((lSe,Cx)=>{"use strict";var Aw=class Aw{constructor(t){this.time=new Date,this.address=t.address}};s(Aw,"ConnectionPoolMonitoringEvent");var On=Aw,Cw=class Cw extends On{constructor(t){super(t),this.options=t.options}};s(Cw,"ConnectionPoolCreatedEvent");var yw=Cw,Iw=class Iw extends On{constructor(t){super(t)}};s(Iw,"ConnectionPoolClosedEvent");var Sw=Iw,Bw=class Bw extends On{constructor(t,r){super(t),this.connectionId=r.id}};s(Bw,"ConnectionCreatedEvent");var _w=Bw,Rw=class Rw extends On{constructor(t,r){super(t),this.connectionId=r.id}};s(Rw,"ConnectionReadyEvent");var ww=Rw,xw=class xw extends On{constructor(t,r,n){super(t),this.connectionId=r.id,this.reason=n||"unknown"}};s(xw,"ConnectionClosedEvent");var vw=xw,Mw=class Mw extends On{constructor(t){super(t)}};s(Mw,"ConnectionCheckOutStartedEvent");var Ow=Mw,Dw=class Dw extends On{constructor(t,r){super(t),this.reason=r}};s(Dw,"ConnectionCheckOutFailedEvent");var Ew=Dw,qw=class qw extends On{constructor(t,r){super(t),this.connectionId=r.id}};s(qw,"ConnectionCheckedOutEvent");var Tw=qw,Pw=class Pw extends On{constructor(t,r){super(t),this.connectionId=r.id}};s(Pw,"ConnectionCheckedInEvent");var Nw=Pw,Lw=class Lw extends On{constructor(t){super(t)}};s(Lw,"ConnectionPoolClearedEvent");var bw=Lw,tZ=["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];Cx.exports={CMAP_EVENT_NAMES:tZ,ConnectionPoolCreatedEvent:yw,ConnectionPoolClosedEvent:Sw,ConnectionCreatedEvent:_w,ConnectionReadyEvent:ww,ConnectionClosedEvent:vw,ConnectionCheckOutStartedEvent:Ow,ConnectionCheckOutFailedEvent:Ew,ConnectionCheckedOutEvent:Tw,ConnectionCheckedInEvent:Nw,ConnectionPoolClearedEvent:bw}});var Wx=E((dSe,jx)=>{"use strict";var Ix=sd(),Bx=require("events").EventEmitter,rZ=mn(),nZ=x().makeCounter,iZ=X().MongoError,sZ=hw().Connection,oZ=ce().eachAsync,aZ=Ih(),uZ=ce().relayEvents,xx=Ax(),cZ=xx.PoolClosedError,fZ=xx.WaitQueueTimeoutError,Zn=kc(),lZ=Zn.ConnectionPoolCreatedEvent,hZ=Zn.ConnectionPoolClosedEvent,dZ=Zn.ConnectionCreatedEvent,pZ=Zn.ConnectionReadyEvent,Mx=Zn.ConnectionClosedEvent,mZ=Zn.ConnectionCheckOutStartedEvent,Uw=Zn.ConnectionCheckOutFailedEvent,Rx=Zn.ConnectionCheckedOutEvent,gZ=Zn.ConnectionCheckedInEvent,yZ=Zn.ConnectionPoolClearedEvent,Dx=Symbol("logger"),xi=Symbol("connections"),Kc=Symbol("permits"),wd=Symbol("minPoolSizeTimer"),Gc=Symbol("generation"),vd=Symbol("connectionCounter"),Od=Symbol("cancellationToken"),Bs=Symbol("waitQueue"),Ed=Symbol("cancelled"),SZ=new Set(["ssl","bson","connectionType","serverApi","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function _Z(e,t){let r=Array.from(SZ).reduce((n,i)=>(Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]),n),{});return Object.freeze(Object.assign({},t,r))}s(_Z,"resolveOptions");var Fw=class Fw extends Bx{constructor(t){if(super(),t=t||{},this.closed=!1,this.options=_Z(t,{connectionType:sZ,maxPoolSize:typeof t.maxPoolSize=="number"?t.maxPoolSize:100,minPoolSize:typeof t.minPoolSize=="number"?t.minPoolSize:0,maxIdleTimeMS:typeof t.maxIdleTimeMS=="number"?t.maxIdleTimeMS:0,waitQueueTimeoutMS:typeof t.waitQueueTimeoutMS=="number"?t.waitQueueTimeoutMS:0,autoEncrypter:t.autoEncrypter,metadata:t.metadata,useUnifiedTopology:t.useUnifiedTopology}),t.minSize>t.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maximum pool size");this[Dx]=rZ("ConnectionPool",t),this[xi]=new Ix,this[Kc]=this.options.maxPoolSize,this[wd]=void 0,this[Gc]=0,this[vd]=nZ(1),this[Od]=new Bx,this[Od].setMaxListeners(1/0),this[Bs]=new Ix,process.nextTick(()=>{this.emit("connectionPoolCreated",new lZ(this)),qx(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[Gc]}get totalConnectionCount(){return this[xi].length+(this.options.maxPoolSize-this[Kc])}get availableConnectionCount(){return this[xi].length}get waitQueueSize(){return this[Bs].length}checkOut(t){if(this.emit("connectionCheckOutStarted",new mZ(this)),this.closed){this.emit("connectionCheckOutFailed",new Uw(this,"poolClosed")),t(new cZ(this));return}let r={callback:t},n=this,i=this.options.waitQueueTimeoutMS;i&&(r.timer=setTimeout(()=>{r[Ed]=!0,r.timer=void 0,n.emit("connectionCheckOutFailed",new Uw(n,"timeout")),r.callback(new fZ(n))},i)),this[Bs].push(r),process.nextTick(()=>Ww(this))}checkIn(t){let r=this.closed,n=Px(this,t),i=!!(r||n||t.closed);if(i||(t.markAvailable(),this[xi].push(t)),this.emit("connectionCheckedIn",new gZ(this,t)),i){let a=t.closed?"error":r?"poolClosed":"stale";Ux(this,t,a)}process.nextTick(()=>Ww(this))}clear(){this[Gc]+=1,this.emit("connectionPoolCleared",new yZ(this))}close(t,r){if(typeof t=="function"&&(r=t),t=Object.assign({force:!1},t),this.closed)return r();for(this[Od].emit("cancel");this.waitQueueSize;){let n=this[Bs].pop();clearTimeout(n.timer),n[Ed]||n.callback(new iZ("connection pool closed"))}this[wd]&&clearTimeout(this[wd]),typeof this[vd].return=="function"&&this[vd].return(),this.closed=!0,oZ(this[xi].toArray(),(n,i)=>{this.emit("connectionClosed",new Mx(this,n,"poolClosed")),n.destroy(t,i)},n=>{this[xi].clear(),this.emit("connectionPoolClosed",new hZ(this)),r(n)})}withConnection(t,r){this.checkOut((n,i)=>{t(n,i,(a,u)=>{typeof r=="function"&&(a?r(a):r(void 0,u)),i&&this.checkIn(i)})})}};s(Fw,"ConnectionPool");var jw=Fw;function qx(e){if(e.closed||e.options.minPoolSize===0)return;let t=e.options.minPoolSize;for(let r=e.totalConnectionCount;rqx(e),10)}s(qx,"ensureMinPoolSize");function Px(e,t){return t.generation!==e[Gc]}s(Px,"connectionIsStale");function wZ(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}s(wZ,"connectionIsIdle");function Lx(e,t){let r=Object.assign({id:e[vd].next().value,generation:e[Gc]},e.options);e[Kc]--,aZ(r,e[Od],(n,i)=>{if(n){e[Kc]++,e[Dx].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),typeof t=="function"&&t(n);return}if(e.closed){i.destroy({force:!0});return}if(uZ(i,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new dZ(e,i)),i.markAvailable(),e.emit("connectionReady",new pZ(e,i)),typeof t=="function"){t(void 0,i);return}e[xi].push(i),process.nextTick(()=>Ww(e))})}s(Lx,"createConnection");function Ux(e,t,r){e.emit("connectionClosed",new Mx(e,t,r)),e[Kc]++,process.nextTick(()=>t.destroy())}s(Ux,"destroyConnection");function Ww(e){if(e.closed)return;for(;e.waitQueueSize;){let r=e[Bs].peekFront();if(r[Ed]){e[Bs].shift();continue}if(!e.availableConnectionCount)break;let n=e[xi].shift(),i=Px(e,n),a=wZ(e,n);if(!i&&!a&&!n.closed){e.emit("connectionCheckedOut",new Rx(e,n)),clearTimeout(r.timer),e[Bs].shift(),r.callback(void 0,n);return}let u=n.closed?"error":i?"stale":"idle";Ux(e,n,u)}let t=e.options.maxPoolSize;if(e.waitQueueSize&&(t<=0||e.totalConnectionCount{let i=e[Bs].shift();if(i==null||i[Ed]){r==null&&e[xi].push(n);return}r?e.emit("connectionCheckOutFailed",new Uw(e,r)):e.emit("connectionCheckedOut",new Rx(e,n)),clearTimeout(i.timer),i.callback(r,n)});return}}s(Ww,"processWaitQueue");jx.exports={ConnectionPool:jw}});var Jx=E((mSe,Xx)=>{"use strict";var vZ=tr().ServerType,Fx=require("events"),kx=Ih(),OZ=hw().Connection,Gx=tr(),EZ=ce().makeStateMachine,TZ=X().MongoNetworkError,NZ=jt().retrieveBSON(),$x=x().makeInterruptableAsyncInterval,Td=x().calculateDurationInMs,$w=x().now,Vw=C_(),zx=Vw.ServerHeartbeatStartedEvent,Hx=Vw.ServerHeartbeatSucceededEvent,bZ=Vw.ServerHeartbeatFailedEvent,Jc=Symbol("server"),Er=Symbol("monitorId"),Nt=Symbol("connection"),bo=Symbol("cancellationToken"),Mi=Symbol("rttPinger"),Xc=Symbol("roundTripTime"),xs=Gx.STATE_CLOSED,Rs=Gx.STATE_CLOSING,Fa="idle",$a="monitoring",za=EZ({[Rs]:[Rs,Fa,xs],[xs]:[xs,$a],[Fa]:[Fa,$a,Rs],[$a]:[$a,Fa,Rs]}),AZ=new Set([Rs,xs,$a]);function Zc(e){return e.s.state===xs||e.s.state===Rs}s(Zc,"isInCloseState");var Yw=class Yw extends Fx{constructor(t,r){super(r),this[Jc]=t,this[Nt]=void 0,this[bo]=new Fx,this[bo].setMaxListeners(1/0),this[Er]=null,this.s={state:xs},this.address=t.description.address,this.options=Object.freeze({connectTimeoutMS:typeof r.connectionTimeout=="number"?r.connectionTimeout:typeof r.connectTimeoutMS=="number"?r.connectTimeoutMS:1e4,heartbeatFrequencyMS:typeof r.heartbeatFrequencyMS=="number"?r.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:typeof r.minHeartbeatFrequencyMS=="number"?r.minHeartbeatFrequencyMS:500,useUnifiedTopology:r.useUnifiedTopology});let n=Object.assign({id:"",host:t.description.host,port:t.description.port,bson:t.s.bson,connectionType:OZ},t.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0,bsonRegExp:!0});delete n.credentials,delete n.autoEncrypter,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==xs)return;let t=this.options.heartbeatFrequencyMS,r=this.options.minHeartbeatFrequencyMS;this[Er]=$x(Yx(this),{interval:t,minInterval:r,immediate:!0})}requestCheck(){AZ.has(this.s.state)||this[Er].wake()}reset(){let t=this[Jc].description.topologyVersion;if(Zc(this)||t==null)return;za(this,Rs),Vx(this),za(this,Fa);let r=this.options.heartbeatFrequencyMS,n=this.options.minHeartbeatFrequencyMS;this[Er]=$x(Yx(this),{interval:r,minInterval:n})}close(){Zc(this)||(za(this,Rs),Vx(this),this.emit("close"),za(this,xs))}};s(Yw,"Monitor");var zw=Yw;function Vx(e){e[Er]&&(e[Er].stop(),e[Er]=null),e[Mi]&&(e[Mi].close(),e[Mi]=void 0),e[bo].emit("cancel"),e[Er]&&(clearTimeout(e[Er]),e[Er]=void 0),e[Nt]&&e[Nt].destroy({force:!0})}s(Vx,"resetMonitorState");function CZ(e,t){let r=$w();e.emit("serverHeartbeatStarted",new zx(e.address));function n(i){e[Nt]&&(e[Nt].destroy({force:!0}),e[Nt]=void 0),e.emit("serverHeartbeatFailed",new bZ(Td(r),i,e.address)),e.emit("resetServer",i),e.emit("resetConnectionPool"),t(i)}if(s(n,"failureHandler"),e[Nt]!=null&&!e[Nt].closed){let i=e.options.connectTimeoutMS,a=e.options.heartbeatFrequencyMS,u=e[Jc].description.topologyVersion,f=u!=null,l=e[Nt].serverApi,h=e[Nt].helloOk,m={[l||h?"hello":"ismaster"]:!0};h&&(m.helloOk=h);let p={socketTimeout:i};f&&(m.maxAwaitTimeMS=a,m.topologyVersion=IZ(u),i&&(p.socketTimeout=i+a),p.exhaustAllowed=!0,e[Mi]==null&&(e[Mi]=new Hw(e[bo],e.connectOptions))),e[Nt].command("admin.$cmd",m,p,(g,w)=>{if(g){n(g);return}let O=w.result,N=e[Mi];"isWritablePrimary"in O&&(O.ismaster=O.isWritablePrimary);let A=f&&N?N.roundTripTime:Td(r);e.emit("serverHeartbeatSucceeded",new Hx(A,O,e.address)),f&&O.topologyVersion?(e.emit("serverHeartbeatStarted",new zx(e.address)),r=$w()):(e[Mi]&&(e[Mi].close(),e[Mi]=void 0),t(void 0,O))});return}kx(e.connectOptions,e[bo],(i,a)=>{if(a&&Zc(e)){a.destroy({force:!0});return}if(i){e[Nt]=void 0,i instanceof TZ||e.emit("resetConnectionPool"),n(i);return}e[Nt]=a,e.emit("serverHeartbeatSucceeded",new Hx(Td(r),a.ismaster,e.address)),t(void 0,a.ismaster)})}s(CZ,"checkServer");function Yx(e){return t=>{za(e,$a);function r(){Zc(e)||za(e,Fa),t()}s(r,"done"),process.nextTick(()=>e.emit("monitoring",e[Jc])),CZ(e,(n,i)=>{if(n&&e[Jc].description.type===vZ.Unknown)return e.emit("resetServer",n),r();i&&i.topologyVersion&&setTimeout(()=>{Zc(e)||e[Er].wake()}),r()})}}s(Yx,"monitorServer");function IZ(e){return{processId:e.processId,counter:NZ.Long.fromNumber(e.counter)}}s(IZ,"makeTopologyVersion");var kw=class kw{constructor(t,r){this[Nt]=null,this[bo]=t,this[Xc]=0,this.closed=!1;let n=r.heartbeatFrequencyMS;this[Er]=setTimeout(()=>Kx(this,r),n)}get roundTripTime(){return this[Xc]}close(){this.closed=!0,clearTimeout(this[Er]),this[Er]=void 0,this[Nt]&&this[Nt].destroy({force:!0})}};s(kw,"RTTPinger");var Hw=kw;function Kx(e,t){let r=$w(),n=e[bo],i=t.heartbeatFrequencyMS;if(e.closed)return;function a(u){if(e.closed){u.destroy({force:!0});return}e[Nt]==null&&(e[Nt]=u),e[Xc]=Td(r),e[Er]=setTimeout(()=>Kx(e,t),i)}if(s(a,"measureAndReschedule"),e[Nt]==null){kx(t,n,(u,f)=>{if(u){e[Nt]=void 0,e[Xc]=0;return}a(f)});return}e[Nt].command("admin.$cmd",{ismaster:1},u=>{if(u){e[Nt]=void 0,e[Xc]=0;return}a()})}s(Kx,"measureRoundTripTime");Xx.exports={Monitor:zw}});var oM=E((ySe,sM)=>{"use strict";var BZ=require("events"),RZ=Wx().ConnectionPool,xZ=kc().CMAP_EVENT_NAMES,qi=X().MongoError,Zx=ce().relayEvents,Tr=jt().retrieveBSON(),MZ=mn(),eM=io().ServerDescription,DZ=io().compareTopologyVersion,qZ=Vt(),PZ=Jx().Monitor,tM=X().MongoNetworkError,rM=X().MongoNetworkTimeoutError,nM=ce().collationNotSupported,LZ=jt().debugOptions,UZ=X().isSDAMUnrecoverableError,jZ=X().isRetryableWriteError,WZ=X().isNodeShuttingDownError,FZ=X().isNetworkErrorBeforeHandshake,Kw=ce().maxWireVersion,$Z=ce().makeStateMachine,zZ=uo().extractCommand,tf=tr(),HZ=tf.ServerType,VZ=Ta().isTransactionCommand,YZ=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"],Qn=tf.STATE_CLOSING,Lr=tf.STATE_CLOSED,ef=tf.STATE_CONNECTING,bd=tf.STATE_CONNECTED,Nd=$Z({[Lr]:[Lr,ef],[ef]:[ef,Qn,bd,Lr],[bd]:[bd,Qn,Lr],[Qn]:[Qn,Lr]}),Di=Symbol("monitor"),Xw=class Xw extends BZ{constructor(t,r,n){super(),this.s={description:t,options:r,logger:MZ("Server",r),bson:r.bson||new Tr([Tr.Binary,Tr.Code,Tr.DBRef,Tr.Decimal128,Tr.Double,Tr.Int32,Tr.Long,Tr.Map,Tr.MaxKey,Tr.MinKey,Tr.ObjectId,Tr.BSONRegExp,Tr.Symbol,Tr.Timestamp]),state:Lr,credentials:r.credentials,topology:n},this.serverApi=r.serverApi;let i=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},r);this.s.pool=new RZ(i),Zx(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(xZ)),this.s.pool.on("clusterTimeReceived",a=>{this.clusterTime=a}),this[Di]=new PZ(this,this.s.options),Zx(this[Di],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[Di].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[Di].on("resetServer",a=>Ms(this,a)),this[Di].on("serverHeartbeatSucceeded",a=>{this.emit("descriptionReceived",new eM(this.description.address,a.reply,{roundTripTime:kZ(this.description.roundTripTime,a.duration)})),this.s.state===ef&&(Nd(this,bd),this.emit("connect",this))})}get description(){return this.s.description}get supportsRetryableWrites(){return iM(this)}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===Lr&&(Nd(this,ef),this[Di].connect())}destroy(t,r){if(typeof t=="function"&&(r=t,t={}),t=Object.assign({},{force:!1},t),this.s.state===Lr){typeof r=="function"&&r();return}Nd(this,Qn),this[Di].close(),this.s.pool.close(t,n=>{Nd(this,Lr),this.emit("closed"),typeof r=="function"&&r(n)})}requestCheck(){this[Di].requestCheck()}command(t,r,n,i){if(typeof n=="function"&&(i=n,n={},n=n||{}),n.serverApi=this.serverApi,this.s.state===Qn||this.s.state===Lr){i(new qi("server is closed"));return}let a=GZ(this,n);if(a)return i(a);if(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()){let u=zZ(r);this.s.logger.debug(`executing command [${JSON.stringify({ns:t,cmd:u.shouldRedact?`${u.name} details REDACTED`:r,options:LZ(YZ,n)})}] against ${this.name}`)}if(nM(this,r)){i(new qi(`server ${this.name} does not support collation`));return}this.s.pool.withConnection((u,f,l)=>{if(u)return Ms(this,u),l(u);f.command(t,r,n,Qc(this,f,r,n,l))},i)}query(t,r,n,i,a){if(this.s.state===Qn||this.s.state===Lr){a(new qi("server is closed"));return}this.s.pool.withConnection((u,f,l)=>{if(u)return Ms(this,u),l(u);f.query(t,r,n,i,Qc(this,f,r,i,l))},a)}getMore(t,r,n,i,a){if(this.s.state===Qn||this.s.state===Lr){a(new qi("server is closed"));return}this.s.pool.withConnection((u,f,l)=>{if(u)return Ms(this,u),l(u);f.getMore(t,r,n,i,Qc(this,f,null,i,l))},a)}killCursors(t,r,n){if(this.s.state===Qn||this.s.state===Lr){typeof n=="function"&&n(new qi("server is closed"));return}this.s.pool.withConnection((i,a,u)=>{if(i)return Ms(this,i),u(i);a.killCursors(t,r,Qc(this,a,null,void 0,u))},n)}insert(t,r,n,i){Gw({server:this,op:"insert",ns:t,ops:r},n,i)}update(t,r,n,i){Gw({server:this,op:"update",ns:t,ops:r},n,i)}remove(t,r,n,i){Gw({server:this,op:"remove",ns:t,ops:r},n,i)}};s(Xw,"Server");var Ad=Xw;Object.defineProperty(Ad.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}});function iM(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==HZ.Standalone}s(iM,"supportsRetryableWrites");function kZ(e,t){if(e===-1)return t;let r=.2;return r*t+(1-r)*e}s(kZ,"calculateRoundTripTime");function GZ(e,t){if(t.readPreference&&!(t.readPreference instanceof qZ))return new qi("readPreference must be an instance of ReadPreference")}s(GZ,"basicReadValidations");function Gw(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.server,i=e.op,a=e.ns,u=Array.isArray(e.ops)?e.ops:[e.ops];if(n.s.state===Qn||n.s.state===Lr){r(new qi("server is closed"));return}if(nM(n,t)){r(new qi(`server ${n.name} does not support collation`));return}if((t.writeConcern&&t.writeConcern.w===0||Kw(n)<5)&&(i==="update"||i==="remove")&&u.find(l=>l.hint)){r(new qi(`servers < 3.4 do not support hint on ${i}`));return}n.s.pool.withConnection((l,h,m)=>{if(l)return Ms(n,l),m(l);h[i](a,u,t,Qc(n,h,u,t,m))},r)}s(Gw,"executeWriteOperation");function Ms(e,t){t instanceof tM&&!(t instanceof rM)&&e[Di].reset(),e.emit("descriptionReceived",new eM(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}s(Ms,"markServerUnknown");function KZ(e,t){return t.generation!==e.generation}s(KZ,"connectionIsStale");function XZ(e,t){let r=t.topologyVersion,n=e.description.topologyVersion;return DZ(n,r)<0}s(XZ,"shouldHandleStateChangeError");function Qx(e,t){return e&&e.inTransaction()&&!VZ(t)}s(Qx,"inActiveTransaction");function Qc(e,t,r,n,i){let a=n&&n.session;return s(function(f,l){f&&!KZ(e.s.pool,t)&&(f instanceof tM?(a&&!a.hasEnded&&(a.serverSession.isDirty=!0),iM(e)&&!Qx(a,r)&&f.addErrorLabel("RetryableWriteError"),(!(f instanceof rM)||FZ(f))&&(Ms(e,f),e.s.pool.clear())):(Kw(e)<9&&jZ(f)&&!Qx(a,r)&&f.addErrorLabel("RetryableWriteError"),UZ(f)&&XZ(e,f)&&((Kw(e)<=7||WZ(f))&&e.s.pool.clear(),Ms(e,f),process.nextTick(()=>e.requestCheck())))),i(f,l)},"handleOperationResult")}s(Qc,"makeOperationHandler");sM.exports={Server:Ad}});var aM=E((_Se,Zw)=>{"use strict";var JZ=mn(),ZZ=require("events").EventEmitter,QZ=require("dns");function eQ(e,t){let r=/^.*?\./,n=`.${e.replace(r,"")}`,i=`.${t.replace(r,"")}`;return n.endsWith(i)}s(eQ,"matchesParentDomain");var Qw=class Qw{constructor(t){this.srvRecords=t}addresses(){return new Set(this.srvRecords.map(t=>`${t.name}:${t.port}`))}};s(Qw,"SrvPollingEvent");var Cd=Qw,ev=class ev extends ZZ{constructor(t){if(super(),!t||!t.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=t.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=t.heartbeatFrequencyMS||1e4,this.logger=JZ("srvPoller",t),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(t){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new Cd(t))}failure(t,r){this.logger.warn(t,r),this.haMode=!0,this.schedule()}parentDomainMismatch(t){this.logger.warn(`parent domain mismatch on SRV record (${t.name}:${t.port})`,t)}_poll(){let t=this.generation;QZ.resolveSrv(this.srvAddress,(r,n)=>{if(t!==this.generation)return;if(r){this.failure("DNS error",r);return}let i=[];if(n.forEach(a=>{eQ(a.name,this.srvHost)?i.push(a):this.parentDomainMismatch(a)}),!i.length){this.failure("No valid addresses found at host");return}this.success(i)})}};s(ev,"SrvPoller");var Jw=ev;Zw.exports.SrvPollingEvent=Cd;Zw.exports.SrvPoller=Jw});var fM=E((vSe,cM)=>{"use strict";var nf=tr().ServerType,rf=tr().TopologyType,Id=Vt(),tv=X().MongoError,tQ=1e4,uM=90;function rQ(){return function(e,t){return rv(e,t.filter(r=>r.isWritable))}}s(rQ,"writableServerSelector");function nQ(e,t,r){if(e.maxStalenessSeconds==null||e.maxStalenessSeconds<0)return r;let n=e.maxStalenessSeconds,i=(t.heartbeatFrequencyMS+tQ)/1e3;if(n((f.lastUpdateTime-f.lastWriteDate-(a.lastUpdateTime-a.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&u.push(f),u),[])}if(t.type===rf.ReplicaSetNoPrimary){if(r.length===0)return r;let a=r.reduce((u,f)=>f.lastWriteDate>u.lastWriteDate?f:u);return r.reduce((u,f)=>((a.lastWriteDate-f.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&u.push(f),u),[])}return r}s(nQ,"maxStalenessReducer");function iQ(e,t){let r=Object.keys(e),n=Object.keys(t);for(let i=0;i(iQ(n,u.tags)&&a.push(u),a),[]);if(i.length)return i}return[]}s(sQ,"tagSetReducer");function rv(e,t){let r=t.reduce((i,a)=>i===-1?a.roundTripTime:Math.min(a.roundTripTime,i),-1),n=r+e.localThresholdMS;return t.reduce((i,a)=>(a.roundTripTime<=n&&a.roundTripTime>=r&&i.push(a),i),[])}s(rv,"latencyWindowReducer");function Bd(e){return e.type===nf.RSPrimary}s(Bd,"primaryFilter");function oQ(e){return e.type===nf.RSSecondary}s(oQ,"secondaryFilter");function aQ(e){return e.type===nf.RSSecondary||e.type===nf.RSPrimary}s(aQ,"nearestFilter");function uQ(e){return e.type!==nf.Unknown}s(uQ,"knownFilter");function cQ(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,r){let n=t.commonWireVersion;if(n&&e.minWireVersion&&e.minWireVersion>n)throw new tv(`Minimum wire version '${e.minWireVersion}' required, but found '${n}'`);if(t.type===rf.Unknown)return[];if(t.type===rf.Single||t.type===rf.Sharded)return rv(t,r.filter(uQ));let i=e.mode;if(i===Id.PRIMARY)return r.filter(Bd);if(i===Id.PRIMARY_PREFERRED){let f=r.filter(Bd);if(f.length)return f}let a=i===Id.NEAREST?aQ:oQ,u=rv(t,sQ(e,nQ(e,t,r.filter(a))));return i===Id.SECONDARY_PREFERRED&&u.length===0?r.filter(Bd):u}}s(cQ,"readPreferenceServerSelector");cM.exports={writableServerSelector:rQ,readPreferenceServerSelector:cQ}});var vM=E((ESe,wM)=>{"use strict";var fQ=sd(),lQ=require("events"),hQ=io().ServerDescription,dQ=tr().ServerType,lM=CS().TopologyDescription,Pi=tr().TopologyType,Ds=C_(),pQ=oM().Server,mQ=ce().relayEvents,Ln=Vt(),gQ=yn().CoreCursor,yQ=require("util").deprecate,cr=jt().retrieveBSON(),SQ=vt().createCompressionInfo,_Q=gs().ClientSession,qd=X().MongoError,wQ=X().MongoServerSelectionError,vQ=vt().resolveClusterTime,OQ=aM().SrvPoller,EQ=vt().getMMAPError,TQ=ce().makeStateMachine,NQ=ce().eachAsync,bQ=x().emitDeprecationWarning,AQ=gs().ServerSessionPool,CQ=ce().makeClientMetadata,IQ=kc().CMAP_EVENT_NAMES,BQ=io().compareTopologyVersion,RQ=x().emitWarning,Ao=tr(),xQ=Ao.drainTimerQueue,MQ=Ao.clearAndRemoveTimerFrom,dM=fM(),Rd=dM.readPreferenceServerSelector,DQ=dM.writableServerSelector,qQ=0,pM=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(IQ),PQ=["connect","descriptionReceived","close","ended"],Ha=Ao.STATE_CLOSING,ti=Ao.STATE_CLOSED,Md=Ao.STATE_CONNECTING,Va=Ao.STATE_CONNECTED,xd=TQ({[ti]:[ti,Md],[Md]:[Md,Ha,Va,ti],[Va]:[Va,Ha,ti],[Ha]:[Ha,ti]}),LQ=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]),nv=Symbol("cancelled"),ei=Symbol("waitQueue"),iv=class iv extends lQ{constructor(t,r){super(),typeof r>"u"&&typeof t!="string"&&(r=t,t=[],r.host&&t.push({host:r.host,port:r.port})),t=t||[],typeof t=="string"&&(t=FQ(t)),r=Object.assign({},Ao.TOPOLOGY_DEFAULTS,r),r=Object.freeze(Object.assign(r,{metadata:CQ(r),compression:{compressors:SQ(r)}})),LQ.forEach(u=>{r[u]&&bQ(`The option \`${u}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});let n=$Q(t,r),i=qQ++,a=t.reduce((u,f)=>{f.domain_socket&&(f.host=f.domain_socket);let l=f.port?`${f.host}:${f.port}`:`${f.host}:27017`;return u.set(l,new hQ(l)),u},new Map);this[ei]=new fQ,this.s={id:i,options:r,seedlist:t,state:ti,description:new lM(n,a,r.replicaSet,null,null,null,r),serverSelectionTimeoutMS:r.serverSelectionTimeoutMS,heartbeatFrequencyMS:r.heartbeatFrequencyMS,minHeartbeatFrequencyMS:r.minHeartbeatFrequencyMS,Cursor:r.cursorFactory||gQ,bson:r.bson||new cr([cr.Binary,cr.Code,cr.DBRef,cr.Decimal128,cr.Double,cr.Int32,cr.Long,cr.Map,cr.MaxKey,cr.MinKey,cr.ObjectId,cr.BSONRegExp,cr.Symbol,cr.Timestamp]),servers:new Map,sessionPool:new AQ(this),sessions:new Set,promiseLibrary:r.promiseLibrary||Promise,credentials:r.credentials,clusterTime:null,connectionTimers:new Set},this.serverApi=r.serverApi,r.srvHost&&(this.s.srvPoller=r.srvPoller||new OQ({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:r.srvHost,logger:r.logger,loggerLevel:r.loggerLevel}),this.s.detectTopologyDescriptionChange=u=>{let f=u.previousDescription.type,l=u.newDescription.type;f!==Pi.Sharded&&l===Pi.Sharded&&(this.s.handleSrvPolling=VQ(this),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return cr.native?"c++":"js"}connect(t,r){if(typeof t=="function"&&(r=t,t={}),t=t||{},this.s.state===Va){typeof r=="function"&&r();return}xd(this,Md),this.emit("topologyOpening",new Ds.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new Ds.TopologyDescriptionChangedEvent(this.s.id,new lM(Pi.Unknown),this.s.description)),HQ(this,Array.from(this.s.description.servers.values())),Ln.translate(t);let n=t.readPreference||Ln.primary,i=s(a=>{if(a){this.close(),typeof r=="function"?r(a):this.emit("error",a);return}xd(this,Va),this.emit("open",a,this),this.emit("connect",this),typeof r=="function"&&r(a,this)},"connectHandler");if(this.s.credentials){this.command("admin.$cmd",{ping:1},{readPreference:n},i);return}this.selectServer(Rd(n),t,i)}close(t,r){if(typeof t=="function"&&(r=t,t={}),typeof t=="boolean"&&(t={force:t}),t=t||{},this.s.state===ti||this.s.state===Ha){typeof r=="function"&&r();return}xd(this,Ha),_M(this[ei],new qd("Topology closed")),xQ(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(n=>n.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{NQ(Array.from(this.s.servers.values()),(n,i)=>mM(n,this,t,i),n=>{this.s.servers.clear(),this.emit("topologyClosed",new Ds.TopologyClosedEvent(this.s.id)),xd(this,ti),typeof r=="function"&&r(n)})})}selectServer(t,r,n){if(typeof r=="function")if(n=r,typeof t!="function"){r=t;let m;t instanceof Ln?m=t:typeof t=="string"?m=new Ln(t):(Ln.translate(r),m=r.readPreference||Ln.primary),t=Rd(m)}else r={};r=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},r);let i=this.description.type===Pi.Sharded,a=r.session,u=a&&a.transaction;if(i&&u&&u.server){n(void 0,u.server);return}let f=t;if(typeof t=="object"){let m=t.readPreference?t.readPreference:Ln.primary;f=Rd(m)}let l={serverSelector:f,transaction:u,callback:n},h=r.serverSelectionTimeoutMS;h&&(l.timer=setTimeout(()=>{l[nv]=!0,l.timer=void 0;let m=new wQ(`Server selection timed out after ${h} ms`,this.description);l.callback(m)},h)),this[ei].push(l),hM(this)}shouldCheckForSessionSupport(){return this.description.type===Pi.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return this.description.logicalSessionTimeoutMinutes!=null}startSession(t,r){let n=new _Q(this,this.s.sessionPool,t,r);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(t,r){Array.isArray(t)||(t=[t]),this.command("admin.$cmd",{endSessions:t},{readPreference:Ln.primaryPreferred,noResponse:!0,serverApi:this.serverApi},()=>{typeof r=="function"&&r()})}serverUpdateHandler(t){if(!this.s.description.hasServer(t.address)||WQ(this.s.description,t))return;let r=this.s.description,n=this.s.description.servers.get(t.address),i=t.$clusterTime;i&&vQ(this,i);let a=n&&n.equals(t);if(this.s.description=this.s.description.update(t),this.s.description.compatibilityError){this.emit("error",new qd(this.s.description.compatibilityError));return}a||this.emit("serverDescriptionChanged",new Ds.ServerDescriptionChangedEvent(this.s.id,t.address,n,this.s.description.servers.get(t.address))),yM(this,t),this[ei].length>0&&hM(this),a||this.emit("topologyDescriptionChanged",new Ds.TopologyDescriptionChangedEvent(this.s.id,r,this.s.description))}auth(t,r){typeof t=="function"&&(r=t,t=null),typeof r=="function"&&r(null,!0)}logout(t){typeof t=="function"&&t(null,!0)}insert(t,r,n,i){Dd({topology:this,op:"insert",ns:t,ops:r},n,i)}update(t,r,n,i){Dd({topology:this,op:"update",ns:t,ops:r},n,i)}remove(t,r,n,i){Dd({topology:this,op:"remove",ns:t,ops:r},n,i)}command(t,r,n,i){typeof n=="function"&&(i=n,n={},n=n||{}),Ln.translate(n);let a=n.readPreference||Ln.primary;this.selectServer(Rd(a),n,(u,f)=>{if(u){i(u);return}let l=!n.retrying,h=!!n.retryWrites,m=!!n.session,p=f.supportsRetryableWrites,g=!m||!n.session.inTransaction(),w=l&&h&&m&&p&&g&&jQ(r),O=s((N,A)=>{if(!N)return i(null,A);if(!SM(N))return i(N);if(w){let M=Object.assign({},n,{retrying:!0});return this.command(t,r,M,i)}return i(N)},"cb");w&&(n.session.incrementTransactionNumber(),n.willRetryWrite=w),f.command(t,r,n,O)})}cursor(t,r,n){n=n||{};let i=n.topology||this,a=n.cursorFactory||this.s.Cursor;return Ln.translate(n),new a(i,t,r,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===Va}isDestroyed(){return this.s.state===ti}unref(){RQ("`unref` is a noop and will be removed in the next major version")}lastIsMaster(){let t=Array.from(this.description.servers.values());return t.length===0?{}:t.filter(i=>i.type!==dQ.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}};s(iv,"Topology");var Ya=iv;Object.defineProperty(Ya.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}});Ya.prototype.destroy=yQ(Ya.prototype.close,"destroy() is deprecated, please use close() instead");var UQ=["findAndModify","insert","update","delete"];function jQ(e){return UQ.some(t=>e[t])}s(jQ,"isWriteCommand");function WQ(e,t){let n=e.servers.get(t.address).topologyVersion;return BQ(n,t.topologyVersion)>0}s(WQ,"isStaleServerDescription");function mM(e,t,r,n){r=r||{},PQ.forEach(i=>e.removeAllListeners(i)),e.destroy(r,()=>{t.emit("serverClosed",new Ds.ServerClosedEvent(t.s.id,e.description.address)),pM.forEach(i=>e.removeAllListeners(i)),typeof n=="function"&&n()})}s(mM,"destroyServer");function FQ(e){return e.split(",").map(t=>({host:t.split(":")[0],port:t.split(":")[1]||27017}))}s(FQ,"parseStringSeedlist");function $Q(e,t){return t.directConnection?Pi.Single:(t.replicaSet||t.setName||t.rs_name)==null?Pi.Unknown:Pi.ReplicaSetNoPrimary}s($Q,"topologyTypeFromSeedlist");function zQ(e){return e[Math.floor(Math.random()*e.length)]}s(zQ,"randomSelection");function gM(e,t,r){e.emit("serverOpening",new Ds.ServerOpeningEvent(e.s.id,t.address));let n=new pQ(t,e.s.options,e);if(mQ(n,e,pM),n.on("descriptionReceived",e.serverUpdateHandler.bind(e)),r){let i=setTimeout(()=>{MQ(i,e.s.connectionTimers),n.connect()},r);return e.s.connectionTimers.add(i),n}return n.connect(),n}s(gM,"createAndConnectServer");function HQ(e,t){e.s.servers=t.reduce((r,n)=>{let i=gM(e,n);return r.set(n.address,i),r},new Map)}s(HQ,"connectServers");function yM(e,t){if(t&&e.s.servers.has(t.address)){let r=e.s.servers.get(t.address);r.s.description=t}for(let r of e.description.servers.values())if(!e.s.servers.has(r.address)){let n=gM(e,r);e.s.servers.set(r.address,n)}for(let r of e.s.servers){let n=r[0];if(e.description.hasServer(n))continue;let i=e.s.servers.get(n);e.s.servers.delete(n),mM(i,e)}}s(yM,"updateServers");function Dd(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.topology,i=e.op,a=e.ns,u=e.ops;n.selectServer(DQ(),t,(f,l)=>{if(f){r(f,null);return}let h=!e.retrying,m=!!t.retryWrites,p=!!t.session,g=l.supportsRetryableWrites,w=!p||!t.session.inTransaction(),O=t.explain===void 0,N=h&&m&&p&&g&&w&&O,A=s((M,L)=>{if(!M)return r(null,L);if(!SM(M))return M=EQ(M),r(M);if(N){let I=Object.assign({},e,{retrying:!0});return Dd(I,t,r)}return r(M)},"handler");r.operationId&&(A.operationId=r.operationId),N&&(t.session.incrementTransactionNumber(),t.willRetryWrite=N),l[i](a,u,t,A)})}s(Dd,"executeWriteOperation");function SM(e){return e instanceof qd&&e.hasErrorLabel("RetryableWriteError")}s(SM,"shouldRetryOperation");function VQ(e){return s(function(r){let n=e.s.description;e.s.description=e.s.description.updateFromSrvPollingEvent(r),e.s.description!==n&&(yM(e),e.emit("topologyDescriptionChanged",new Ds.TopologyDescriptionChangedEvent(e.s.id,n,e.s.description)))},"handleSrvPolling")}s(VQ,"srvPollingHandler");function _M(e,t){for(;e.length;){let r=e.shift();clearTimeout(r.timer),r[nv]||r.callback(t)}}s(_M,"drainWaitQueue");function hM(e){if(e.s.state===ti){_M(e[ei],new qd("Topology is closed, please connect"));return}let t=Array.from(e.description.servers.values()),r=e[ei].length;for(let n=0;n0&&e.s.servers.forEach(n=>process.nextTick(()=>n.requestCheck()))}s(hM,"processWaitQueue");wM.exports={Topology:Ya}});var CM=E((NSe,AM)=>{"use strict";var Pd=require("url"),Co=require("querystring"),OM=require("dns"),Re=X().MongoParseError,YQ=Vt(),kQ=x().emitWarningOnce,GQ=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/,KQ=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map(e=>e.toLowerCase()));function XQ(e,t){let r=/^.*?\./,n=`.${e.replace(r,"")}`,i=`.${t.replace(r,"")}`;return n.endsWith(i)}s(XQ,"matchesParentDomain");function JQ(e,t,r){let n=Pd.parse(e,!0);if(t.directConnection||t.directconnection)return r(new Re("directConnection not supported with SRV URI"));if(n.hostname.split(".").length<3)return r(new Re("URI does not have hostname, domain name and tld"));if(n.domainLength=n.hostname.split(".").length,e.substring(14).split("/")[0].match(","))return r(new Re("Invalid URI, cannot contain multiple hostnames"));if(n.port)return r(new Re(`Ports not accepted with '${ov}' URIs`));let a=n.host;OM.resolveSrv(`_mongodb._tcp.${a}`,(u,f)=>{if(u)return r(u);if(f.length===0)return r(new Re("No addresses found at host"));for(let l=0;l`${l.name}:${l.port}`).join(","),!("ssl"in t)&&(!n.search||!("ssl"in n.query)||n.query.ssl===null)&&(n.query.ssl=!0),OM.resolveTxt(a,(l,h)=>{if(l){if(l.code!=="ENODATA"&&l.code!=="ENOTFOUND")return r(l);h=null}if(h){if(h.length>1)return r(new Re("Multiple text records not allowed"));if(h=Co.parse(h[0].join("")),Object.keys(h).some(p=>p.toLowerCase()==="loadbalanced"))return r(new Re("Load balancer mode requires driver version 4+"));if(Object.keys(h).some(p=>p!=="authSource"&&p!=="replicaSet"))return r(new Re("Text record must only set `authSource` or `replicaSet`"));n.query=Object.assign({},h,n.query)}n.search=Co.stringify(n.query);let m=Pd.format(n);bM(m,t,(p,g)=>{if(p){r(p);return}r(null,Object.assign({},g,{srvHost:a}))})})})}s(JQ,"parseSrvConnectionString");function sv(e,t){if(Array.isArray(t))t=t.filter((r,n)=>t.indexOf(r)===n),t.length===1&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((r,n)=>{let i=n.split(":");return r[i[0]]=sv(e,i[1]),r},{});else if(t.indexOf(",")>0)t=t.split(",").map(r=>sv(e,r));else if(t.toLowerCase()==="true"||t.toLowerCase()==="false")t=t.toLowerCase()==="true";else if(!Number.isNaN(t)&&!QQ.has(e)){let r=parseFloat(t);Number.isNaN(r)||(t=parseFloat(t))}return t}s(sv,"parseQueryStringItemValue");var ZQ=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),QQ=new Set(["authsource","replicaset"]),EM=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),TM={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function eee(e,t,r,n){if(t==="journal"?t="j":t==="wtimeoutms"&&(t="wtimeout"),ZQ.has(t)?r=r==="true"||r===!0:t==="appname"?r=decodeURIComponent(r):t==="readconcernlevel"&&(e.readConcernLevel=r,t="readconcern",r={level:r}),t==="compressors"&&(r=Array.isArray(r)?r:[r],!r.every(i=>i==="snappy"||i==="zlib")))throw new Re("Value for `compressors` must be at least one of: `snappy`, `zlib`");if(t==="authmechanism"&&!EM.has(r))throw new Re(`Value for authMechanism must be one of: ${Array.from(EM).join(", ")}, found: ${r}`);if(t==="readpreference"&&!YQ.isValid(r))throw new Re("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if(t==="zlibcompressionlevel"&&(r<-1||r>9))throw new Re("zlibCompressionLevel must be an integer between -1 and 9");if((t==="compressors"||t==="zlibcompressionlevel")&&(e.compression=e.compression||{},e=e.compression),t==="authmechanismproperties"&&(typeof r.SERVICE_NAME=="string"&&(e.gssapiServiceName=r.SERVICE_NAME),typeof r.SERVICE_REALM=="string"&&(e.gssapiServiceRealm=r.SERVICE_REALM),typeof r.CANONICALIZE_HOST_NAME<"u"&&(e.gssapiCanonicalizeHostName=r.CANONICALIZE_HOST_NAME)),t==="readpreferencetags"&&(r=Array.isArray(r)?ree(r):[r]),n.caseTranslate&&TM[t]){e[TM[t]]=r;return}e[t]=r}s(eee,"applyConnectionStringOption");var tee=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function ree(e){let t=[];for(let r=0;r{let i=n.split(":");t[r][i[0]]=i[1]});return t}s(ree,"splitArrayOfMultipleReadPreferenceTags");function nee(e){if(e.options==null)return;let t=e.options,r=t.authsource||t.authSource;r!=null&&(e.auth=Object.assign({},e.auth,{db:r}));let n=t.authmechanism||t.authMechanism;if(n!=null){if(tee.has(n)&&(!e.auth||e.auth.username==null))throw new Re(`Username required for mechanism \`${n}\``);if(n==="GSSAPI"){if(r!=null&&r!=="$external")throw new Re(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-AWS"){if(r!=null&&r!=="$external")throw new Re(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-X509"){if(e.auth&&e.auth.password!=null)throw new Re(`Password not allowed for mechanism \`${n}\``);if(r!=null&&r!=="$external")throw new Re(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}n==="PLAIN"&&e.auth&&e.auth.db==null&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}return e.auth&&e.auth.db==null&&(e.auth=Object.assign({},e.auth,{db:"admin"})),e}s(nee,"applyAuthExpectations");function iee(e,t){let r={},n=Co.parse(e);oee(n);for(let i in n){let a=n[i];if(a===""||a==null)throw new Re("Incomplete key value pair for option");let u=i.toLowerCase();if(u==="serverapi")throw new Re("URI cannot contain `serverApi`, it can only be passed to the client");let f=KQ.has(u)?a:sv(u,a);eee(r,u,f,t)}return r.wtimeout&&r.wtimeoutms&&(delete r.wtimeout,kQ("Unsupported option `wtimeout` specified")),Object.keys(r).length?r:null}s(iee,"parseQueryString");function see(e){return e.tls&&(e.ssl=e.tls),e.tlsInsecure?(e.checkServerIdentity=!1,e.sslValidate=!1):Object.assign(e,{checkServerIdentity:!e.tlsAllowInvalidHostnames,sslValidate:!e.tlsAllowInvalidCertificates}),e.tlsCAFile&&(e.ssl=!0,e.sslCA=e.tlsCAFile),e.tlsCertificateKeyFile&&(e.ssl=!0,e.tlsCertificateFile?(e.sslCert=e.tlsCertificateFile,e.sslKey=e.tlsCertificateKeyFile):(e.sslKey=e.tlsCertificateKeyFile,e.sslCert=e.tlsCertificateKeyFile)),e.tlsCertificateKeyFilePassword&&(e.ssl=!0,e.sslPass=e.tlsCertificateKeyFilePassword),e}s(see,"translateTLSOptions");function oee(e){let t=Object.keys(e);if(t.indexOf("tlsInsecure")!==-1&&(t.indexOf("tlsAllowInvalidCertificates")!==-1||t.indexOf("tlsAllowInvalidHostnames")!==-1))throw new Re("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");let r=NM("tls",e,t),n=NM("ssl",e,t);if(r!=null&&n!=null&&r!==n)throw new Re("All values of `tls` and `ssl` must be the same.")}s(oee,"checkTLSOptions");function NM(e,t,r){let n=r.indexOf(e)!==-1,i;if(Array.isArray(t[e])?i=t[e][0]:i=t[e],n&&Array.isArray(t[e])){let a=t[e][0];t[e].forEach(u=>{if(u!==a)throw new Re(`All values of ${e} must be the same.`)})}return i}s(NM,"assertTlsOptionsAreEqual");var aee="mongodb",ov="mongodb+srv",uee=[aee,ov];function bM(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{Pd.parse(e)}catch{return r(new Re("URI malformed, cannot be parsed"))}let n=e.match(GQ);if(!n)return r(new Re("Invalid connection string"));let i=n[1];if(uee.indexOf(i)===-1)return r(new Re("Invalid protocol provided"));let a=n[4].split("?"),u=a.length>0?a[0]:null,f=a.length>1?a[1]:null,l;try{l=iee(f,t)}catch(N){return r(N)}if(l=Object.assign({},l,t),Object.keys(l).some(N=>N.toLowerCase()==="loadbalanced"))return r(new Re("Load balancer mode requires driver version 4+"));if(i===ov)return JQ(e,l,r);let h={username:null,password:null,db:u&&u!==""?Co.unescape(u):null};if(l.auth?(l.auth.username&&(h.username=l.auth.username),l.auth.user&&(h.username=l.auth.user),l.auth.password&&(h.password=l.auth.password)):(l.username&&(h.username=l.username),l.user&&(h.username=l.user),l.password&&(h.password=l.password)),n[4].split("?")[0].indexOf("@")!==-1)return r(new Re("Unescaped slash in userinfo section"));let m=n[3].split("@");if(m.length>2)return r(new Re("Unescaped at-sign in authority section"));if(m[0]==null||m[0]==="")return r(new Re("No username provided in authority section"));if(m.length>1){let N=m.shift().split(":");if(N.length>2)return r(new Re("Unescaped colon in authority section"));if(N[0]==="")return r(new Re("Invalid empty username provided"));h.username||(h.username=Co.unescape(N[0])),h.password||(h.password=N[1]?Co.unescape(N[1]):null)}let p=null,g=m.shift().split(",").map(N=>{let A=Pd.parse(`mongodb://${N}`);if(A.path==="/:")return p=new Re("Double colon in host identifier"),null;if(N.match(/\.sock/)&&(A.hostname=Co.unescape(N),A.port=null),Number.isNaN(A.port)){p=new Re("Invalid port (non-numeric string)");return}let M={host:A.hostname,port:A.port?parseInt(A.port):27017};if(M.port===0){p=new Re("Invalid port (zero) with hostname");return}if(M.port>65535){p=new Re("Invalid port (larger than 65535) with hostname");return}if(M.port<0){p=new Re("Invalid port (negative number)");return}return M}).filter(N=>!!N);if(p)return r(p);if(g.length===0||g[0].host===""||g[0].host===null)return r(new Re("No hostname or hostnames provided in connection string"));if(!!l.directConnection&&g.length!==1)return r(new Re("directConnection option requires exactly one host"));l.directConnection==null&&g.length===1&&l.replicaSet==null&&(l.directConnection=!0);let O={hosts:g,auth:h.db||h.username?h:null,options:Object.keys(l).length?l:null};O.auth&&O.auth.db?O.defaultDatabase=O.auth.db:O.defaultDatabase="test",O.options=see(O.options);try{nee(O)}catch(N){return r(N)}r(null,O)}s(bM,"parseConnectionString");AM.exports=bM});var G=E((ASe,BM)=>{"use strict";var IM=th(),cee=rh()(require),fee=ce().retrieveEJSON();try{let e=cee("bson-ext");e&&(IM=e)}catch{}var av=Object.freeze({v1:"1"}),lee=Object.keys(av).map(e=>av[e]);BM.exports={ServerApiVersion:av,ValidServerApiVersions:lee,MongoError:X().MongoError,MongoNetworkError:X().MongoNetworkError,MongoParseError:X().MongoParseError,MongoTimeoutError:X().MongoTimeoutError,MongoServerSelectionError:X().MongoServerSelectionError,MongoWriteConcernError:X().MongoWriteConcernError,Connection:FS(),Server:kh(),ReplSet:nR(),Mongos:hR(),Logger:mn(),Cursor:yn().CoreCursor,ReadPreference:Vt(),Sessions:gs(),BSON:IM,EJSON:fee,Topology:vM().Topology,Query:Xr().Query,MongoCredentials:T0().MongoCredentials,defaultAuthProviders:I0().defaultAuthProviders,MongoCR:i0(),X509:a0(),Plain:f0(),GSSAPI:p0(),ScramSHA1:bc().ScramSHA1,ScramSHA256:bc().ScramSHA256,parseConnectionString:CM()}});var xM=E((CSe,RM)=>{"use strict";var hee=require("events").EventEmitter,cv=class cv extends hee{constructor(){super()}instrument(t,r){this.$MongoClient=t;let n=this.$prototypeConnect=t.prototype.connect,i=this;t.prototype.connect=function(a){return this.s.options.monitorCommands=!0,this.on("commandStarted",u=>i.emit("started",u)),this.on("commandSucceeded",u=>i.emit("succeeded",u)),this.on("commandFailed",u=>i.emit("failed",u)),n.call(this,a)},typeof r=="function"&&r(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}};s(cv,"Instrumentation");var uv=cv;RM.exports=uv});var sf=E((BSe,DM)=>{"use strict";var dee=G().MongoNetworkError,Dt=ro().MONGODB_ERROR_CODES,MM=new Set([Dt.HostUnreachable,Dt.HostNotFound,Dt.NetworkTimeout,Dt.ShutdownInProgress,Dt.PrimarySteppedDown,Dt.ExceededTimeLimit,Dt.SocketException,Dt.NotMaster,Dt.InterruptedAtShutdown,Dt.InterruptedDueToReplStateChange,Dt.NotMasterNoSlaveOk,Dt.NotMasterOrSecondary,Dt.StaleShardVersion,Dt.StaleEpoch,Dt.StaleConfig,Dt.RetryChangeStream,Dt.FailedToSatisfyReadPreference,Dt.CursorNotFound]);function pee(e,t){return e instanceof dee?!0:t>=9?e.code===Dt.CursorNotFound?!0:e.hasErrorLabel("ResumableChangeStreamError"):MM.has(e.code)}s(pee,"isResumableError");DM.exports={GET_MORE_RESUMABLE_CODES:MM,isResumableError:pee,MONGODB_ERROR_CODES:Dt}});var Ld=E((xSe,qM)=>{"use strict";qM.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}});var Kt=E((MSe,FM)=>{"use strict";var Io=ro().MONGODB_ERROR_CODES,fv=x().applyWriteConcern,mee=G().BSON.Code,gee=x().debugOptions,yt=x().handleCallback,Qr=G().MongoError,PM=x().parseIndexOptions,ka=G().ReadPreference,LM=x().toError,yee=uo().extractCommand,See=Ld(),_ee=x().MongoDBNamespace,wee=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function UM(e,t,r,n,i){let a=Object.assign({},{readPreference:ka.PRIMARY},n);if(a=fv(a,{db:e},n),a.writeConcern&&typeof i!="function")throw Qr.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new Qr("topology was destroyed"));Aee(e,t,r,a,(u,f)=>{if(u==null||u.code===Io.CannotCreateIndex||u.code===Io.DuplicateKey||u.code===Io.IndexOptionsConflict||u.code===Io.IndexKeySpecsConflict||u.code===Io.InterruptedAtShutdown||u.code===Io.InvalidIndexSpecificationOption)return yt(i,u,f);let l=WM(e,t,r,n);a.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(See.SYSTEM_INDEX_COLLECTION),l,a,(h,m)=>{if(i!=null){if(h)return yt(i,h);if(m==null)return yt(i,null,null);if(m.result.writeErrors)return yt(i,Qr.create(m.result.writeErrors[0]),null);yt(i,null,l.name)}})})}s(UM,"createIndex");function vee(e,t,r){function n(i){if(r.listeners(t).length>0){r.emit(t,i,e);for(let a=0;a{if(l!=null&&l.code!==Io.NamespaceNotFound)return yt(i,l,null);if(h==null||!h[f])UM(e,t,r,n,i);else if(typeof i=="function")return yt(i,null,f)})}s(Oee,"ensureIndex");function Eee(e,t,r,n,i){let a=t,u=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new Qr("topology was destroyed"));a&&a._bsontype==="Code"||(a=new mee(a)),r!=null&&!Array.isArray(r)&&typeof r!="function"?u=[r]:r!=null&&Array.isArray(r)&&typeof r!="function"&&(u=r);let f={$eval:a,args:u};n.nolock&&(f.nolock=n.nolock),n.readPreference=new ka(ka.PRIMARY),lv(e,f,n,(l,h)=>{if(l)return yt(i,l,null);if(h&&h.ok===1)return yt(i,null,h.retval);if(h)return yt(i,Qr.create({message:`eval failed: ${h.errmsg}`,driver:!0}),null);yt(i,l,h)})}s(Eee,"evaluate");function lv(e,t,r,n){if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new Qr("topology was destroyed"));let i=r.dbName||r.authdb||e.databaseName;if(r.readPreference=ka.resolve(e,r),e.s.logger.isDebug()){let a=yee(t);e.s.logger.debug(`executing command ${JSON.stringify(a.shouldRedact?`${a.name} details REDACTED`:t)} against ${i}.$cmd with options [${JSON.stringify(gee(wee,r))}]`)}e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,r,(a,u)=>{if(a)return yt(n,a);if(r.full)return yt(n,null,u);yt(n,null,u.result)})}s(lv,"executeCommand");function Tee(e,t,r,n){let i=new _ee("admin","$cmd");e.s.topology.command(i,t,r,(a,u)=>{if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new Qr("topology was destroyed"));if(a)return yt(n,a);yt(n,null,u.result)})}s(Tee,"executeDbAdminCommand");function jM(e,t,r,n){let i=r.full==null?!1:r.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new Qr("topology was destroyed"));function a(u){let f={};for(let l=0;l{if(u)return n(LM(u));if(!Array.isArray(f))return yt(n,null,[]);if(i)return yt(n,null,f);yt(n,null,a(f))})}s(jM,"indexInformation");function Nee(e,t,r){try{e.collection("system.profile").find({},t).toArray(r)}catch(n){return r(n,null)}}s(Nee,"profilingInfo");function bee(e){if(typeof e!="string")throw Qr.create({message:"database name must be a string",driver:!0});if(e.length===0)throw Qr.create({message:"database name cannot be the empty string",driver:!0});if(e==="$external")return;let t=[" ",".","$","/","\\"];for(let r=0;r{if(p)return yt(i,p,null);if(g.ok===0)return yt(i,LM(g),null);yt(i,null,u)})}s(Aee,"createIndexUsingCreateIndexes");FM.exports={createListener:vee,createIndex:UM,ensureIndex:Oee,evaluate:Eee,executeCommand:lv,executeDbAdminCommand:Tee,indexInformation:jM,profilingInfo:Nee,validateDatabaseName:bee}});var Nr=E((qSe,VM)=>{"use strict";var Ud=x().applyRetryableWrites,jd=x().applyWriteConcern,of=x().decorateWithCollation,Cee=x().decorateWithReadConcern,Iee=Kt().executeCommand,$M=x().formattedOrderClause,mt=x().handleCallback,Wd=G().MongoError,Bee=G().ReadPreference,Li=x().toError,hv=yn().CursorState,zM=ce().maxWireVersion;function Ree(e,t,r){let n=r.skip,i=r.limit,a=r.hint,u=r.maxTimeMS;t=t||{};let f={count:r.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?a=e.options.hint:e.cmd.hint&&(a=e.cmd.hint),of(f,e,e.cmd)):of(f,e,r),typeof n=="number"&&(f.skip=n),typeof i=="number"&&(f.limit=i),typeof u=="number"&&(f.maxTimeMS=u),a&&(f.hint=a),Cee(f,e),f}s(Ree,"buildCountCommand");function xee(e,t,r,n,i,a){let u={findAndModify:e.collectionName,query:t};r=$M(r),r&&(u.sort=r),u.new=!!i.new,u.remove=!!i.remove,u.upsert=!!i.upsert;let f=i.projection||i.fields;f&&(u.fields=f),i.arrayFilters&&(u.arrayFilters=i.arrayFilters,delete i.arrayFilters),n&&!i.remove&&(u.update=n),i.maxTimeMS&&(u.maxTimeMS=i.maxTimeMS),i.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions,i.checkKeys=!1;let l=Object.assign({},i);l=Ud(l,e.s.db),l=jd(l,{db:e.s.db,collection:e},i),l.writeConcern&&(u.writeConcern=l.writeConcern),l.bypassDocumentValidation===!0&&(u.bypassDocumentValidation=l.bypassDocumentValidation),l.readPreference=Bee.primary;try{of(u,e,l)}catch(h){return a(h,null)}Iee(e.s.db,u,l,(h,m)=>h?mt(a,h,null):mt(a,null,m))}s(xee,"findAndModify");function Mee(e,t,r,n){let i=r.full==null?!1:r.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new Wd("topology was destroyed"));function a(u){let f={};for(let l=0;l{if(u)return n(Li(u));if(!Array.isArray(f))return mt(n,null,[]);if(i)return mt(n,null,f);mt(n,null,a(f))})}s(Mee,"indexInformation");function HM(e,t,r){let n=typeof r.forceServerObjectId=="boolean"?r.forceServerObjectId:e.s.db.options.forceServerObjectId;return n===!0?t:t.map(i=>(n!==!0&&i._id==null&&(i._id=e.s.pkFactory.createPk()),i))}s(HM,"prepareDocs");function Dee(e,t){if(e.s.state===hv.CLOSED||e.isDead&&e.isDead())return mt(t,Wd.create({message:"Cursor is closed",driver:!0}));if(e.s.state===hv.INIT&&e.cmd&&e.cmd.sort)try{e.cmd.sort=$M(e.cmd.sort)}catch(r){return mt(t,r)}e._next((r,n)=>{if(e.s.state=hv.OPEN,r)return mt(t,r);mt(t,null,n)})}s(Dee,"nextObject");function qee(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=r||{},t=Array.isArray(t)?t:[t];let i=Object.assign({},r);i=Ud(i,e.s.db),i=jd(i,{db:e.s.db,collection:e},r),i.keepGoing===!0&&(i.ordered=!1),i.serializeFunctions=r.serializeFunctions||e.s.serializeFunctions,t=HM(e,t,r),e.s.topology.insert(e.s.namespace,t,i,(a,u)=>{if(n!=null){if(a)return mt(n,a);if(u==null)return mt(n,null,null);if(u.result.code)return mt(n,Li(u.result));if(u.result.writeErrors)return mt(n,Li(u.result.writeErrors[0]));u.ops=t,mt(n,null,u)}})}s(qee,"insertDocuments");function Pee(e,t,r,n){typeof r=="function"?(n=r,r={}):typeof t=="function"&&(n=t,r={},t={}),r=r||{};let i=Object.assign({},r);i=Ud(i,e.s.db),i=jd(i,{db:e.s.db,collection:e},r),t==null&&(t={});let a={q:t,limit:0};r.single?a.limit=1:i.retryWrites&&(i.retryWrites=!1),r.hint&&(a.hint=r.hint);try{of(i,e,r)}catch(u){return n(u,null)}if(r.explain!==void 0&&zM(e.s.topology)<3)return n?n(new Wd("server does not support explain on remove")):void 0;e.s.topology.remove(e.s.namespace,[a],i,(u,f)=>{if(n!=null){if(u)return mt(n,u,null);if(f==null)return mt(n,null,null);if(f.result.code)return mt(n,Li(f.result));if(f.result.writeErrors)return mt(n,Li(f.result.writeErrors[0]));mt(n,null,f)}})}s(Pee,"removeDocuments");function Lee(e,t,r,n,i){if(typeof n=="function"&&(i=n,n=null),n==null&&(n={}),typeof i!="function"&&(i=null),t==null||typeof t!="object")return i(Li("selector must be a valid JavaScript object"));if(r==null||typeof r!="object")return i(Li("document must be a valid JavaScript object"));let a=Object.assign({},n);a=Ud(a,e.s.db),a=jd(a,{db:e.s.db,collection:e},n),a.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions;let u={q:t,u:r};u.upsert=n.upsert!==void 0?!!n.upsert:!1,u.multi=n.multi!==void 0?!!n.multi:!1,n.hint&&(u.hint=n.hint),a.arrayFilters&&(u.arrayFilters=a.arrayFilters,delete a.arrayFilters),a.retryWrites&&u.multi&&(a.retryWrites=!1);try{of(a,e,n)}catch(f){return i(f,null)}if(n.explain!==void 0&&zM(e.s.topology)<3)return i?i(new Wd("server does not support explain on update")):void 0;e.s.topology.update(e.s.namespace,[u],a,(f,l)=>{if(i!=null){if(f)return mt(i,f,null);if(l==null)return mt(i,null,null);if(l.result.code)return mt(i,Li(l.result));if(l.result.writeErrors)return mt(i,Li(l.result.writeErrors[0]));mt(i,null,l)}})}s(Lee,"updateDocuments");VM.exports={buildCountCommand:Ree,findAndModify:xee,indexInformation:Mee,nextObject:Dee,prepareDocs:HM,insertDocuments:qee,removeDocuments:Pee,updateDocuments:Lee}});var Ga=E((LSe,XM)=>{"use strict";var Uee=x().applyWriteConcern,dv=G().BSON.Code,jee=Kt().createIndex,Wee=x().decorateWithCollation,YM=x().decorateWithReadConcern,Fee=Kt().ensureIndex,$ee=Kt().evaluate,pv=Kt().executeCommand,Ur=x().handleCallback,kM=Kt().indexInformation,zee=G().BSON.Long,Hee=G().MongoError,GM=G().ReadPreference,Vee=Nr().insertDocuments,Yee=Nr().updateDocuments,kee=`function () { +var c = db[ns].find(condition); +var map = new Map(); +var reduce_function = reduce; + +while (c.hasNext()) { +var obj = c.next(); +var key = {}; + +for (var i = 0, len = keys.length; i < len; ++i) { +var k = keys[i]; +key[k] = obj[k]; +} + +var aggObj = map.get(key); + +if (aggObj == null) { +var newObj = Object.extend({}, key); +aggObj = Object.extend(newObj, initial); +map.put(key, aggObj); +} + +reduce_function(obj, aggObj); +} + +return { "result": map.values() }; +}`;function Gee(e,t,r,n){jee(e.s.db,e.collectionName,t,r,n)}s(Gee,"createIndex");function Kee(e,t,r,n){let i=e.s.topology.capabilities();for(let a=0;a{p[g]=1}),m.group.key=p}f=Object.assign({},f),f.readPreference=GM.resolve(e,f),YM(m,e,f);try{Wee(m,e,f)}catch(p){return l(p,null)}pv(e.s.db,m,f,(p,g)=>{if(p)return Ur(l,p,null);Ur(l,null,g.retval)})}else{let h=i!=null&&i._bsontype==="Code"?i.scope:{};h.ns=e.collectionName,h.keys=t,h.condition=r,h.initial=n;let m=kee.replace(/ reduce;/,i.toString()+";");$ee(e.s.db,new dv(m,h),null,f,(p,g)=>{if(p)return Ur(l,p,null);Ur(l,null,g.result||g)})}}s(Jee,"group");function Zee(e,t,r){t=Object.assign({},{full:!0},t),kM(e.s.db,e.collectionName,t,r)}s(Zee,"indexes");function Qee(e,t,r,n){KM(e,r,(i,a)=>{if(i!=null)return Ur(n,i,null);if(!Array.isArray(t))return Ur(n,null,a[t]!=null);for(let u=0;u{if(a)return Ur(r,a,null);if(u==null)return Ur(r,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);let f=[];i&&(t.raw=i);for(let l=0;l{if(n!=null){if(t==null)return Ur(n,null,null);if(a)return Ur(n,a,null);Ur(n,null,u)}})}s(tte,"save");XM.exports={createIndex:Gee,createIndexes:Kee,ensureIndex:Xee,group:Jee,indexes:Zee,indexExists:Qee,indexInformation:KM,parallelCollectionScan:ete,save:tte}});var eD=E((jSe,QM)=>{"use strict";var rte=Ga().buildCountCommand,Ka=x().handleCallback,JM=G().MongoError,nte=Array.prototype.push,Fd=yn().CursorState;function ite(e,t,r,n){t&&(typeof e.cursorSkip()=="number"&&(r.skip=e.cursorSkip()),typeof e.cursorLimit()=="number"&&(r.limit=e.cursorLimit())),r.readPreference&&e.setReadPreference(r.readPreference),typeof r.maxTimeMS!="number"&&e.cmd&&typeof e.cmd.maxTimeMS=="number"&&(r.maxTimeMS=e.cmd.maxTimeMS);let i={};i.skip=r.skip,i.limit=r.limit,i.hint=r.hint,i.maxTimeMS=r.maxTimeMS,i.collectionName=e.namespace.collection;let a;try{a=rte(e,e.cmd.query,i)}catch(u){return n(u)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),a,e.options,(u,f)=>{n(u,f?f.result.n:null)})}s(ite,"count");function mv(e,t){if(!t)throw JM.create({message:"callback is mandatory",driver:!0});if(e.isNotified())return;if(e.s.state===Fd.CLOSED||e.isDead())return Ka(t,JM.create({message:"Cursor is closed",driver:!0}));e.s.state===Fd.INIT&&(e.s.state=Fd.OPEN);let r=null;if(e.bufferedCount()>0){for(;r=ZM(e,t);)r(e,t);mv(e,t)}else e.next((n,i)=>{if(n)return Ka(t,n);if(i==null)return e.close({skipKillCursors:!0},()=>Ka(t,null,null));Ka(t,null,i)!==!1&&mv(e,t)})}s(mv,"each");function ZM(e,t){if(e.bufferedCount()!==0)return e._next(t),ZM}s(ZM,"loop");function ste(e,t){let r=[];e.rewind(),e.s.state=Fd.INIT;let n=s(()=>{e._next((i,a)=>{if(i)return Ka(t,i);if(a==null)return e.close({skipKillCursors:!0},()=>Ka(t,null,r));if(r.push(a),e.bufferedCount()>0){let u=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&typeof e.s.transforms.doc=="function"&&(u=u.map(e.s.transforms.doc)),nte.apply(r,u)}n()})},"fetchDocs");n()}s(ste,"toArray");QM.exports={count:ite,each:mv,toArray:ste}});var rD=E((FSe,tD)=>{"use strict";var ote=Nr().buildCountCommand,ate=k().OperationBase,yv=class yv extends ate{constructor(t,r,n){super(n),this.cursor=t,this.applySkipLimit=r}execute(t){let r=this.cursor,n=this.applySkipLimit,i=this.options;n&&(typeof r.cursorSkip()=="number"&&(i.skip=r.cursorSkip()),typeof r.cursorLimit()=="number"&&(i.limit=r.cursorLimit())),i.readPreference&&r.setReadPreference(i.readPreference),typeof i.maxTimeMS!="number"&&r.cmd&&typeof r.cmd.maxTimeMS=="number"&&(i.maxTimeMS=r.cmd.maxTimeMS);let a={};a.skip=i.skip,a.limit=i.limit,a.hint=i.hint,a.maxTimeMS=i.maxTimeMS,a.collectionName=r.namespace.collection;let u;try{u=ote(r,r.cmd.query,a)}catch(f){return t(f)}r.server=r.topology.s.coreTopology,r.topology.command(r.namespace.withCollection("$cmd"),u,r.options,(f,l)=>{t(f,l?l.result.n:null)})}};s(yv,"CountOperation");var gv=yv;tD.exports=gv});var ri=E((zSe,uD)=>{"use strict";var ute=require("stream").Transform,cte=require("stream").PassThrough,_v=require("util").deprecate,nD=x().handleCallback,iD=G().ReadPreference,xe=G().MongoError,sD=yn().CoreCursor,ge=yn().CursorState,fte=G().BSON.Map,af=x().maybePromise,lte=Ia(),hte=x().formattedOrderClause,dte=Bc().Explain,pte=k().Aspect,Sv=eD().each,mte=rD(),oD=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],aD=["numberOfRetries","tailableRetryInterval"],$d=class $d extends sD{constructor(t,r,n,i){super(t,r,n,i),this.operation&&(i=this.operation.options);let a=i.numberOfRetries||5,u=i.tailableRetryInterval||500,f=a,l=i.promiseLibrary||Promise;this.s={numberOfRetries:a,tailableRetryInterval:u,currentNumberOfRetries:f,state:ge.INIT,promiseLibrary:l,explicitlyIgnoreSession:!!i.explicitlyIgnoreSession},!i.explicitlyIgnoreSession&&i.session&&(this.cursorState.session=i.session),this.options.noCursorTimeout===!0&&this.addCursorFlag("noCursorTimeout",!0);let h=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?h=this.cmd.cursor.batchSize:i.cursor&&i.cursor.batchSize?h=i.cursor.batchSize:typeof i.batchSize=="number"&&(h=i.batchSize),this.setCursorBatchSize(h)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}set session(t){this.cursorState.session=t}_initializeCursor(t){this.operation&&this.operation.session!=null?this.cursorState.session=this.operation.session:!this.s.explicitlyIgnoreSession&&!this.cursorState.session&&this.topology.hasSessionSupport()&&(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(t)}hasNext(t){if(this.s.state===ge.CLOSED||this.isDead&&this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return af(this,t,r=>{let n=this;if(n.isNotified())return r(null,!1);n._next((i,a)=>{if(i)return r(i);if(a==null||n.s.state===$d.CLOSED||n.isDead())return r(null,!1);n.s.state=ge.OPEN,n.cursorState.cursorIndex--,n.cursorState.limit>0&&n.cursorState.currentLimit--,r(null,!0)})})}next(t){return af(this,t,r=>{let n=this;if(n.s.state===ge.CLOSED||n.isDead&&n.isDead()){r(xe.create({message:"Cursor is closed",driver:!0}));return}if(n.s.state===ge.INIT&&n.cmd.sort)try{n.cmd.sort=hte(n.cmd.sort)}catch(i){return r(i)}n._next((i,a)=>{if(i)return r(i);n.s.state=ge.OPEN,r(null,a)})})}filter(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.query=t,this}maxScan(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=t,this}hint(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=t,this}min(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.min=t,this}max(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.max=t,this}returnKey(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=t,this}showRecordId(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=t,this}snapshot(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=t,this}setCursorOption(t,r){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});if(aD.indexOf(t)===-1)throw xe.create({message:`option ${t} is not a supported option ${aD}`,driver:!0});return this.s[t]=r,t==="numberOfRetries"&&(this.s.currentNumberOfRetries=r),this}addCursorFlag(t,r){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});if(oD.indexOf(t)===-1)throw xe.create({message:`flag ${t} is not a supported flag ${oD}`,driver:!0});if(typeof r!="boolean")throw xe.create({message:`flag ${t} must be a boolean value`,driver:!0});return this.cmd[t]=r,this}addQueryModifier(t,r){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});if(t[0]!=="$")throw xe.create({message:`${t} is not a valid query modifier`,driver:!0});let n=t.substr(1);return this.cmd[n]=r,n==="orderby"&&(this.cmd.sort=this.cmd[n]),this}comment(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=t,this}maxAwaitTimeMS(t){if(typeof t!="number")throw xe.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=t,this}maxTimeMS(t){if(typeof t!="number")throw xe.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=t,this}project(t){if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=t,this}sort(t,r){if(this.options.tailable)throw xe.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===ge.CLOSED||this.s.state===ge.OPEN||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});let n=t;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new fte(n.map(i=>{let a=[i[0],null];if(i[1]==="asc")a[1]=1;else if(i[1]==="desc")a[1]=-1;else if(i[1]===1||i[1]===-1||i[1].$meta)a[1]=i[1];else throw new xe("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");return a}))),r!=null&&(n=[[t,r]]),this.cmd.sort=n,this}batchSize(t){if(this.options.tailable)throw xe.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===ge.CLOSED||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw xe.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=t,this.setCursorBatchSize(t),this}collation(t){return this.cmd.collation=t,this}limit(t){if(this.options.tailable)throw xe.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===ge.OPEN||this.s.state===ge.CLOSED||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw xe.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=t,this.setCursorLimit(t),this}skip(t){if(this.options.tailable)throw xe.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===ge.OPEN||this.s.state===ge.CLOSED||this.isDead())throw xe.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw xe.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=t,this.setCursorSkip(t),this}each(t){this.rewind(),this.s.state=ge.INIT,Sv(this,t)}forEach(t,r){if(this.rewind(),this.s.state=ge.INIT,typeof r=="function")Sv(this,(n,i)=>{if(n)return r(n),!1;if(i!=null){try{t(i)}catch(a){return r(a),!1}return!0}if(i==null&&r){let a=r;return r=null,a(null),!1}});else return new this.s.promiseLibrary((n,i)=>{Sv(this,(a,u)=>{if(a)return i(a),!1;if(u==null)return n(null),!1;try{t(u)}catch(f){return i(f),!1}return!0})})}setReadPreference(t){if(this.s.state!==ge.INIT)throw xe.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(t instanceof iD)this.options.readPreference=t;else if(typeof t=="string")this.options.readPreference=new iD(t);else throw new TypeError("Invalid read preference: "+t);return this}toArray(t){if(this.options.tailable)throw xe.create({message:"Tailable cursor cannot be converted to array",driver:!0});return af(this,t,r=>{let n=this,i=[];n.rewind(),n.s.state=ge.INIT;let a=s(()=>{n._next((u,f)=>{if(u)return nD(r,u);if(f==null)return n.close({skipKillCursors:!0},()=>nD(r,null,i));if(i.push(f),n.bufferedCount()>0){let l=n.readBufferedDocuments(n.bufferedCount());Array.prototype.push.apply(i,l)}a()})},"fetchDocs");a()})}count(t,r,n){if(this.cmd.query==null)throw xe.create({message:"count can only be used with find command",driver:!0});typeof r=="function"&&(n=r,r={}),r=r||{},typeof t=="function"&&(n=t,t=!0),this.cursorState.session&&(r=Object.assign({},r,{session:this.cursorState.session}));let i=new mte(this,t,r);return lte(this.topology,i,n)}close(t,r){return typeof t=="function"&&(r=t,t={}),t=Object.assign({},{skipKillCursors:!1},t),af(this,r,n=>{this.s.state=ge.CLOSED,t.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),n(null,this)})})}map(t){if(this.cursorState.transforms&&this.cursorState.transforms.doc){let r=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>t(r(n))}else this.cursorState.transforms={doc:t};return this}isClosed(){return this.isDead()}destroy(t){t&&this.emit("error",t),this.pause(),this.close()}stream(t){return this.cursorState.streamOptions=t||{},this}transformStream(t){let r=t||{};if(typeof r.transform=="function"){let n=new ute({objectMode:!0,transform:function(i,a,u){this.push(r.transform(i)),u()}});return this.pipe(n)}return this.pipe(new cte({objectMode:!0}))}explain(t,r){if(typeof t=="function"&&(r=t,t=!0),t===void 0&&(t=!0),!this.operation||!this.operation.hasAspect(pte.EXPLAINABLE))throw new xe("This command cannot be explained");return this.operation.explain=new dte(t),af(this,r,n=>{sD.prototype._next.apply(this,[n])})}getLogger(){return this.logger}};s($d,"Cursor");var qs=$d;qs.prototype.maxTimeMs=qs.prototype.maxTimeMS;_v(qs.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead.");_v(qs.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version");_v(qs.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version");uD.exports=qs});var ni=E((VSe,lD)=>{"use strict";var zd=k().Aspect,gte=k().OperationBase,cD=G().ReadPreference,yte=ho(),Ste=wi(),_te=ce().maxWireVersion,wte=x().decorateWithExplain,vte=gs().commandSupportsReadConcern,Ote=X().MongoError,Ete=uo().extractCommand,fD=5,vv=class vv extends gte{constructor(t,r,n){super(r),this.ns=t.s.namespace.withCollection("$cmd");let i=this.hasAspect(zd.NO_INHERIT_OPTIONS)?void 0:t;this.readPreference=this.hasAspect(zd.WRITE_OPERATION)?cD.primary:cD.resolve(i,this.options),this.readConcern=Nte(i,this.options),this.writeConcern=Tte(i,this.options),n&&typeof n.fullResponse=="boolean"&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,t.s.logger?this.logger=t.s.logger:t.s.db&&t.s.db.logger&&(this.logger=t.s.db.logger)}executeCommand(t,r,n){this.server=t;let i=this.options,a=_te(t),u=this.session&&this.session.inTransaction();if(this.readConcern&&vte(r)&&!u&&Object.assign(r,{readConcern:this.readConcern}),i.collation&&a=fD&&(this.writeConcern&&this.hasAspect(zd.WRITE_OPERATION)&&Object.assign(r,{writeConcern:this.writeConcern}),i.collation&&typeof i.collation=="object"&&Object.assign(r,{collation:i.collation})),typeof i.maxTimeMS=="number"&&(r.maxTimeMS=i.maxTimeMS),typeof i.comment=="string"&&(r.comment=i.comment),this.hasAspect(zd.EXPLAINABLE)&&this.explain&&(a<6&&r.aggregate?r.explain=!0:r=wte(r,this.explain)),this.logger&&this.logger.isDebug()){let f=Ete(r);this.logger.debug(`executing command ${JSON.stringify(f.shouldRedact?`${f.name} details REDACTED`:r)} against ${this.ns}`)}t.command(this.ns.toString(),r,this.options,(f,l)=>{if(f){n(f,null);return}if(this.fullResponse){n(null,l);return}n(null,l.result)})}};s(vv,"CommandOperationV2");var wv=vv;function Tte(e,t){return Ste.fromOptions(t)||e&&e.writeConcern}s(Tte,"resolveWriteConcern");function Nte(e,t){return yte.fromOptions(t)||e&&e.readConcern}s(Nte,"resolveReadConcern");lD.exports=wv});var uf=E((kSe,dD)=>{"use strict";var bte=ni(),hD=G().MongoError,Ate=ce().maxWireVersion,Cte=G().ReadPreference,Hd=k().Aspect,Ite=k().defineAspects,Bte=1,Rte=8,Ov=class Ov extends bte{constructor(t,r,n){if(super(t,n,{fullResponse:!0}),this.target=t.s.namespace&&t.s.namespace.collection?t.s.namespace.collection:Bte,this.pipeline=r,this.hasWriteStage=!1,typeof n.out=="string")this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(r.length>0){let i=r[r.length-1];(i.$out||i.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=Cte.primary),this.explain&&this.writeConcern)throw new hD('"explain" cannot be used on an aggregate call with writeConcern');if(n.cursor!=null&&typeof n.cursor!="object")throw new hD("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(t){this.pipeline.push(t)}execute(t,r){let n=this.options,i=Ate(t),a={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&i=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(a,{writeConcern:this.writeConcern}),n.bypassDocumentValidation===!0&&(a.bypassDocumentValidation=n.bypassDocumentValidation),typeof n.allowDiskUse=="boolean"&&(a.allowDiskUse=n.allowDiskUse),n.hint&&(a.hint=n.hint),this.explain&&(n.full=!1),a.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(a.cursor.batchSize=n.batchSize),super.executeCommand(t,a,r)}};s(Ov,"AggregateOperation");var Vd=Ov;Ite(Vd,[Hd.READ_OPERATION,Hd.RETRYABLE,Hd.EXECUTE_WITH_SELECTION,Hd.EXPLAINABLE]);dD.exports=Vd});var Zd=E((KSe,yD)=>{"use strict";var mD=G().BSON.Long,xte=G().MongoError,Yd=G().BSON.ObjectID,br=G().BSON,pD=G().MongoWriteConcernError,Ev=x().emitWarningOnce,Bo=x().toError,xo=x().handleCallback,Mte=x().applyRetryableWrites,Dte=x().applyWriteConcern,qte=x().executeLegacyOperation,Pte=x().isPromiseLike,Gd=x().hasAtomicOperators,Lte=ce().maxWireVersion,Ute=64,Ro=1,Ui=2,Ps=3,jte=new br([br.Binary,br.Code,br.DBRef,br.Decimal128,br.Double,br.Int32,br.Long,br.Map,br.MaxKey,br.MinKey,br.ObjectId,br.BSONRegExp,br.Symbol,br.Timestamp]),bv=class bv{constructor(t,r){this.originalZeroIndex=r,this.currentIndex=0,this.originalIndexes=[],this.batchType=t,this.operations=[],this.size=0,this.sizeBytes=0}};s(bv,"Batch");var Tv=bv,Xa=Symbol("upsertedIds"),Ja=Symbol("insertedIds"),Av=class Av{constructor(t){this.result=t,this[Xa]=void 0,this[Ja]=void 0}get insertedCount(){return typeof this.result.nInserted!="number"?0:this.result.nInserted}get matchedCount(){return typeof this.result.nMatched!="number"?0:this.result.nMatched}get modifiedCount(){return typeof this.result.nModified!="number"?0:this.result.nModified}get deletedCount(){return typeof this.result.nRemoved!="number"?0:this.result.nRemoved}get upsertedCount(){return this.result.upserted?this.result.upserted.length:0}get upsertedIds(){if(this[Xa])return this[Xa];this[Xa]={};for(let t of this.result.upserted||[])this[Xa][t.index]=t._id;return this[Xa]}get insertedIds(){if(this[Ja])return this[Ja];this[Ja]={};for(let t of this.result.insertedIds||[])this[Ja][t.index]=t._id;return this[Ja]}get n(){return this.result.insertedCount}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(t){return this.result.upserted[t]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(t){return ti.multi)),t.batch.batchType===Ps&&(n.retryWrites=n.retryWrites&&!t.batch.operations.some(i=>i.limit===0)));try{t.batch.batchType===Ro?this.s.topology.insert(this.s.namespace,t.batch.operations,n,t.resultHandler):t.batch.batchType===Ui?this.s.topology.update(this.s.namespace,t.batch.operations,n,t.resultHandler):t.batch.batchType===Ps&&this.s.topology.remove(this.s.namespace,t.batch.operations,n,t.resultHandler)}catch(i){i.ok=0,xo(r,null,Jd(t.batch,this.s.bulkResult,i,null))}}handleWriteError(t,r){if(this.s.bulkResult.writeErrors.length>0){let n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return xo(t,new Qa(Bo({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),r),null),!0}if(r.getWriteConcernError())return xo(t,new Qa(Bo(r.getWriteConcernError()),r),null),!0}};s(xv,"BulkOperationBase");var Xd=xv;Object.defineProperty(Xd.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}});yD.exports={Batch:Tv,BulkOperationBase:Xd,mergeBatchResults:Jd,bson:jte,INSERT:Ro,UPDATE:Ui,REMOVE:Ps,BulkWriteError:Qa,BulkWriteResult:Za}});var vD=E((JSe,Mv)=>{"use strict";var ji=Zd(),Fte=ji.BulkOperationBase,SD=ji.Batch,$te=ji.bson,zte=x(),_D=zte.toError;function Hte(e,t,r){let n=$te.calculateObjectSize(r,{checkKeys:!1,ignoreUndefined:!1});if(n>=e.s.maxBsonObjectSize)throw _D("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===ji.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===ji.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===ji.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);let i=e.s.maxKeySize;if(e.s.currentBatch==null&&(e.s.currentBatch=new SD(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+i+n>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new SD(t,e.s.currentIndex)),Array.isArray(r))throw _D("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(r),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===ji.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:r._id})):t===ji.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===ji.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=i+n,e}s(Hte,"addToOperationsList");var Dv=class Dv extends Fte{constructor(t,r,n){n=n||{},n=Object.assign(n,{addToOperationsList:Hte}),super(t,r,n,!1)}handleWriteError(t,r){return this.s.batches.length?!1:super.handleWriteError(t,r)}};s(Dv,"UnorderedBulkOperation");var ff=Dv;function wD(e,t,r){return new ff(e,t,r)}s(wD,"initializeUnorderedBulkOp");wD.UnorderedBulkOperation=ff;Mv.exports=wD;Mv.exports.Bulk=ff});var ND=E((QSe,qv)=>{"use strict";var Qd=Zd(),Vte=Qd.BulkOperationBase,OD=Qd.Batch,Yte=Qd.bson,kte=x(),ED=kte.toError;function Gte(e,t,r){let n=Yte.calculateObjectSize(r,{checkKeys:!1,ignoreUndefined:!1});if(n>=e.s.maxBsonObjectSize)throw ED("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch==null&&(e.s.currentBatch=new OD(t,e.s.currentIndex));let i=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+i+n>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new OD(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===Qd.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:r._id}),Array.isArray(r))throw ED("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(r),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=i+n,e.s.currentIndex+=1,e}s(Gte,"addToOperationsList");var Pv=class Pv extends Vte{constructor(t,r,n){n=n||{},n=Object.assign(n,{addToOperationsList:Gte}),super(t,r,n,!0)}};s(Pv,"OrderedBulkOperation");var lf=Pv;function TD(e,t,r){return new lf(e,t,r)}s(TD,"initializeOrderedBulkOp");TD.OrderedBulkOperation=lf;qv.exports=TD;qv.exports.Bulk=lf});var ep=E((t0e,AD)=>{"use strict";var bD=G().MongoError,Kte=ri(),Xte=yn().CursorState,Lv=class Lv extends Kte{constructor(t,r,n){super(t,r,n)}batchSize(t){if(this.s.state===Xte.CLOSED||this.isDead())throw bD.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw bD.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=t,this.setCursorBatchSize(t),this}geoNear(t){return this.operation.addToPipeline({$geoNear:t}),this}group(t){return this.operation.addToPipeline({$group:t}),this}limit(t){return this.operation.addToPipeline({$limit:t}),this}match(t){return this.operation.addToPipeline({$match:t}),this}maxTimeMS(t){return this.operation.options.maxTimeMS=t,this}out(t){return this.operation.addToPipeline({$out:t}),this}project(t){return this.operation.addToPipeline({$project:t}),this}lookup(t){return this.operation.addToPipeline({$lookup:t}),this}redact(t){return this.operation.addToPipeline({$redact:t}),this}skip(t){return this.operation.addToPipeline({$skip:t}),this}sort(t){return this.operation.addToPipeline({$sort:t}),this}unwind(t){return this.operation.addToPipeline({$unwind:t}),this}getLogger(){return this.logger}};s(Lv,"AggregationCursor");var hf=Lv;hf.prototype.get=hf.prototype.toArray;AD.exports=hf});var rp=E((n0e,ID)=>{"use strict";var CD=G().ReadPreference,tp=G().MongoError,Jte=ri(),Uv=yn().CursorState,jv=class jv extends Jte{constructor(t,r,n,i){super(t,r,n,i)}setReadPreference(t){if(this.s.state===Uv.CLOSED||this.isDead())throw tp.create({message:"Cursor is closed",driver:!0});if(this.s.state!==Uv.INIT)throw tp.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(t instanceof CD)this.options.readPreference=t;else if(typeof t=="string")this.options.readPreference=new CD(t);else throw new TypeError("Invalid read preference: "+t);return this}batchSize(t){if(this.s.state===Uv.CLOSED||this.isDead())throw tp.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw tp.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=t),this.setCursorBatchSize(t),this}maxTimeMS(t){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=t),this}getLogger(){return this.logger}};s(jv,"CommandCursor");var df=jv;df.prototype.get=df.prototype.toArray;ID.exports=df});var $v=E((s0e,BD)=>{"use strict";var Zte=x().applyRetryableWrites,Qte=x().applyWriteConcern,ere=G().MongoError,tre=k().OperationBase,Fv=class Fv extends tre{constructor(t,r,n){super(n),this.collection=t,this.operations=r}execute(t){let r=this.collection,n=this.operations,i=this.options;r.s.options.ignoreUndefined&&(i=Object.assign({},i),i.ignoreUndefined=r.s.options.ignoreUndefined);let a=i.ordered===!0||i.ordered==null?r.initializeOrderedBulkOp(i):r.initializeUnorderedBulkOp(i),u=!1;try{for(let m=0;m{if(!p&&m)return t(m,null);t(null,p)})}};s(Fv,"BulkWriteOperation");var Wv=Fv;BD.exports=Wv});var Vv=E((a0e,RD)=>{"use strict";var rre=uf(),Hv=class Hv extends rre{constructor(t,r,n){let i=[{$match:r}];typeof n.skip=="number"&&i.push({$skip:n.skip}),typeof n.limit=="number"&&i.push({$limit:n.limit}),i.push({$group:{_id:1,n:{$sum:1}}}),super(t,i,n)}execute(t,r){super.execute(t,(n,i)=>{if(n){r(n,null);return}let a=i.result;if(a.cursor==null||a.cursor.firstBatch==null){r(null,0);return}let u=a.cursor.firstBatch;r(null,u.length?u[0].n:0)})}};s(Hv,"CountDocumentsOperation");var zv=Hv;RD.exports=zv});var kv=E((c0e,DD)=>{"use strict";var xD=k().Aspect,nre=k().defineAspects,ire=ni(),MD=G().MongoError,sre=x().parseIndexOptions,ore=ce().maxWireVersion,are=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]),Yv=class Yv extends ire{constructor(t,r,n,i){if(super(t,i),this.collection=r,!Array.isArray(n)||Array.isArray(n[0])){this.onlyReturnNameOfCreatedIndex=!0;let a=sre(n),f={name:typeof i.name=="string"?i.name:a.name,key:a.fieldHash};for(let l in i)are.has(l)&&(f[l]=i[l]);this.indexes=[f];return}this.indexes=n}execute(t,r){let n=this.options,i=this.indexes,a=ore(t);for(let f=0;f{if(f){r(f);return}r(null,this.onlyReturnNameOfCreatedIndex?i[0].name:l)})}};s(Yv,"CreateIndexesOperation");var np=Yv;nre(np,[xD.WRITE_OPERATION,xD.EXECUTE_WITH_SELECTION]);DD.exports=np});var PD=E((l0e,qD)=>{"use strict";var ure=k().OperationBase,cre=Nr().removeDocuments,fre=k().Aspect,lre=k().defineAspects,Gv=class Gv extends ure{constructor(t,r,n){super(n),this.collection=t,this.filter=r}execute(t){let r=this.collection,n=this.filter,i=this.options;i.single=!1,cre(r,n,i,(a,u)=>{if(t!=null){if(a&&t)return t(a);if(u==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,u.result);u.deletedCount=u.result.n,t(null,u)}})}};s(Gv,"DeleteManyOperation");var ip=Gv;lre(ip,[fre.EXPLAINABLE]);qD.exports=ip});var UD=E((d0e,LD)=>{"use strict";var hre=k().OperationBase,dre=Nr().removeDocuments,pre=k().Aspect,mre=k().defineAspects,Kv=class Kv extends hre{constructor(t,r,n){super(n),this.collection=t,this.filter=r}execute(t){let r=this.collection,n=this.filter,i=this.options;i.single=!0,dre(r,n,i,(a,u)=>{if(t!=null){if(a&&t)return t(a);if(u==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,u.result);u.deletedCount=u.result.n,t(null,u)}})}};s(Kv,"DeleteOneOperation");var sp=Kv;mre(sp,[pre.EXPLAINABLE]);LD.exports=sp});var WD=E((m0e,jD)=>{"use strict";var op=k().Aspect,gre=k().defineAspects,yre=ni(),Sre=x().decorateWithCollation,_re=x().decorateWithReadConcern,wre=ce().maxWireVersion,vre=sf().MongoError,Xv=class Xv extends yre{constructor(t,r,n,i){super(t,i),this.collection=t,this.key=r,this.query=n}execute(t,r){let n=this.collection,i=this.key,a=this.query,u=this.options,f={distinct:n.collectionName,key:i,query:a};typeof u.maxTimeMS=="number"&&(f.maxTimeMS=u.maxTimeMS),_re(f,n,u);try{Sre(f,n,u)}catch(l){return r(l,null)}if(this.explain&&wre(t)<4){r(new vre("server does not support explain on distinct"));return}super.executeCommand(t,f,(l,h)=>{if(l){r(l);return}r(null,this.options.full||this.explain?h:h.values)})}};s(Xv,"DistinctOperation");var ap=Xv;gre(ap,[op.READ_OPERATION,op.RETRYABLE,op.EXECUTE_WITH_SELECTION,op.EXPLAINABLE]);jD.exports=ap});var Un=E((y0e,zD)=>{"use strict";var FD=k().Aspect,Ore=k().OperationBase,$D=x().applyWriteConcern,Ere=x().debugOptions,Jv=x().handleCallback,Tre=G().MongoError,Zv=G().ReadPreference,Nre=x().MongoDBNamespace,bre=uo().extractCommand,Are=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"],eO=class eO extends Ore{constructor(t,r,n,i){super(r),this.hasAspect(FD.WRITE_OPERATION)?(n!=null?$D(this.options,{db:t,coll:n},this.options):$D(this.options,{db:t},this.options),this.options.readPreference=Zv.primary):n!=null?this.options.readPreference=Zv.resolve(n,r):this.options.readPreference=Zv.resolve(t,r),this.db=t,i!=null&&(this.command=i),n!=null&&(this.collection=n)}_buildCommand(){if(this.command!=null)return this.command}execute(t){let r=this.db,n=Object.assign({},this.options);if(r.serverConfig&&r.serverConfig.isDestroyed())return t(new Tre("topology was destroyed"));let i;try{i=this._buildCommand()}catch(f){return t(f)}let a=n.dbName||n.authdb||r.databaseName;if(this.hasAspect(FD.WRITE_OPERATION)&&n.writeConcern&&(!n.session||!n.session.inTransaction())&&(i.writeConcern=n.writeConcern),r.s.logger.isDebug()){let f=bre(i);r.s.logger.debug(`executing command ${JSON.stringify(f.shouldRedact?`${f.name} details REDACTED`:i)} against ${a}.$cmd with options [${JSON.stringify(Ere(Are,n))}]`)}let u=this.namespace!=null?this.namespace:new Nre(a,"$cmd");r.s.topology.command(u,i,n,(f,l)=>{if(f)return Jv(t,f);if(n.full)return Jv(t,null,l);Jv(t,null,l.result)})}};s(eO,"CommandOperation");var Qv=eO;zD.exports=Qv});var up=E((_0e,HD)=>{"use strict";var Cre=k().Aspect,Ire=Un(),Bre=k().defineAspects,tO=x().handleCallback,iO=class iO extends Ire{constructor(t,r){let n=Object.assign({},r,t.s.options);r.session&&(n.session=r.session),super(t,n)}execute(t){super.execute((r,n)=>{if(r)return tO(t,r);if(n.ok)return tO(t,null,!0);tO(t,null,!1)})}};s(iO,"DropOperation");var eu=iO;Bre(eu,Cre.WRITE_OPERATION);var sO=class sO extends eu{constructor(t,r,n){super(t,n),this.name=r,this.namespace=`${t.namespace}.${r}`}_buildCommand(){return{drop:this.name}}};s(sO,"DropCollectionOperation");var rO=sO,oO=class oO extends eu{_buildCommand(){return{dropDatabase:1}}};s(oO,"DropDatabaseOperation");var nO=oO;HD.exports={DropOperation:eu,DropCollectionOperation:rO,DropDatabaseOperation:nO}});var uO=E((v0e,YD)=>{"use strict";var Rre=k().Aspect,xre=k().defineAspects,Mre=Un(),Dre=x().applyWriteConcern,VD=x().handleCallback,aO=class aO extends Mre{constructor(t,r,n){super(t.s.db,n,t),this.collection=t,this.indexName=r}_buildCommand(){let t=this.collection,r=this.indexName,n=this.options,i={dropIndexes:t.collectionName,index:r};return i=Dre(i,{db:t.s.db,collection:t},n),i}execute(t){super.execute((r,n)=>{if(typeof t=="function"){if(r)return VD(t,r,null);VD(t,null,n)}})}};s(aO,"DropIndexOperation");var cp=aO;xre(cp,Rre.WRITE_OPERATION);YD.exports=cp});var KD=E((E0e,GD)=>{"use strict";var qre=k().Aspect,Pre=k().defineAspects,Lre=uO(),kD=x().handleCallback,cO=class cO extends Lre{constructor(t,r){super(t,"*",r)}execute(t){super.execute(r=>{if(r)return kD(t,r,!1);kD(t,null,!0)})}};s(cO,"DropIndexesOperation");var fp=cO;Pre(fp,qre.WRITE_OPERATION);GD.exports=fp});var JD=E((N0e,XD)=>{"use strict";var Ure=ro().MONGODB_ERROR_CODES,fO=k().Aspect,jre=k().defineAspects,Wre=ni(),Fre=ce().maxWireVersion,$re=Vv(),lO=class lO extends Wre{constructor(t,r){super(t,r),this.collection=t,this.collectionName=t.s.namespace.collection}execute(t,r){if(Fre(t)<12)return this.executeLegacy(t,r);if(this.options.query)return new $re(this.collection,this.options.query,this.options).execute(t,r);let n=[{$collStats:{count:{}}},{$group:{_id:1,n:{$sum:"$count"}}}],i={aggregate:this.collectionName,pipeline:n,cursor:{}};typeof this.options.maxTimeMS=="number"&&(i.maxTimeMS=this.options.maxTimeMS),super.executeCommand(t,i,(a,u)=>{if(a&&a.code!==Ure.NamespaceNotFound){r(a);return}r(void 0,u&&u.cursor&&u.cursor.firstBatch&&u.cursor.firstBatch[0].n||0)})}executeLegacy(t,r){let n={count:this.collectionName},i=this.options;i.query&&(n.query=i.query),i.hint&&(n.hint=i.hint),typeof i.maxTimeMS=="number"&&(n.maxTimeMS=i.maxTimeMS),typeof i.skip=="number"&&(n.skip=i.skip),typeof i.limit=="number"&&(n.limit=i.limit),super.executeCommand(t,n,(a,u)=>{if(a){r(a);return}r(null,u.n)})}};s(lO,"EstimatedDocumentCountOperation");var lp=lO;jre(lp,[fO.READ_OPERATION,fO.RETRYABLE,fO.EXECUTE_WITH_SELECTION]);XD.exports=lp});var eq=E((A0e,QD)=>{"use strict";var zre=k().OperationBase,hp=k().Aspect,Hre=k().defineAspects,ZD=G().ReadPreference,Vre=ce().maxWireVersion,Yre=X().MongoError,hO=class hO extends zre{constructor(t,r,n,i){super(i),this.ns=r,this.cmd=n,this.readPreference=ZD.resolve(t,this.options)}execute(t,r){if(this.server=t,this.readPreference=ZD.resolve(this,this.options),typeof this.cmd.allowDiskUse<"u"&&Vre(t)<4){r(new Yre("The `allowDiskUse` option is not supported on MongoDB < 3.2"));return}this.explain&&(this.options.explain=this.explain.verbosity);let n=this.cursorState||{};t.query(this.ns.toString(),this.cmd,n,this.options,r)}};s(hO,"FindOperation");var dp=hO;Hre(dp,[hp.READ_OPERATION,hp.RETRYABLE,hp.EXECUTE_WITH_SELECTION,hp.EXPLAINABLE]);QD.exports=dp});var nq=E((I0e,rq)=>{"use strict";var tq=x().handleCallback,kre=k().OperationBase,Gre=x().toError,Kre=k().Aspect,Xre=k().defineAspects,dO=class dO extends kre{constructor(t,r,n){super(n),this.collection=t,this.query=r}execute(t){let r=this.collection,n=this.query,i=this.options;try{r.find(n,i).limit(-1).batchSize(1).next((u,f)=>{if(u!=null)return tq(t,Gre(u),null);tq(t,null,f)})}catch(a){t(a)}}};s(dO,"FindOneOperation");var pp=dO;Xre(pp,[Kre.EXPLAINABLE]);rq.exports=pp});var pf=E((R0e,aq)=>{"use strict";var Jre=k().OperationBase,Zre=x().applyRetryableWrites,Qre=x().applyWriteConcern,ene=x().decorateWithCollation,tne=Kt().executeCommand,rne=x().formattedOrderClause,iq=x().handleCallback,nne=G().ReadPreference,sq=ce().maxWireVersion,oq=sf().MongoError,ine=k().Aspect,sne=k().defineAspects,one=x().decorateWithExplain,pO=class pO extends Jre{constructor(t,r,n,i,a){super(a),this.collection=t,this.query=r,this.sort=n,this.doc=i}execute(t){let r=this.collection,n=this.query,i=rne(this.sort),a=this.doc,u=this.options,f={findAndModify:r.collectionName,query:n};i&&(f.sort=i),f.new=!!u.new,f.remove=!!u.remove,f.upsert=!!u.upsert;let l=u.projection||u.fields;l&&(f.fields=l),u.arrayFilters&&(f.arrayFilters=u.arrayFilters),a&&!u.remove&&(f.update=a),u.maxTimeMS&&(f.maxTimeMS=u.maxTimeMS),u.serializeFunctions=u.serializeFunctions||r.s.serializeFunctions,u.checkKeys=!1,u=Zre(u,r.s.db),u=Qre(u,{db:r.s.db,collection:r},u),u.writeConcern&&(f.writeConcern=u.writeConcern),u.bypassDocumentValidation===!0&&(f.bypassDocumentValidation=u.bypassDocumentValidation),u.readPreference=nne.primary;try{ene(f,r,u)}catch(h){return t(h,null)}if(u.hint){if(u.writeConcern&&u.writeConcern.w===0||sq(r.s.topology)<8){t(new oq("The current topology does not support a hint on findAndModify commands"));return}f.hint=u.hint}if(this.explain){if(sq(r.s.topology)<4){t(new oq("server does not support explain on findAndModify"));return}f=one(f,this.explain)}tne(r.s.db,f,u,(h,m)=>h?iq(t,h,null):iq(t,null,m))}};s(pO,"FindAndModifyOperation");var mp=pO;sne(mp,[ine.EXPLAINABLE]);aq.exports=mp});var cq=E((M0e,uq)=>{"use strict";var ane=pf(),gO=class gO extends ane{constructor(t,r,n){let i=Object.assign({},n);if(i.fields=n.projection,i.remove=!0,r==null||typeof r!="object")throw new TypeError("Filter parameter must be an object");super(t,r,i.sort,null,i)}};s(gO,"FindOneAndDeleteOperation");var mO=gO;uq.exports=mO});var lq=E((q0e,fq)=>{"use strict";var une=G().MongoError,cne=pf(),fne=x().hasAtomicOperators,SO=class SO extends cne{constructor(t,r,n,i){if("returnDocument"in i&&"returnOriginal"in i)throw new une("findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined");let a=Object.assign({},i);if(a.fields=i.projection,a.update=!0,a.new=i.returnDocument==="after"||i.returnOriginal===!1,a.upsert=i.upsert===!0,r==null||typeof r!="object")throw new TypeError("Filter parameter must be an object");if(n==null||typeof n!="object")throw new TypeError("Replacement parameter must be an object");if(fne(n))throw new TypeError("Replacement document must not contain atomic operators");super(t,r,a.sort,n,a)}};s(SO,"FindOneAndReplaceOperation");var yO=SO;fq.exports=yO});var dq=E((L0e,hq)=>{"use strict";var lne=G().MongoError,hne=pf(),dne=x().hasAtomicOperators,wO=class wO extends hne{constructor(t,r,n,i){if("returnDocument"in i&&"returnOriginal"in i)throw new lne("findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined");let a=Object.assign({},i);if(a.fields=i.projection,a.update=!0,a.new=i.returnDocument==="after"||i.returnOriginal===!1,a.upsert=i.upsert===!0,r==null||typeof r!="object")throw new TypeError("Filter parameter must be an object");if(n==null||typeof n!="object")throw new TypeError("Update parameter must be an object");if(!dne(n))throw new TypeError("Update document requires atomic operators");super(t,r,a.sort,n,a)}};s(wO,"FindOneAndUpdateOperation");var _O=wO;hq.exports=_O});var mq=E((j0e,pq)=>{"use strict";var pne=k().Aspect,mne=k().defineAspects,gne=k().OperationBase,yne=x().decorateCommand,Sne=x().decorateWithReadConcern,_ne=Kt().executeCommand,vO=x().handleCallback,wne=G().ReadPreference,vne=x().toError,OO=class OO extends gne{constructor(t,r,n,i){super(i),this.collection=t,this.x=r,this.y=n}execute(t){let r=this.collection,n=this.x,i=this.y,a=this.options,u={geoSearch:r.collectionName,near:[n,i]};u=yne(u,a,["readPreference","session"]),a=Object.assign({},a),a.readPreference=wne.resolve(r,a),Sne(u,r,a),_ne(r.s.db,u,a,(f,l)=>{if(f)return vO(t,f);(l.err||l.errmsg)&&vO(t,vne(l)),vO(t,null,l)})}};s(OO,"GeoHaystackSearchOperation");var gp=OO;mne(gp,pne.READ_OPERATION);pq.exports=gp});var yq=E((F0e,gq)=>{"use strict";var One=k().OperationBase,Ene=Nr().indexInformation,TO=class TO extends One{constructor(t,r){super(r),this.collection=t}execute(t){let r=this.collection,n=this.options;n=Object.assign({},{full:!0},n),Ene(r.s.db,r.collectionName,n,t)}};s(TO,"IndexesOperation");var EO=TO;gq.exports=EO});var _q=E((z0e,Sq)=>{"use strict";var Tne=k().OperationBase,yp=x().handleCallback,Nne=Kt().indexInformation,bO=class bO extends Tne{constructor(t,r,n){super(n),this.collection=t,this.indexes=r}execute(t){let r=this.collection,n=this.indexes,i=this.options;Nne(r.s.db,r.collectionName,i,(a,u)=>{if(a!=null)return yp(t,a,null);if(!Array.isArray(n))return yp(t,null,u[n]!=null);for(let f=0;f{"use strict";var bne=k().OperationBase,Ane=Nr().indexInformation,CO=class CO extends bne{constructor(t,r,n){super(n),this.db=t,this.name=r}execute(t){let r=this.db,n=this.name,i=this.options;Ane(r,n,i,t)}};s(CO,"IndexInformationOperation");var AO=CO;wq.exports=AO});var Oq=E((k0e,vq)=>{"use strict";var Cne=k().OperationBase,Ine=$v(),Bne=G().MongoError,Rne=Nr().prepareDocs,RO=class RO extends Cne{constructor(t,r,n){super(n),this.collection=t,this.docs=r}execute(t){let r=this.collection,n=this.docs,i=this.options;if(!Array.isArray(n))return t(Bne.create({message:"docs parameter must be an array of documents",driver:!0}));i.serializeFunctions=i.serializeFunctions||r.s.serializeFunctions,n=Rne(r,n,i);let a=n.map(f=>({insertOne:{document:f}}));new Ine(r,a,i).execute((f,l)=>{if(f)return t(f,null);t(null,xne(n,l))})}};s(RO,"InsertManyOperation");var BO=RO;function xne(e,t){let r={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};return t.getLastOp()&&(r.result.opTime=t.getLastOp()),r}s(xne,"mapInsertManyResults");vq.exports=BO});var Tq=E((K0e,Eq)=>{"use strict";var Mne=G().MongoError,Dne=k().OperationBase,qne=Nr().insertDocuments,MO=class MO extends Dne{constructor(t,r,n){super(n),this.collection=t,this.doc=r}execute(t){let r=this.collection,n=this.doc,i=this.options;if(Array.isArray(n))return t(Mne.create({message:"doc parameter must be an object",driver:!0}));qne(r,[n],i,(a,u)=>{if(t!=null){if(a&&t)return t(a);if(u==null)return t(null,{result:{ok:1}});u.insertedCount=u.result.n,u.insertedId=n._id,t&&t(null,u)}})}};s(MO,"InsertOneOperation");var xO=MO;Eq.exports=xO});var LO=E((J0e,Nq)=>{"use strict";var Pne=k().OperationBase,DO=x().handleCallback,Lne=G().MongoError,PO=class PO extends Pne{constructor(t,r){super(r),this.collection=t}execute(t){let r=this.collection,n=this.options;r.s.db.listCollections({name:r.collectionName},n).toArray((i,a)=>{if(i)return DO(t,i);if(a.length===0)return DO(t,Lne.create({message:`collection ${r.namespace} not found`,driver:!0}));DO(t,i,a[0].options||null)})}};s(PO,"OptionsOperation");var qO=PO;Nq.exports=qO});var Cq=E((Q0e,Aq)=>{"use strict";var Une=LO(),bq=x().handleCallback,jO=class jO extends Une{constructor(t,r){super(t,r)}execute(t){super.execute((r,n)=>{if(r)return bq(t,r);bq(t,null,!!(n&&n.capped))})}};s(jO,"IsCappedOperation");var UO=jO;Aq.exports=UO});var Bq=E((t_e,Iq)=>{"use strict";var jne=ni(),WO=k().Aspect,Wne=k().defineAspects,Fne=ce().maxWireVersion,$ne=3,FO=class FO extends jne{constructor(t,r){super(t,r,{fullResponse:!0}),this.collectionNamespace=t.s.namespace}execute(t,r){if(Fne(t)<$ne){let a=this.collectionNamespace.withCollection("system.indexes").toString(),u=this.collectionNamespace.toString();t.query(a,{query:{ns:u}},{},this.options,r);return}let i=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(t,{listIndexes:this.collectionNamespace.collection,cursor:i},r)}};s(FO,"ListIndexesOperation");var Sp=FO;Wne(Sp,[WO.READ_OPERATION,WO.RETRYABLE,WO.EXECUTE_WITH_SELECTION]);Iq.exports=Sp});var zO=E((n_e,xq)=>{"use strict";var zne=k().Aspect,Hne=Un(),Vne=k().defineAspects,Yne=require("crypto"),Rq=x().handleCallback,kne=x().toError,Gne=x().emitWarning,$O=class $O extends Hne{constructor(t,r,n,i){super(t,i),this.username=r,this.password=n}_buildCommand(){let t=this.db,r=this.username,n=this.password,i=this.options,a=[];Array.isArray(i.roles)&&(a=i.roles),typeof i.roles=="string"&&(a=[i.roles]),a.length===0&&Gne("Creating a user without roles is deprecated in MongoDB >= 2.6"),(t.databaseName.toLowerCase()==="admin"||i.dbName==="admin")&&!Array.isArray(i.roles)?a=["root"]:Array.isArray(i.roles)||(a=["dbOwner"]);let u=t.s.topology.lastIsMaster().maxWireVersion>=7,f=n;if(!u){let h=Yne.createHash("md5");h.update(r+":mongo:"+n),f=h.digest("hex")}let l={createUser:r,customData:i.customData||{},roles:a,digestPassword:u};return typeof n=="string"&&(l.pwd=f),l}execute(t){if(this.options.digestPassword!=null)return t(kne("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((n,i)=>n?Rq(t,n,null):Rq(t,n,i))}};s($O,"AddUserOperation");var _p=$O;Vne(_p,zne.WRITE_OPERATION);xq.exports=_p});var qq=E((s_e,Dq)=>{"use strict";var Kne=k().OperationBase,Mq=x().handleCallback,HO;function Xne(){return HO||(HO=tu()),HO}s(Xne,"loadCollection");var YO=class YO extends Kne{constructor(t,r){super(r),this.db=t}execute(t){let r=this.db,n=this.options,i=Xne();n=Object.assign({},n,{nameOnly:!0}),r.listCollections({},n).toArray((a,u)=>{if(a!=null)return Mq(t,a,null);u=u.filter(f=>f.name.indexOf("$")===-1),Mq(t,null,u.map(f=>new i(r,r.s.topology,r.databaseName,f.name,r.s.pkFactory,r.s.options)))})}};s(YO,"CollectionsOperation");var VO=YO;Dq.exports=VO});var Uq=E((a_e,Lq)=>{"use strict";var Jne=ni(),Zne=k().defineAspects,Pq=k().Aspect,kO=class kO extends Jne{constructor(t,r,n){super(t,n),this.command=r}execute(t,r){let n=this.command;this.executeCommand(t,n,r)}};s(kO,"RunCommandOperation");var wp=kO;Zne(wp,[Pq.EXECUTE_WITH_SELECTION,Pq.NO_INHERIT_OPTIONS]);Lq.exports=wp});var Wq=E((c_e,jq)=>{"use strict";var Qne=k().Aspect,eie=k().defineAspects,tie=Un(),rie=x().applyWriteConcern,nie=Op().loadCollection,iie=G().MongoError,sie=G().ReadPreference,oie=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]),GO=class GO extends tie{constructor(t,r,n){super(t,n),this.name=r}_buildCommand(){let t=this.name,r=this.options,n={create:t};for(let i in r)r[i]!=null&&typeof r[i]!="function"&&!oie.has(i)&&(n[i]=r[i]);return n}execute(t){let r=this.db,n=this.name,i=this.options,a=nie(),u=Object.assign({nameOnly:!0,strict:!1},i);u=rie(u,{db:r},u);function f(h){if(h)return t(h);try{t(null,new a(r,r.s.topology,r.databaseName,n,r.s.pkFactory,i))}catch(m){t(m)}}if(s(f,"done"),u.strict){r.listCollections({name:n},u).setReadPreference(sie.PRIMARY).toArray((h,m)=>{if(h)return t(h);if(m.length>0)return t(new iie(`Collection ${n} already exists. Currently in strict mode.`));super.execute(f)});return}super.execute(f)}};s(GO,"CreateCollectionOperation");var vp=GO;eie(vp,Qne.WRITE_OPERATION);jq.exports=vp});var JO=E((l_e,$q)=>{"use strict";var aie=k().OperationBase,Fq=x().handleCallback,uie=G().MongoError,cie=x().MongoDBNamespace,XO=class XO extends aie{constructor(t,r,n){super(n),this.db=t,this.selector=r}execute(t){let r=this.db,n=this.selector,i=this.options,a=new cie("admin","$cmd");r.s.topology.command(a,n,i,(u,f)=>{if(r.serverConfig&&r.serverConfig.isDestroyed())return t(new uie("topology was destroyed"));if(u)return Fq(t,u);Fq(t,null,f.result)})}};s(XO,"ExecuteDbAdminCommandOperation");var KO=XO;$q.exports=KO});var Hq=E((d_e,zq)=>{"use strict";var fie=ni(),ZO=k().Aspect,lie=k().defineAspects,hie=ce().maxWireVersion,die=Ld(),pie=3;function mie(e){let t=`${e}.`;return{doc:r=>{let n=r.name.indexOf(t);return r.name&&n===0&&(r.name=r.name.substr(n+t.length)),r}}}s(mie,"listCollectionsTransforms");var QO=class QO extends fie{constructor(t,r,n){super(t,n,{fullResponse:!0}),this.db=t,this.filter=r,this.nameOnly=!!this.options.nameOnly,typeof this.options.batchSize=="number"&&(this.batchSize=this.options.batchSize)}execute(t,r){if(hie(t){l&&l.message&&l.message.documents&&Array.isArray(l.message.documents)&&(l.message.documents=l.message.documents.map(u.doc)),r(f,l)});return}let n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(t,n,r)}};s(QO,"ListCollectionsOperation");var Ep=QO;lie(Ep,[ZO.READ_OPERATION,ZO.RETRYABLE,ZO.EXECUTE_WITH_SELECTION]);zq.exports=Ep});var Yq=E((m_e,Vq)=>{"use strict";var gie=Un(),tE=class tE extends gie{constructor(t,r,n){super(t,n)}_buildCommand(){return{profile:-1}}execute(t){super.execute((r,n)=>{if(r==null&&n.ok===1){let i=n.was;return i===0?t(null,"off"):i===1?t(null,"slow_only"):i===2?t(null,"all"):t(new Error("Error: illegal profiling level value "+i),null)}else r!=null?t(r,null):t(new Error("Error with profile command"),null)})}};s(tE,"ProfilingLevelOperation");var eE=tE;Vq.exports=eE});var nE=E((y_e,Gq)=>{"use strict";var yie=k().Aspect,Sie=Un(),_ie=k().defineAspects,kq=x().handleCallback,wie=wi(),rE=class rE extends Sie{constructor(t,r,n){let i={},a=wie.fromOptions(n);a!=null&&(i.writeConcern=a),n.dbName&&(i.dbName=n.dbName),typeof n.maxTimeMS=="number"&&(i.maxTimeMS=n.maxTimeMS),super(t,i),this.username=r}_buildCommand(){return{dropUser:this.username}}execute(t){super.execute((r,n)=>{if(r)return kq(t,r,null);kq(t,r,!!n.ok)})}};s(rE,"RemoveUserOperation");var Tp=rE;_ie(Tp,yie.WRITE_OPERATION);Gq.exports=Tp});var oE=E((__e,Xq)=>{"use strict";var vie=k().OperationBase,Oie=x().applyWriteConcern,Eie=x().checkCollectionName,Tie=Kt().executeDbAdminCommand,Np=x().handleCallback,Nie=Op().loadCollection,Kq=x().toError,sE=class sE extends vie{constructor(t,r,n){super(n),this.collection=t,this.newName=r}execute(t){let r=this.collection,n=this.newName,i=this.options,a=Nie();Eie(n);let u=r.namespace,f=r.s.namespace.withCollection(n).toString(),l=typeof i.dropTarget=="boolean"?i.dropTarget:!1,h={renameCollection:u,to:f,dropTarget:l};Oie(h,{db:r.s.db,collection:r},i),Tie(r.s.db.admin().s.db,h,i,(m,p)=>{if(m)return Np(t,m,null);if(p.errmsg)return Np(t,Kq(p),null);try{return Np(t,null,new a(r.s.db,r.s.topology,r.s.namespace.db,n,r.s.pkFactory,r.s.options))}catch(g){return Np(t,Kq(g),null)}})}};s(sE,"RenameOperation");var iE=sE;Xq.exports=iE});var Zq=E((v_e,Jq)=>{"use strict";var bie=Un(),Aie=new Set(["off","slow_only","all"]),uE=class uE extends bie{constructor(t,r,n){let i=0;r==="off"?i=0:r==="slow_only"?i=1:r==="all"&&(i=2),super(t,n),this.level=r,this.profile=i}_buildCommand(){return{profile:this.profile}}execute(t){let r=this.level;if(!Aie.has(r))return t(new Error("Error: illegal profiling level value "+r));super.execute((n,i)=>n==null&&i.ok===1?t(null,r):n!=null?t(n,null):t(new Error("Error with profile command"),null))}};s(uE,"SetProfilingLevelOperation");var aE=uE;Jq.exports=aE});var eP=E((E_e,Qq)=>{"use strict";var Cie=Un(),fE=class fE extends Cie{constructor(t,r,n){let i={validate:r},a=Object.keys(n);for(let u=0;un!=null?t(n,null):i.ok===0?t(new Error("Error with validate command"),null):i.result!=null&&i.result.constructor!==String?t(new Error("Error with validation data"),null):i.result!=null&&i.result.match(/exception|corrupt/)!=null?t(new Error("Error: invalid collection "+r),null):i.valid!=null&&!i.valid?t(new Error("Error: invalid collection "+r),null):t(null,i))}};s(fE,"ValidateCollectionOperation");var cE=fE;Qq.exports=cE});var rP=E((N_e,tP)=>{"use strict";var Iie=ni(),lE=k().Aspect,Bie=k().defineAspects,Rie=x().MongoDBNamespace,hE=class hE extends Iie{constructor(t,r){super(t,r),this.ns=new Rie("admin","$cmd")}execute(t,r){let n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),typeof this.options.authorizedDatabases=="boolean"&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(t,n,r)}};s(hE,"ListDatabasesOperation");var bp=hE;Bie(bp,[lE.READ_OPERATION,lE.RETRYABLE,lE.EXECUTE_WITH_SELECTION]);tP.exports=bp});var dE=E((A_e,iP)=>{"use strict";var nP=x().applyWriteConcern,xie=zO(),ru=JO(),Mie=nE(),Die=eP(),qie=rP(),ii=Ia();function en(e,t,r){if(!(this instanceof en))return new en(e,t);this.s={db:e,topology:t,promiseLibrary:r}}s(en,"Admin");en.prototype.command=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift():{};let i=new ru(this.s.db,e,t);return ii(this.s.db.s.topology,i,r)};en.prototype.buildInfo=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={buildinfo:1},n=new ru(this.s.db,r,e);return ii(this.s.db.s.topology,n,t)};en.prototype.serverInfo=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={buildinfo:1},n=new ru(this.s.db,r,e);return ii(this.s.db.s.topology,n,t)};en.prototype.serverStatus=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new ru(this.s.db,{serverStatus:1},e);return ii(this.s.db.s.topology,r,t)};en.prototype.ping=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={ping:1},n=new ru(this.s.db,r,e);return ii(this.s.db.s.topology,n,t)};en.prototype.addUser=function(e,t,r,n){let i=Array.prototype.slice.call(arguments,2);n=typeof i[i.length-1]=="function"?i.pop():void 0,typeof e=="string"&&t!=null&&typeof t=="object"&&(r=t,t=null),r=i.length?i.shift():{},r=Object.assign({},r),r=nP(r,{db:this.s.db}),r.dbName="admin";let a=new xie(this.s.db,e,t,r);return ii(this.s.db.s.topology,a,n)};en.prototype.removeUser=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift():{},t=Object.assign({},t),t=nP(t,{db:this.s.db}),t.dbName="admin";let i=new Mie(this.s.db,e,t);return ii(this.s.db.s.topology,i,r)};en.prototype.validateCollection=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new Die(this,e,t);return ii(this.s.db.s.topology,n,r)};en.prototype.listDatabases=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},ii(this.s.db.s.topology,new qie(this.s.db,e),t)};en.prototype.replSetGetStatus=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new ru(this.s.db,{replSetGetStatus:1},e);return ii(this.s.db.s.topology,r,t)};iP.exports=en});var gf=E((I_e,fP)=>{"use strict";var uP=require("events").EventEmitter,Pie=require("util").inherits,pE=x().getSingleProperty,Lie=rp(),Ap=x().handleCallback,Uie=x().filterOptions,sP=x().toError,Cp=G().ReadPreference,oP=G().MongoError,jie=G().ObjectID,Wie=G().Logger,aP=tu(),Fie=x().conditionallyMergeWriteConcern,mE=x().executeLegacyOperation,$ie=Ip(),mf=require("util").deprecate,cP=x().deprecateOptions,zie=x().MongoDBNamespace,nu=Ld(),Hie=wi(),gE=ho(),Vie=ep(),Ls=Kt().createListener,Yie=Kt().ensureIndex,kie=Kt().evaluate,Gie=Kt().profilingInfo,Kie=Kt().validateDatabaseName,Xie=uf(),Jie=zO(),Zie=qq(),Qie=Un(),ese=Uq(),tse=Wq(),rse=kv(),nse=up().DropCollectionOperation,ise=up().DropDatabaseOperation,sse=JO(),ose=IO(),ase=Hq(),use=Yq(),cse=nE(),fse=oE(),lse=Zq(),jr=Ia(),hse=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","bsonRegExp","compression","retryWrites"];function Se(e,t,r){if(r=r||{},!(this instanceof Se))return new Se(e,t,r);uP.call(this);let n=r.promiseLibrary||Promise;r=Uie(r,hse),r.promiseLibrary=n,this.s={dbCache:{},children:[],topology:t,options:r,logger:Wie("Db",r),bson:t?t.bson:null,readPreference:Cp.fromOptions(r),bufferMaxEntries:typeof r.bufferMaxEntries=="number"?r.bufferMaxEntries:-1,parentDb:r.parentDb||null,pkFactory:r.pkFactory||jie,nativeParser:r.nativeParser||r.native_parser,promiseLibrary:n,noListener:typeof r.noListener=="boolean"?r.noListener:!1,readConcern:gE.fromOptions(r),writeConcern:Hie.fromOptions(r),namespace:new zie(e)},Kie(e),pE(this,"serverConfig",this.s.topology),pE(this,"bufferMaxEntries",this.s.bufferMaxEntries),pE(this,"databaseName",this.s.namespace.db),!r.parentDb&&(this.s.noListener||(t.on("error",Ls(this,"error",this)),t.on("timeout",Ls(this,"timeout",this)),t.on("close",Ls(this,"close",this)),t.on("parseError",Ls(this,"parseError",this)),t.once("open",Ls(this,"open",this)),t.once("fullsetup",Ls(this,"fullsetup",this)),t.once("all",Ls(this,"all",this)),t.on("reconnect",Ls(this,"reconnect",this))))}s(Se,"Db");Pie(Se,uP);Se.prototype.on=mf(function(){return Se.super_.prototype.on.apply(this,arguments)},"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Se.prototype.once=mf(function(){return Se.super_.prototype.once.apply(this,arguments)},"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Object.defineProperty(Se.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}});Object.defineProperty(Se.prototype,"options",{enumerable:!0,get:function(){return this.s.options}});Object.defineProperty(Se.prototype,"slaveOk",{enumerable:!0,get:function(){return this.s.options.readPreference!=null&&(this.s.options.readPreference!=="primary"||this.s.options.readPreference.mode!=="primary")}});Object.defineProperty(Se.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}});Object.defineProperty(Se.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference==null?Cp.primary:this.s.readPreference}});Object.defineProperty(Se.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}});Object.defineProperty(Se.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}});Se.prototype.command=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t);let n=new ese(this,e,t);return jr(this.s.topology,n,r)};Se.prototype.aggregate=function(e,t,r){typeof t=="function"&&(r=t,t={}),t==null&&r==null&&(t={});let n=new Vie(this.s.topology,new Xie(this,e,t),t);if(typeof r=="function"){r(null,n);return}return n};Se.prototype.admin=function(){let e=dE();return new e(this,this.s.topology,this.s.promiseLibrary)};var dse=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs","bsonRegExp"];Se.prototype.collection=cP({name:"Db.collection",deprecatedOptions:["strict"],optionsIndex:1},function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},t=Object.assign({},t),t.promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new gE(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined);for(let i of dse)!(i in t)&&this.s.options[i]!==void 0&&(t[i]=this.s.options[i]);if(t=Fie(t,this.s.options),t==null||!t.strict)try{let i=new aP(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return r&&r(null,i),i}catch(i){if(i instanceof oP&&r)return r(i);throw i}if(typeof r!="function")throw sP(`A callback is required in strict mode. While getting collection ${e}`);if(this.serverConfig&&this.serverConfig.isDestroyed())return r(new oP("topology was destroyed"));let n=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},n).toArray((i,a)=>{if(i!=null)return Ap(r,i,null);if(a.length===0)return Ap(r,sP(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return Ap(r,null,new aP(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(u){return Ap(r,u,null)}})});Se.prototype.createCollection=cP({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},t.promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new gE(t.readConcern.level):this.readConcern;let n=new tse(this,e,t);return jr(this.s.topology,n,r)});Se.prototype.stats=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={dbStats:!0};e.scale!=null&&(r.scale=e.scale),e.readPreference==null&&this.s.readPreference&&(e.readPreference=this.s.readPreference);let n=new Qie(this,e,null,r);return jr(this.s.topology,n,t)};Se.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new Lie(this.s.topology,new ase(this,e,t),t)};Se.prototype.eval=mf(function(e,t,r,n){let i=Array.prototype.slice.call(arguments,1);return n=typeof i[i.length-1]=="function"?i.pop():void 0,t=i.length?i.shift():t,r=i.length?i.shift()||{}:{},mE(this.s.topology,kie,[this,e,t,r,n])},"Db.eval is deprecated as of MongoDB version 3.2");Se.prototype.renameCollection=function(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=Object.assign({},r,{readPreference:Cp.PRIMARY}),r.new_collection=!0;let i=new fse(this.collection(e),t,r);return jr(this.s.topology,i,n)};Se.prototype.dropCollection=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new nse(this,e,t);return jr(this.s.topology,n,r)};Se.prototype.dropDatabase=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new ise(this,e);return jr(this.s.topology,r,t)};Se.prototype.collections=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new Zie(this,e);return jr(this.s.topology,r,t)};Se.prototype.executeDbAdminCommand=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},t.readPreference=Cp.resolve(this,t);let n=new sse(this,e,t);return jr(this.s.topology,n,r)};Se.prototype.createIndex=function(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=r?Object.assign({},r):{};let i=new rse(this,e,t,r);return jr(this.s.topology,i,n)};Se.prototype.ensureIndex=mf(function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},mE(this.s.topology,Yie,[this,e,t,r,n])},"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0");Se.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)};Se.prototype.addUser=function(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=r||{},typeof e=="string"&&t!=null&&typeof t=="object"&&(r=t,t=null);let i=new Jie(this,e,t,r);return jr(this.s.topology,i,n)};Se.prototype.removeUser=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new cse(this,e,t);return jr(this.s.topology,n,r)};Se.prototype.setProfilingLevel=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new lse(this,e,t);return jr(this.s.topology,n,r)};Se.prototype.profilingInfo=mf(function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},mE(this.s.topology,Gie,[this,e,t])},"Db.profilingInfo is deprecated. Query the system.profile collection directly.");Se.prototype.profilingLevel=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new use(this,e);return jr(this.s.topology,r,t)};Se.prototype.indexInformation=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new ose(this,e,t);return jr(this.s.topology,n,r)};Se.prototype.unref=function(){this.s.topology.unref()};Se.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new $ie(this,e,t)};Se.prototype.getLogger=function(){return this.s.logger};Se.SYSTEM_NAMESPACE_COLLECTION=nu.SYSTEM_NAMESPACE_COLLECTION;Se.SYSTEM_INDEX_COLLECTION=nu.SYSTEM_INDEX_COLLECTION;Se.SYSTEM_PROFILE_COLLECTION=nu.SYSTEM_PROFILE_COLLECTION;Se.SYSTEM_USER_COLLECTION=nu.SYSTEM_USER_COLLECTION;Se.SYSTEM_COMMAND_COLLECTION=nu.SYSTEM_COMMAND_COLLECTION;Se.SYSTEM_JS_COLLECTION=nu.SYSTEM_JS_COLLECTION;fP.exports=Se});var Op=E((R_e,lP)=>{"use strict";var yE,SE,_E;function pse(){return yE||(yE=tu()),yE}s(pse,"loadCollection");function mse(){return SE||(SE=ri()),SE}s(mse,"loadCursor");function gse(){return _E||(_E=gf()),_E}s(gse,"loadDb");lP.exports={loadCollection:pse,loadCursor:mse,loadDb:gse}});var pP=E((M_e,dP)=>{"use strict";var yse=x().applyWriteConcern,Sse=G().BSON.Code,_se=x().decorateWithCollation,wse=x().decorateWithReadConcern,vse=Kt().executeCommand,iu=x().handleCallback,Ose=x().isObject,Ese=Op().loadDb,Tse=k().OperationBase,Nse=G().ReadPreference,bse=x().toError,Ase=k().Aspect,Cse=k().defineAspects,Ise=x().decorateWithExplain,Bse=ce().maxWireVersion,Rse=sf().MongoError,xse=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"],wE=class wE extends Tse{constructor(t,r,n,i){super(i),this.collection=t,this.map=r,this.reduce=n}execute(t){let r=this.collection,n=this.map,i=this.reduce,a=this.options,u={mapReduce:r.collectionName,map:n,reduce:i};for(let f in a)f==="scope"?u[f]=hP(a[f]):xse.indexOf(f)===-1&&(u[f]=a[f]);a=Object.assign({},a),a.readPreference=Nse.resolve(r,a),a.readPreference!==!1&&a.readPreference!=="primary"&&a.out&&a.out.inline!==1&&a.out!=="inline"?(a.readPreference="primary",yse(u,{db:r.s.db,collection:r},a)):wse(u,r,a),a.bypassDocumentValidation===!0&&(u.bypassDocumentValidation=a.bypassDocumentValidation);try{_se(u,r,a)}catch(f){return t(f,null)}if(this.explain){if(Bse(r.s.topology)<9){t(new Rse("server does not support explain on mapReduce"));return}u=Ise(u,this.explain)}vse(r.s.db,u,a,(f,l)=>{if(f)return iu(t,f);if(l.ok!==1||l.err||l.errmsg)return iu(t,bse(l));if(this.explain)return t(void 0,l);let h={};if(l.timeMillis&&(h.processtime=l.timeMillis),l.counts&&(h.counts=l.counts),l.timing&&(h.timing=l.timing),l.results)return a.verbose==null||!a.verbose?iu(t,null,l.results):iu(t,null,{results:l.results,stats:h});let m=null;if(l.result!=null&&typeof l.result=="object"){let p=l.result,g=Ese();m=new g(p.db,r.s.db.s.topology,r.s.db.s.options).collection(p.collection)}else m=r.s.db.collection(l.result);if(a.verbose==null||!a.verbose)return iu(t,f,m);iu(t,f,{collection:m,stats:h})})}};s(wE,"MapReduceOperation");var Bp=wE;function hP(e){if(!Ose(e)||e._bsontype==="ObjectID")return e;let t=Object.keys(e),r,n={};for(let i=t.length-1;i>=0;i--)r=t[i],typeof e[r]=="function"?n[r]=new Sse(String(e[r])):n[r]=hP(e[r]);return n}s(hP,"processScope");Cse(Bp,[Ase.EXPLAINABLE]);dP.exports=Bp});var gP=E((q_e,mP)=>{"use strict";var Mse=k().Aspect,Dse=k().defineAspects,qse=ni(),Pse=tr().serverType,Lse=tr().ServerType,Use=G().MongoError,vE=class vE extends qse{constructor(t,r){super(t,r),this.collectionName=t.collectionName}execute(t,r){if(Pse(t)!==Lse.Standalone){r(new Use("reIndex can only be executed on standalone servers."));return}super.executeCommand(t,{reIndex:this.collectionName},(n,i)=>{if(n){r(n);return}r(null,!!i.ok)})}};s(vE,"ReIndexOperation");var Rp=vE;Dse(Rp,[Mse.EXECUTE_WITH_SELECTION]);mP.exports=Rp});var SP=E((L_e,yP)=>{"use strict";var jse=k().OperationBase,Wse=Nr().updateDocuments,Fse=x().hasAtomicOperators,EE=class EE extends jse{constructor(t,r,n,i){if(super(i),Fse(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=t,this.filter=r,this.replacement=n}execute(t){let r=this.collection,n=this.filter,i=this.replacement,a=this.options;a.multi=!1,Wse(r,n,i,a,(u,f)=>$se(u,f,i,t))}};s(EE,"ReplaceOneOperation");var OE=EE;function $se(e,t,r,n){if(n!=null){if(e&&n)return n(e);if(t==null)return n(null,{result:{ok:1}});t.modifiedCount=t.result.nModified!=null?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[r],n&&n(null,t)}}s($se,"replaceCallback");yP.exports=OE});var wP=E((j_e,_P)=>{"use strict";var zse=k().Aspect,Hse=Un(),Vse=k().defineAspects,TE=class TE extends Hse{constructor(t,r){super(t.s.db,r,t)}_buildCommand(){let t=this.collection,r=this.options,n={collStats:t.collectionName};return r.scale!=null&&(n.scale=r.scale),n}};s(TE,"StatsOperation");var xp=TE;Vse(xp,zse.READ_OPERATION);_P.exports=xp});var OP=E((F_e,vP)=>{"use strict";var Yse=k().OperationBase,kse=Nr().updateDocuments,Gse=x().hasAtomicOperators,Kse=k().Aspect,Xse=k().defineAspects,NE=class NE extends Yse{constructor(t,r,n,i){if(super(i),!Gse(n))throw new TypeError("Update document requires atomic operators");this.collection=t,this.filter=r,this.update=n}execute(t){let r=this.collection,n=this.filter,i=this.update,a=this.options;a.multi=!0,kse(r,n,i,a,(u,f)=>{if(t!=null){if(u)return t(u);if(f==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,f.result);f.modifiedCount=f.result.nModified!=null?f.result.nModified:f.result.n,f.upsertedId=Array.isArray(f.result.upserted)&&f.result.upserted.length>0?f.result.upserted[0]:null,f.upsertedCount=Array.isArray(f.result.upserted)&&f.result.upserted.length?f.result.upserted.length:0,f.matchedCount=Array.isArray(f.result.upserted)&&f.result.upserted.length>0?0:f.result.n,t(null,f)}})}};s(NE,"UpdateManyOperation");var Mp=NE;Xse(Mp,[Kse.EXPLAINABLE]);vP.exports=Mp});var TP=E((z_e,EP)=>{"use strict";var Jse=k().OperationBase,Zse=Nr().updateDocuments,Qse=x().hasAtomicOperators,eoe=k().Aspect,toe=k().defineAspects,bE=class bE extends Jse{constructor(t,r,n,i){if(super(i),!Qse(n))throw new TypeError("Update document requires atomic operators");this.collection=t,this.filter=r,this.update=n}execute(t){let r=this.collection,n=this.filter,i=this.update,a=this.options;a.multi=!1,Zse(r,n,i,a,(u,f)=>{if(t!=null){if(u)return t(u);if(f==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,f.result);f.modifiedCount=f.result.nModified!=null?f.result.nModified:f.result.n,f.upsertedId=Array.isArray(f.result.upserted)&&f.result.upserted.length>0?f.result.upserted[0]:null,f.upsertedCount=Array.isArray(f.result.upserted)&&f.result.upserted.length?f.result.upserted.length:0,f.matchedCount=Array.isArray(f.result.upserted)&&f.result.upserted.length>0?0:f.result.n,t(null,f)}})}};s(bE,"UpdateOneOperation");var Dp=bE;toe(Dp,[eoe.EXPLAINABLE]);EP.exports=Dp});var tu=E((V_e,MP)=>{"use strict";var tn=require("util").deprecate,qp=x().deprecateOptions,NP=x().emitWarningOnce,roe=x().checkCollectionName,noe=G().BSON.ObjectID,bP=G().MongoError,AP=x().normalizeHintField,ioe=x().decorateCommand,soe=x().decorateWithCollation,ooe=x().decorateWithReadConcern,aoe=x().formattedOrderClause,su=G().ReadPreference,uoe=vD(),coe=ND(),foe=Ip(),ou=x().executeLegacyOperation,loe=wi(),hoe=ho(),doe=x().MongoDBNamespace,poe=ep(),moe=rp(),goe=Ga().ensureIndex,yoe=Ga().group,Soe=Ga().parallelCollectionScan,_oe=Nr().removeDocuments,woe=Ga().save,voe=Nr().updateDocuments,Ooe=uf(),Eoe=$v(),Toe=Vv(),CP=kv(),Noe=PD(),boe=UD(),Aoe=WD(),Coe=up().DropCollectionOperation,Ioe=uO(),Boe=KD(),IP=JD(),Roe=eq(),xoe=nq(),BP=pf(),Moe=cq(),Doe=lq(),qoe=dq(),Poe=mq(),Loe=yq(),Uoe=_q(),joe=IO(),Woe=Oq(),Foe=Tq(),$oe=Cq(),zoe=Bq(),Hoe=pP(),Voe=LO(),Yoe=oE(),koe=gP(),Goe=SP(),Koe=wP(),Xoe=OP(),Joe=TP(),Ve=Ia(),Zoe=["ignoreUndefined"];function ie(e,t,r,n,i,a){roe(n);let u=null,f=a==null||a.slaveOk==null?e.slaveOk:a.slaveOk,l=a==null||a.serializeFunctions==null?e.s.options.serializeFunctions:a.serializeFunctions,h=a==null||a.raw==null?e.s.options.raw:a.raw,m=a==null||a.promoteLongs==null?e.s.options.promoteLongs:a.promoteLongs,p=a==null||a.promoteValues==null?e.s.options.promoteValues:a.promoteValues,g=a==null||a.promoteBuffers==null?e.s.options.promoteBuffers:a.promoteBuffers,w=a==null||a.bsonRegExp==null?e.s.options.bsonRegExp:a.bsonRegExp,O=null,N=new doe(r,n),A=a.promiseLibrary||Promise;i=i??noe,this.s={pkFactory:i,db:e,topology:t,options:a,namespace:N,readPreference:su.fromOptions(a),slaveOk:f,serializeFunctions:l,raw:h,promoteLongs:m,promoteValues:p,promoteBuffers:g,bsonRegExp:w,internalHint:u,collectionHint:O,promiseLibrary:A,readConcern:hoe.fromOptions(a),writeConcern:loe.fromOptions(a)}}s(ie,"Collection");Object.defineProperty(ie.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}});Object.defineProperty(ie.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}});Object.defineProperty(ie.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}});Object.defineProperty(ie.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern==null?this.s.db.readConcern:this.s.readConcern}});Object.defineProperty(ie.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference==null?this.s.db.readPreference:this.s.readPreference}});Object.defineProperty(ie.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern==null?this.s.db.writeConcern:this.s.writeConcern}});Object.defineProperty(ie.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=AP(e)}});var RP=["maxScan","fields","snapshot","oplogReplay"];ie.prototype.find=qp({name:"collection.find",deprecatedOptions:RP,optionsIndex:1},function(e,t,r){typeof r=="object"&&NP("Third parameter to `find()` must be a callback or undefined");let n=e;typeof r!="function"&&(typeof t=="function"?(r=t,t=void 0):t==null&&(r=typeof n=="function"?n:void 0,n=typeof n=="object"?n:void 0)),n=n??{};let i=n;if(Buffer.isBuffer(i)){let h=i[0]|i[1]<<8|i[2]<<16|i[3]<<24;if(h!==i.length){let m=new Error("query selector raw message size does not match message header size ["+i.length+"] != ["+h+"]");throw m.name="MongoError",m}}n!=null&&n._bsontype==="ObjectID"&&(n={_id:n}),t||(t={});let a=t.projection||t.fields;a&&!Buffer.isBuffer(a)&&Array.isArray(a)&&(a=a.length?a.reduce((h,m)=>(h[m]=1,h),{}):{_id:1});let u=Object.assign({},t);for(let h in this.s.options)Zoe.indexOf(h)!==-1&&(u[h]=this.s.options[h]);if(u.skip=t.skip?t.skip:0,u.limit=t.limit?t.limit:0,u.raw=typeof t.raw=="boolean"?t.raw:this.s.raw,u.hint=t.hint!=null?AP(t.hint):this.s.collectionHint,u.timeout=typeof t.timeout>"u"?void 0:t.timeout,u.slaveOk=t.slaveOk!=null?t.slaveOk:this.s.db.slaveOk,u.readPreference=su.resolve(this,u),u.readPreference!=null&&(u.readPreference!=="primary"||u.readPreference.mode!=="primary")&&(u.slaveOk=!0),n!=null&&typeof n!="object")throw bP.create({message:"query selector must be an object",driver:!0});let f={find:this.s.namespace.toString(),limit:u.limit,skip:u.skip,query:n};typeof t.allowDiskUse=="boolean"&&(f.allowDiskUse=t.allowDiskUse),typeof u.awaitdata=="boolean"&&(u.awaitData=u.awaitdata),typeof u.timeout=="boolean"&&(u.noCursorTimeout=!u.timeout),ioe(f,u,["session","collation"]),a&&(f.fields=a),u.db=this.s.db,u.promiseLibrary=this.s.promiseLibrary,u.raw==null&&typeof this.s.raw=="boolean"&&(u.raw=this.s.raw),u.promoteLongs==null&&typeof this.s.promoteLongs=="boolean"&&(u.promoteLongs=this.s.promoteLongs),u.promoteValues==null&&typeof this.s.promoteValues=="boolean"&&(u.promoteValues=this.s.promoteValues),u.promoteBuffers==null&&typeof this.s.promoteBuffers=="boolean"&&(u.promoteBuffers=this.s.promoteBuffers),u.bsonRegExp==null&&typeof this.s.bsonRegExp=="boolean"&&(u.bsonRegExp=this.s.bsonRegExp),f.sort&&(f.sort=aoe(f.sort)),ooe(f,this,t);try{soe(f,this,t)}catch(h){if(typeof r=="function")return r(h,null);throw h}let l=this.s.topology.cursor(new Roe(this,this.s.namespace,f,u),u);if(typeof r=="function"){r(null,l);return}return l});ie.prototype.insertOne=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined);let n=new Foe(this,e,t);return Ve(this.s.topology,n,r)};ie.prototype.insertMany=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t?Object.assign({},t):{ordered:!0};let n=new Woe(this,e,t);return Ve(this.s.topology,n,r)};ie.prototype.bulkWrite=function(e,t,r){if(typeof t=="function"&&(r=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw bP.create({message:"operations must be an array of documents",driver:!0});let n=new Eoe(this,e,t);return Ve(this.s.topology,n,r)};ie.prototype.insert=tn(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],t.keepGoing===!0&&(t.ordered=!1),this.insertMany(e,t,r)},"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.");ie.prototype.updateOne=function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=Object.assign({},r),this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Ve(this.s.topology,new Joe(this,e,t,r),n)};ie.prototype.replaceOne=function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=Object.assign({},r),this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Ve(this.s.topology,new Goe(this,e,t,r),n)};ie.prototype.updateMany=function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=Object.assign({},r),this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Ve(this.s.topology,new Xoe(this,e,t,r),n)};ie.prototype.update=tn(function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),ou(this.s.topology,voe,[this,e,t,r,n])},"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.");ie.prototype.deleteOne=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined);let n=new boe(this,e,t);return Ve(this.s.topology,n,r)};ie.prototype.removeOne=ie.prototype.deleteOne;ie.prototype.deleteMany=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined);let n=new Noe(this,e,t);return Ve(this.s.topology,n,r)};ie.prototype.removeMany=ie.prototype.deleteMany;ie.prototype.remove=tn(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined),ou(this.s.topology,_oe,[this,e,t,r])},"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.");ie.prototype.save=tn(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined),ou(this.s.topology,woe,[this,e,t,r])},"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.");ie.prototype.findOne=qp({name:"collection.find",deprecatedOptions:RP,optionsIndex:1},function(e,t,r){typeof r=="object"&&NP("Third parameter to `findOne()` must be a callback or undefined"),typeof e=="function"&&(r=e,e={},t={}),typeof t=="function"&&(r=t,t={}),e=e||{},t=t||{};let n=new xoe(this,e,t);return Ve(this.s.topology,n,r)});ie.prototype.rename=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t,{readPreference:su.PRIMARY});let n=new Yoe(this,e,t);return Ve(this.s.topology,n,r)};ie.prototype.drop=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new Coe(this.s.db,this.collectionName,e);return Ve(this.s.topology,r,t)};ie.prototype.options=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new Voe(this,e);return Ve(this.s.topology,r,t)};ie.prototype.isCapped=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new $oe(this,e);return Ve(this.s.topology,r,t)};ie.prototype.createIndex=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new CP(this,this.collectionName,e,t);return Ve(this.s.topology,n,r)};ie.prototype.createIndexes=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t?Object.assign({},t):{},typeof t.maxTimeMS!="number"&&delete t.maxTimeMS;let n=new CP(this,this.collectionName,e,t);return Ve(this.s.topology,n,r)};ie.prototype.dropIndex=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift()||{}:{},t.readPreference=su.PRIMARY;let i=new Ioe(this,e,t);return Ve(this.s.topology,i,r)};ie.prototype.dropIndexes=function(e,t){typeof e=="function"&&(t=e,e={}),e=e?Object.assign({},e):{},typeof e.maxTimeMS!="number"&&delete e.maxTimeMS;let r=new Boe(this,e);return Ve(this.s.topology,r,t)};ie.prototype.dropAllIndexes=tn(ie.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead.");ie.prototype.reIndex=tn(function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new koe(this,e);return Ve(this.s.topology,r,t)},"collection.reIndex is deprecated. Use db.command instead.");ie.prototype.listIndexes=function(e){return new moe(this.s.topology,new zoe(this,e),e)};ie.prototype.ensureIndex=tn(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},ou(this.s.topology,goe,[this,e,t,r])},"collection.ensureIndex is deprecated. Use createIndexes instead.");ie.prototype.indexExists=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new Uoe(this,e,t);return Ve(this.s.topology,n,r)};ie.prototype.indexInformation=function(e,t){let r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]=="function"?r.pop():void 0,e=r.length?r.shift()||{}:{};let n=new joe(this.s.db,this.collectionName,e);return Ve(this.s.topology,n,t)};ie.prototype.count=tn(function(e,t,r){let n=Array.prototype.slice.call(arguments,0);return r=typeof n[n.length-1]=="function"?n.pop():void 0,e=n.length?n.shift()||{}:{},t=n.length?n.shift()||{}:{},typeof t=="function"&&(r=t,t={}),t=t||{},Ve(this.s.topology,new IP(this,Object.assign({query:e},t)),r)},"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead");ie.prototype.estimatedDocumentCount=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new IP(this,e);return Ve(this.s.topology,r,t)};ie.prototype.countDocuments=function(e,t,r){let n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]=="function"?n.pop():void 0,e=n.length?n.shift()||{}:{},t=n.length?n.shift()||{}:{};let i=new Toe(this,e,t);return Ve(this.s.topology,i,r)};ie.prototype.distinct=function(e,t,r,n){let i=Array.prototype.slice.call(arguments,1);n=typeof i[i.length-1]=="function"?i.pop():void 0;let a=i.length?i.shift()||{}:{},u=i.length?i.shift()||{}:{},f=new Aoe(this,e,a,u);return Ve(this.s.topology,f,n)};ie.prototype.indexes=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new Loe(this,e);return Ve(this.s.topology,r,t)};ie.prototype.stats=function(e,t){let r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]=="function"?r.pop():void 0,e=r.length?r.shift()||{}:{};let n=new Koe(this,e);return Ve(this.s.topology,n,t)};ie.prototype.findOneAndDelete=function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined),Ve(this.s.topology,new Moe(this,e,t),r)};ie.prototype.findOneAndReplace=qp({name:"collection.findOneAndReplace",deprecatedOptions:["returnOriginal"],optionsIndex:2},function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Ve(this.s.topology,new Doe(this,e,t,r),n)});ie.prototype.findOneAndUpdate=qp({name:"collection.findOneAndUpdate",deprecatedOptions:["returnOriginal"],optionsIndex:2},function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Ve(this.s.topology,new qoe(this,e,t,r),n)});ie.prototype.findAndModify=tn(xP,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.");ie.prototype._findAndModify=xP;function xP(e,t,r,n,i){let a=Array.prototype.slice.call(arguments,1);return i=typeof a[a.length-1]=="function"?a.pop():void 0,t=a.length?a.shift()||[]:[],r=a.length?a.shift():null,n=a.length?a.shift()||{}:{},n=Object.assign({},n),n.readPreference=su.PRIMARY,Ve(this.s.topology,new BP(this,e,t,r,n),i)}s(xP,"_findAndModify");ie.prototype.findAndRemove=tn(function(e,t,r,n){let i=Array.prototype.slice.call(arguments,1);return n=typeof i[i.length-1]=="function"?i.pop():void 0,t=i.length?i.shift()||[]:[],r=i.length?i.shift()||{}:{},r.remove=!0,Ve(this.s.topology,new BP(this,e,t,null,r),n)},"collection.findAndRemove is deprecated. Use findOneAndDelete instead.");ie.prototype.aggregate=function(e,t,r){if(Array.isArray(e))typeof t=="function"&&(r=t,t={}),t==null&&r==null&&(t={});else{let i=Array.prototype.slice.call(arguments,0);r=i.pop();let a=i[i.length-1];t=a&&(a.readPreference||a.explain||a.cursor||a.out||a.maxTimeMS||a.hint||a.allowDiskUse)?i.pop():{},e=i}let n=new poe(this.s.topology,new Ooe(this,e,t),t);if(typeof r=="function"){r(null,n);return}return n};ie.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new foe(this,e,t)};ie.prototype.parallelCollectionScan=tn(function(e,t){return typeof e=="function"&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,e=Object.assign({},e),e.readPreference=su.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),ou(this.s.topology,Soe,[this,e,t],{skipSessions:!0})},"parallelCollectionScan is deprecated in MongoDB v4.1");ie.prototype.geoHaystackSearch=tn(function(e,t,r,n){let i=Array.prototype.slice.call(arguments,2);n=typeof i[i.length-1]=="function"?i.pop():void 0,r=i.length?i.shift()||{}:{};let a=new Poe(this,e,t,r);return Ve(this.s.topology,a,n)},"geoHaystackSearch is deprecated, and will be removed in a future version.");ie.prototype.group=tn(function(e,t,r,n,i,a,u,f){let l=Array.prototype.slice.call(arguments,3);return f=typeof l[l.length-1]=="function"?l.pop():void 0,n=l.length?l.shift():null,i=l.length?l.shift():null,a=l.length?l.shift():null,u=l.length?l.shift()||{}:{},typeof i!="function"&&(a=i,i=null),!Array.isArray(e)&&e instanceof Object&&typeof e!="function"&&e._bsontype!=="Code"&&(e=Object.keys(e)),typeof n=="function"&&(n=n.toString()),typeof i=="function"&&(i=i.toString()),a=a??!0,ou(this.s.topology,yoe,[this,e,t,r,n,i,a,u,f])},"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.");ie.prototype.mapReduce=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={}),r.out==null)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");typeof e=="function"&&(e=e.toString()),typeof t=="function"&&(t=t.toString()),typeof r.finalize=="function"&&(r.finalize=r.finalize.toString());let i=new Hoe(this,e,t,r);return Ve(this.s.topology,i,n)};ie.prototype.initializeUnorderedBulkOp=function(e){return e=e||{},e.ignoreUndefined==null&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,uoe(this.s.topology,this,e)};ie.prototype.initializeOrderedBulkOp=function(e){return e=e||{},e.ignoreUndefined==null&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,coe(this.s.topology,this,e)};ie.prototype.getLogger=function(){return this.s.db.s.logger};MP.exports=ie});var Ip=E((k_e,zP)=>{"use strict";var Qoe=sd(),eae=require("events"),tae=sf().isResumableError,Sf=G().MongoError,rae=ri(),nae=ce().relayEvents,CE=ce().maxWireVersion,AE=x().maybePromise,DP=x().now,iae=x().calculateDurationInMs,sae=uf(),yf=Symbol("resumeQueue"),UP=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],jP=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(UP),Pp={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")},xE=class xE extends eae{constructor(t,r,n){super();let i=tu(),a=gf(),u=au();if(this.pipeline=r||[],this.options=n||{},this.parent=t,this.namespace=t.s.namespace,t instanceof i)this.type=Pp.COLLECTION,this.topology=t.s.db.serverConfig;else if(t instanceof a)this.type=Pp.DATABASE,this.topology=t.serverConfig;else if(t instanceof u)this.type=Pp.CLUSTER,this.topology=t.topology;else throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.promiseLibrary=t.s.promiseLibrary,!this.options.readPreference&&t.s.readPreference&&(this.options.readPreference=t.s.readPreference),this[yf]=new Qoe,this.cursor=WP(this,n),this.closed=!1,this.on("newListener",f=>{f==="change"&&this.cursor&&this.listenerCount("change")===0&&this.cursor.on("data",l=>RE(this,l))}),this.on("removeListener",f=>{f==="change"&&this.listenerCount("change")===0&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(t){return AE(this.parent,t,r=>{PP(this,(n,i)=>{if(n)return r(n);i.hasNext(r)})})}next(t){return AE(this.parent,t,r=>{PP(this,(n,i)=>{if(n)return r(n);i.next((a,u)=>{if(a){this[yf].push(()=>this.next(r)),$P(this,a,r);return}RE(this,u,r)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(t){return AE(this.parent,t,r=>{if(this.closed||(this.closed=!0,!this.cursor))return r();let n=this.cursor;return n.close(i=>(["data","close","end","error"].forEach(a=>n.removeAllListeners(a)),this.cursor=void 0,r(i)))})}pipe(t,r){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(t),this.cursor.pipe(t,r)}unpipe(t){return this.pipeDestinations&&this.pipeDestinations.indexOf(t)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(t),1),this.cursor.unpipe(t)}stream(t){return this.streamOptions=t,this.cursor.stream(t)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}};s(xE,"ChangeStream");var IE=xE,ME=class ME extends rae{constructor(t,r,n){super(t,r,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(t){this._resumeToken=t,this.emit("resumeTokenChanged",t)}get resumeToken(){return this._resumeToken}get resumeOptions(){let t={};for(let r of jP)this.options[r]&&(t[r]=this.options[r]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(r=>delete t[r]),this.resumeToken){let r=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";t[r]=this.resumeToken}else this.startAtOperationTime&&CE(this.server)>=7&&(t.startAtOperationTime=this.startAtOperationTime);return t}cacheResumeToken(t){this.bufferedCount()===0&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=t,this.hasReceived=!0}_processBatch(t,r){let n=r.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,n[t].length===0&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(t){super._initializeCursor((r,n)=>{if(r||n==null){t(r,n);return}let i=n.documents[0];this.startAtOperationTime==null&&this.resumeAfter==null&&this.startAfter==null&&CE(this.server)>=7&&(this.startAtOperationTime=i.operationTime),this._processBatch("firstBatch",i),this.emit("init",n),this.emit("response"),t(r,n)})}_getMore(t){super._getMore((r,n)=>{if(r){t(r);return}this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),t(r,n)})}};s(ME,"ChangeStreamCursor");var BE=ME;function WP(e,t){let r={fullDocument:t.fullDocument||"default"};qP(r,t,UP),e.type===Pp.CLUSTER&&(r.allChangesForCluster=!0);let n=[{$changeStream:r}].concat(e.pipeline),i=qP({},t,jP),a=new BE(e.topology,new sae(e.parent,n,t),i);if(nae(a,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&a.on("data",function(u){RE(e,u)}),a.on("error",function(u){$P(e,u)}),e.pipeDestinations){let u=a.stream(e.streamOptions);for(let f of e.pipeDestinations)u.pipe(f)}return a}s(WP,"createChangeStreamCursor");function qP(e,t,r){return r.forEach(n=>{t[n]&&(e[n]=t[n])}),e}s(qP,"applyKnownOptions");var oae=3e4;function FP(e,t,r){setTimeout(()=>{t&&t.start==null&&(t.start=DP());let n=t.start||DP(),i=t.timeout||oae,a=t.readPreference;if(e.isConnected({readPreference:a}))return r();if(iae(n)>i)return r(new Sf("Timed out waiting for connection"));FP(e,t,r)},500)}s(FP,"waitForTopologyConnected");function RE(e,t,r){let n=e.cursor;if(t==null&&(e.closed=!0),e.closed){r&&r(new Sf("ChangeStream is closed"));return}if(t&&!t._id){let i=new Error("A change stream document has been received that lacks a resume token (_id).");return r?r(i):e.emit("error",i)}return n.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,r?r(void 0,t):e.emit("change",t)}s(RE,"processNewChange");function $P(e,t,r){let n=e.topology,i=e.cursor;if(e.closed){r&&r(new Sf("ChangeStream is closed"));return}function a(f){e.cursor=f,LP(e)}s(a,"resumeWithCursor");function u(f){r||(e.emit("error",f),e.emit("close")),LP(e,f),e.closed=!0}if(s(u,"unresumableError"),i&&tae(t,CE(i.server))){e.cursor=void 0,["data","close","end","error"].forEach(f=>i.removeAllListeners(f)),i.close(),FP(n,{readPreference:i.options.readPreference},f=>{if(f)return u(f);let l=WP(e,i.resumeOptions);if(!r)return a(l);l.hasNext(h=>{if(h)return u(h);a(l)})});return}return r?r(t):e.emit("error",t)}s($P,"processError");function PP(e,t){if(e.isClosed()){t(new Sf("ChangeStream is closed."));return}if(e.cursor){t(void 0,e.cursor);return}e[yf].push(t)}s(PP,"getCursor");function LP(e,t){for(;e[yf].length;){let r=e[yf].pop();if(e.isClosed()&&!t){r(new Sf("Change Stream is not open."));return}r(t,e.cursor)}}s(LP,"processResumeQueue");zP.exports=IE});var Us=E(Lp=>{"use strict";var aae=require("events"),Mo=G().MongoError,_f=require("util").format,DE=G().ReadPreference,uae=G().Sessions.ClientSession,uu=s(function(e,t){var r=this,n=[];t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:n,storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return r.s.storedOps.length}})},"Store");uu.prototype.add=function(e,t,r,n,i){if(this.s.storeOptions.force)return i(Mo.create({message:"db closed by application",driver:!0}));if(this.s.storeOptions.bufferMaxEntries===0)return i(Mo.create({message:_f("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){for(;this.s.storedOps.length>0;){var a=this.s.storedOps.shift();a.c(Mo.create({message:_f("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}return}this.s.storedOps.push({t:e,n:t,o:r,op:n,c:i})};uu.prototype.addObjectAndMethod=function(e,t,r,n,i){if(this.s.storeOptions.force)return i(Mo.create({message:"db closed by application",driver:!0}));if(this.s.storeOptions.bufferMaxEntries===0)return i(Mo.create({message:_f("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){for(;this.s.storedOps.length>0;){var a=this.s.storedOps.shift();a.c(Mo.create({message:_f("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}return}this.s.storedOps.push({t:e,m:r,o:t,p:n,c:i})};uu.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||Mo.create({message:_f("no connection available for operation"),driver:!0}))};var HP=["primary","primaryPreferred","nearest","secondaryPreferred"],VP=["secondary","secondaryPreferred"];uu.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var r=typeof e.executePrimary=="boolean"?e.executePrimary:!0,n=typeof e.executeSecondary=="boolean"?e.executeSecondary:!0;t.length>0;){var i=t.shift();i.t==="cursor"?(r&&n||r&&i.o.options&&i.o.options.readPreference&&HP.indexOf(i.o.options.readPreference.mode)!==-1||!r&&n&&i.o.options&&i.o.options.readPreference&&VP.indexOf(i.o.options.readPreference.mode)!==-1)&&i.o[i.m].apply(i.o,i.p):i.t==="auth"?this.s.topology[i.t].apply(this.s.topology,i.o):r&&n?this.s.topology[i.t](i.n,i.o,i.op,i.c):r&&i.op&&i.op.readPreference&&HP.indexOf(i.op.readPreference.mode)!==-1?this.s.topology[i.t](i.n,i.o,i.op,i.c):!r&&n&&i.op&&i.op.readPreference&&VP.indexOf(i.op.readPreference.mode)!==-1&&this.s.topology[i.t](i.n,i.o,i.op,i.c)}};uu.prototype.all=function(){return this.s.storedOps};var YP=s(function(e){var t=s(function(p,g,w){Object.defineProperty(p,g,{enumerable:!0,get:function(){return w}})},"setup_get_property"),r=!1,n=!1,i=!1,a=!1,u=!1,f=!1,l=e.maxWriteBatchSize||1e3,h=!1,m=!1;e.minWireVersion>=0&&(i=!0),e.maxWireVersion>=1&&(r=!0,a=!0),e.maxWireVersion>=2&&(n=!0),e.maxWireVersion>=3&&(u=!0,f=!0),e.maxWireVersion>=5&&(h=!0,m=!0),e.minWireVersion==null&&(e.minWireVersion=0),e.maxWireVersion==null&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",r),t(this,"hasWriteCommands",n),t(this,"hasTextSearch",i),t(this,"hasAuthCommands",a),t(this,"hasListCollectionsCommand",u),t(this,"hasListIndexesCommand",f),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",l),t(this,"commandsTakeWriteConcern",h),t(this,"commandsTakeCollation",m)},"ServerCapabilities"),qE=class qE extends aae{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return this.logicalSessionTimeoutMinutes!=null}startSession(t,r){let n=new uae(this,this.s.sessionPool,t,r);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(t,r){return this.s.coreTopology.endSessions(t,r)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:this.s.coreTopology.lastIsMaster()==null?null:(this.s.sCapabilities=new YP(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(t,r,n,i){this.s.coreTopology.command(t.toString(),r,DE.translate(n),i)}insert(t,r,n,i){this.s.coreTopology.insert(t.toString(),r,n,i)}update(t,r,n,i){this.s.coreTopology.update(t.toString(),r,n,i)}remove(t,r,n,i){this.s.coreTopology.remove(t.toString(),r,n,i)}isConnected(t){return t=t||{},t=DE.translate(t),this.s.coreTopology.isConnected(t)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(t,r,n){return n=n||{},n=DE.translate(n),n.disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(t,r,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(t,r,n){return this.s.coreTopology.selectServer(t,r,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(t,r){this.s.sessions.forEach(n=>n.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),t===!0&&(this.s.storeOptions.force=t,this.s.store.flush()),this.s.coreTopology.destroy({force:typeof t=="boolean"?t:!1},r)}};s(qE,"TopologyBase");var Do=qE;Object.defineProperty(Do.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}});Object.defineProperty(Do.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}});Object.defineProperty(Do.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}});Object.defineProperty(Do.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}});Lp.Store=uu;Lp.ServerCapabilities=YP;Lp.TopologyBase=Do});var UE=E((J_e,GP)=>{"use strict";var cae=G().Topology,fae=Us().ServerCapabilities,lae=ri(),kP=x().translateOptions,LE=class LE extends cae{constructor(t,r){r=r||{};let n=Object.assign({},{cursorFactory:lae,reconnect:!1,emitError:typeof r.emitError=="boolean"?r.emitError:!0,maxPoolSize:typeof r.maxPoolSize=="number"?r.maxPoolSize:typeof r.poolSize=="number"?r.poolSize:10,minPoolSize:typeof r.minPoolSize=="number"?r.minPoolSize:typeof r.minSize=="number"?r.minSize:0,monitorCommands:typeof r.monitorCommands=="boolean"?r.monitorCommands:!1});n=kP(n,r);var i=r.socketOptions&&Object.keys(r.socketOptions).length>0?r.socketOptions:r;n=kP(n,i),n.serverApi=r.serverApi,n.useUnifiedTopology=r.useUnifiedTopology,super(t,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:this.lastIsMaster()==null?null:(this.s.sCapabilities=new fae(this.lastIsMaster()),this.s.sCapabilities)}command(t,r,n,i){super.command(t.toString(),r,n,i)}insert(t,r,n,i){super.insert(t.toString(),r,n,i)}update(t,r,n,i){super.update(t.toString(),r,n,i)}remove(t,r,n,i){super.remove(t.toString(),r,n,i)}};s(LE,"NativeTopology");var PE=LE;GP.exports=PE});var wf=E((Q_e,XP)=>{"use strict";var hae=G().Server,dae=ri(),pae=Us().TopologyBase,mae=Us().Store,gae=G().MongoError,yae=x().MAX_JS_INT,KP=x().translateOptions,Sae=x().filterOptions,_ae=x().mergeOptions,wae=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","compression","promiseLibrary","monitorCommands"],jE=class jE extends pae{constructor(t,r,n){super();var i=this;n=Sae(n,wae);let a=n.promiseLibrary;var u={force:!1,bufferMaxEntries:typeof n.bufferMaxEntries=="number"?n.bufferMaxEntries:yae},f=n.store||new mae(i,u);if(t.indexOf("/")!==-1)r!=null&&typeof r=="object"&&(n=r,r=null);else if(r==null)throw gae.create({message:"port must be specified",driver:!0});var l=typeof n.auto_reconnect=="boolean"?n.auto_reconnect:!0;l=typeof n.autoReconnect=="boolean"?n.autoReconnect:l;var h=_ae({},{host:t,port:r,disconnectHandler:f,cursorFactory:dae,reconnect:l,emitError:typeof n.emitError=="boolean"?n.emitError:!0,size:typeof n.poolSize=="number"?n.poolSize:5,monitorCommands:typeof n.monitorCommands=="boolean"?n.monitorCommands:!1});h=KP(h,n);var m=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;h=KP(h,m),this.s={coreTopology:new hae(h),sCapabilities:null,clonedOptions:h,reconnect:h.reconnect,emitError:h.emitError,poolSize:h.size,storeOptions:u,store:f,host:t,port:r,options:n,sessionPool:null,sessions:new Set,promiseLibrary:a||Promise}}connect(t,r){var n=this;typeof t=="function"&&(r=t,t={}),t==null&&(t=this.s.clonedOptions),typeof r!="function"&&(r=null),t=Object.assign({},this.s.clonedOptions,t),n.s.options=t,n.s.storeOptions.bufferMaxEntries=typeof t.bufferMaxEntries=="number"?t.bufferMaxEntries:-1;var i=s(function(){return function(g){var w=["timeout","error","close"];w.forEach(function(O){n.s.coreTopology.removeListener(O,p[O])}),n.s.coreTopology.removeListener("connect",i);try{r(g)}catch(O){process.nextTick(function(){throw O})}}},"connectErrorHandler"),a=s(function(g){return function(w){g!=="error"&&n.emit(g,w)}},"errorHandler"),u=s(function(){n.emit("reconnect",n),n.s.store.execute()},"reconnectHandler"),f=s(function(g){n.emit("reconnectFailed",g),n.s.store.flush(g)},"reconnectFailedHandler"),l=s(function(){n.s.store.flush()},"destroyHandler"),h=s(function(g){return function(w,O){n.emit(g,w,O)}},"relay"),m=s(function(){["timeout","error","close","destroy"].forEach(function(g){n.s.coreTopology.removeAllListeners(g)}),n.s.coreTopology.on("timeout",a("timeout")),n.s.coreTopology.once("error",a("error")),n.s.coreTopology.on("close",a("close")),n.s.coreTopology.on("destroy",l),n.emit("open",null,n);try{r(null,n)}catch(g){process.nextTick(function(){throw g})}},"connectHandler"),p={timeout:i("timeout"),error:i("error"),close:i("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach(function(g){n.s.coreTopology.removeAllListeners(g)}),n.s.coreTopology.once("timeout",p.timeout),n.s.coreTopology.once("error",p.error),n.s.coreTopology.once("close",p.close),n.s.coreTopology.once("connect",m),n.s.coreTopology.on("reconnect",u),n.s.coreTopology.on("reconnectFailed",f),n.s.coreTopology.on("serverDescriptionChanged",h("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",h("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",h("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",h("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",h("serverOpening")),n.s.coreTopology.on("serverClosed",h("serverClosed")),n.s.coreTopology.on("topologyOpening",h("topologyOpening")),n.s.coreTopology.on("topologyClosed",h("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",h("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",h("commandStarted")),n.s.coreTopology.on("commandSucceeded",h("commandSucceeded")),n.s.coreTopology.on("commandFailed",h("commandFailed")),n.s.coreTopology.on("attemptReconnect",h("attemptReconnect")),n.s.coreTopology.on("monitoring",h("monitoring")),n.s.coreTopology.connect(t)}};s(jE,"Server");var qo=jE;Object.defineProperty(qo.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}});Object.defineProperty(qo.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}});Object.defineProperty(qo.prototype,"host",{enumerable:!0,get:function(){return this.s.host}});Object.defineProperty(qo.prototype,"port",{enumerable:!0,get:function(){return this.s.port}});XP.exports=qo});var FE=E((twe,ZP)=>{"use strict";var vae=Us().TopologyBase,Oae=G().MongoError,Eae=G().Mongos,Tae=ri(),Nae=wf(),bae=Us().Store,Aae=x().MAX_JS_INT,JP=x().translateOptions,Cae=x().filterOptions,Iae=x().mergeOptions,Bae=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","promiseLibrary","monitorCommands"],WE=class WE extends vae{constructor(t,r){super(),r=r||{};var n=this;r=Cae(r,Bae);for(var i=0;i0?r.socketOptions:r;h=JP(h,m),this.s={coreTopology:new Eae(f,h),sCapabilities:null,debug:h.debug,storeOptions:a,clonedOptions:h,store:u,options:r,sessionPool:null,sessions:new Set,promiseLibrary:r.promiseLibrary||Promise}}connect(t,r){var n=this;typeof t=="function"&&(r=t,t={}),t==null&&(t={}),typeof r!="function"&&(r=null),t=Object.assign({},this.s.clonedOptions,t),n.s.options=t,n.s.storeOptions.bufferMaxEntries=typeof t.bufferMaxEntries=="number"?t.bufferMaxEntries:-1;var i=s(function(){return function(m){var p=["timeout","error","close"];p.forEach(function(g){n.removeListener(g,i)}),n.s.coreTopology.removeListener("connect",i),n.close(!0);try{r(m)}catch(g){process.nextTick(function(){throw g})}}},"connectErrorHandler"),a=s(function(m){return function(p){m!=="error"&&n.emit(m,p)}},"errorHandler"),u=s(function(){n.emit("reconnect"),n.s.store.execute()},"reconnectHandler"),f=s(function(m){return function(p,g){n.emit(m,p,g)}},"relay"),l=s(function(){var m=["timeout","error","close","fullsetup"];m.forEach(function(p){n.s.coreTopology.removeAllListeners(p)}),n.s.coreTopology.on("timeout",a("timeout")),n.s.coreTopology.on("error",a("error")),n.s.coreTopology.on("close",a("close")),n.s.coreTopology.on("fullsetup",function(){n.emit("fullsetup",n)}),n.emit("open",null,n);try{r(null,n)}catch(p){process.nextTick(function(){throw p})}},"connectHandler"),h=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"];h.forEach(function(m){n.s.coreTopology.removeAllListeners(m)}),n.s.coreTopology.on("serverDescriptionChanged",f("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",f("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",f("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",f("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",f("serverOpening")),n.s.coreTopology.on("serverClosed",f("serverClosed")),n.s.coreTopology.on("topologyOpening",f("topologyOpening")),n.s.coreTopology.on("topologyClosed",f("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",f("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",f("commandStarted")),n.s.coreTopology.on("commandSucceeded",f("commandSucceeded")),n.s.coreTopology.on("commandFailed",f("commandFailed")),n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.s.coreTopology.once("connect",l),n.s.coreTopology.on("joined",f("joined")),n.s.coreTopology.on("left",f("left")),n.s.coreTopology.on("reconnect",u),n.s.coreTopology.connect(t)}};s(WE,"Mongos");var Up=WE;Object.defineProperty(Up.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}});ZP.exports=Up});var zE=E((nwe,eL)=>{"use strict";var Rae=wf(),xae=ri(),Mae=G().MongoError,Dae=Us().TopologyBase,qae=Us().Store,Pae=G().ReplSet,Lae=x().MAX_JS_INT,QP=x().translateOptions,Uae=x().filterOptions,jae=x().mergeOptions,Wae=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"],$E=class $E extends Dae{constructor(t,r){super(),r=r||{};var n=this;r=Uae(r,Wae);for(var i=0;i0?r.socketOptions:r;l=QP(l,h);var m=new Pae(f,l);m.on("reconnect",function(){n.emit("reconnect"),u.execute()}),this.s={coreTopology:m,sCapabilities:null,tag:r.tag,storeOptions:a,clonedOptions:l,store:u,options:r,sessionPool:null,sessions:new Set,promiseLibrary:r.promiseLibrary||Promise},l.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return m}})}connect(t,r){var n=this;typeof t=="function"&&(r=t,t={}),t==null&&(t={}),typeof r!="function"&&(r=null),t=Object.assign({},this.s.clonedOptions,t),n.s.options=t,n.s.storeOptions.bufferMaxEntries=typeof t.bufferMaxEntries=="number"?t.bufferMaxEntries:-1;var i=s(function(p){return function(g){p!=="error"&&n.emit(p,g)}},"errorHandler"),a=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"];a.forEach(function(p){n.s.coreTopology.removeAllListeners(p)});var u=s(function(p){return function(g,w){n.emit(p,g,w)}},"relay"),f=s(function(p){return function(g,w){n.emit(p,g,w.lastIsMaster(),w)}},"replsetRelay"),l=s(function(p,g){n.emit("ha",p,g),p==="start"?n.emit("ha_connect",p,g):p==="end"&&n.emit("ha_ismaster",p,g)},"relayHa");n.s.coreTopology.on("joined",f("joined")),n.s.coreTopology.on("left",u("left")),n.s.coreTopology.on("ping",u("ping")),n.s.coreTopology.on("ha",l),n.s.coreTopology.on("serverDescriptionChanged",u("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",u("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",u("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",u("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",u("serverOpening")),n.s.coreTopology.on("serverClosed",u("serverClosed")),n.s.coreTopology.on("topologyOpening",u("topologyOpening")),n.s.coreTopology.on("topologyClosed",u("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",u("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",u("commandStarted")),n.s.coreTopology.on("commandSucceeded",u("commandSucceeded")),n.s.coreTopology.on("commandFailed",u("commandFailed")),n.s.coreTopology.on("fullsetup",function(){n.emit("fullsetup",n,n)}),n.s.coreTopology.on("all",function(){n.emit("all",null,n)});var h=s(function(){n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.emit("open",null,n);try{r(null,n)}catch(p){process.nextTick(function(){throw p})}},"connectHandler"),m=s(function(){return function(p){["timeout","error","close"].forEach(function(g){n.s.coreTopology.removeListener(g,m)}),n.s.coreTopology.removeListener("connect",m),n.s.coreTopology.destroy();try{r(p)}catch(g){n.s.coreTopology.isConnected()||process.nextTick(function(){throw g})}}},"connectErrorHandler");n.s.coreTopology.once("timeout",m("timeout")),n.s.coreTopology.once("error",m("error")),n.s.coreTopology.once("close",m("close")),n.s.coreTopology.once("connect",h),n.s.coreTopology.connect(t)}close(t,r){["timeout","error","close","joined","left"].forEach(n=>this.removeAllListeners(n)),super.close(t,r)}};s($E,"ReplSet");var jp=$E;Object.defineProperty(jp.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}});eL.exports=jp});var iL=E((swe,nL)=>{"use strict";var Fae=G().ReadPreference,HE=require("url"),$ae=require("util").format,zae=G().Logger,tL=require("dns"),Hae=ho(),Vae=require("querystring"),Wp=X().MongoParseError;nL.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n;try{n=HE.parse(e,!0)}catch{return r(new Error("URL malformed, cannot be parsed"))}if(n.protocol!=="mongodb:"&&n.protocol!=="mongodb+srv:")return r(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if(n.protocol==="mongodb:")return rL(e,t,r);if(n.hostname.split(".").length<3)return r(new Error("URI does not have hostname, domain name and tld"));if(n.domainLength=n.hostname.split(".").length,e.substring(14).split("/")[0].match(","))return r(new Error("Invalid URI, cannot contain multiple hostnames"));if(n.port)return r(new Error("Ports not accepted with `mongodb+srv` URIs"));let a=`_mongodb._tcp.${n.host}`;tL.resolveSrv(a,function(u,f){if(u)return r(u);if(f.length===0)return r(new Error("No addresses found at host"));for(let g=0;g1)return r(new Wp("Multiple text records not allowed"));w=w[0].join("");let O=Vae.parse(w),N=Object.keys(O);if(Object.keys(N).some(A=>A.toLowerCase()==="loadbalanced"))return r(new Wp("Load balancer mode requires driver version 4+"));if(N.some(A=>A!=="authSource"&&A!=="replicaSet"))return r(new Wp("Text record must only set `authSource` or `replicaSet`"));N.length>0&&p.push(w)}p.length&&(m+=`?${p.join("&")}`),rL(m,t,r)})})};function Yae(e,t){let r=/^.*?\./,n=`.${e.replace(r,"")}`,i=`.${t.replace(r,"")}`;return!!n.endsWith(i)}s(Yae,"matchesParentDomain");function rL(e,t,r){let n,i;try{n=kae(e,t)}catch(a){i=a}return i?r(i,null):r(null,n)}s(rL,"parseHandler");function kae(e,t){let r="",n="",i="",a="admin",u=HE.parse(e,!0);if((u.hostname==null||u.hostname==="")&&e.indexOf(".sock")===-1)throw new Error("No hostname or hostnames provided in connection string");if(u.port==="0")throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(u.port,10))&&parseInt(u.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(u.path&&u.path.length>0&&u.path[0]!=="/"&&e.indexOf(".sock")===-1)throw new Error("Missing delimiting slash between hosts and options");if(u.query)for(let W in u.query){if(W.indexOf("::")!==-1)throw new Error("Double colon in host identifier");if(u.query[W]==="")throw new Error("Query parameter "+W+" is an incomplete value pair")}if(u.auth){let W=u.auth.split(":");if(e.indexOf(u.auth)!==-1&&W.length>2)throw new Error("Username with password containing an unescaped colon");if(e.indexOf(u.auth)!==-1&&u.auth.indexOf("@")!==-1)throw new Error("Username containing an unescaped at-sign")}let l=e.split("?").shift().split(","),h=[];for(let W=0;W1&&ee.path.indexOf("::")===-1?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}if(e.indexOf("?")!==-1?(i=e.substr(e.indexOf("?")+1),r=e.substring(10,e.indexOf("?"))):r=e.substring(10),r.indexOf("@")!==-1&&(n=r.split("@")[0],r=r.split("@")[1]),r.split("/").length>2)throw new Error("Unsupported host '"+r.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(r.indexOf(".sock")!==-1){if(r.indexOf(".sock/")!==-1){if(a=r.split(".sock/")[1],a.indexOf("/")!==-1)throw a.split("/").length===2&&a.split("/")[1].length===0?new Error("Illegal trailing backslash after database name"):new Error("More than 1 database name in URL");r=r.split("/",r.indexOf(".sock")+5)}}else if(r.indexOf("/")!==-1){if(r.split("/").length>2)throw r.split("/")[2].length===0?new Error("Illegal trailing backslash after database name"):new Error("More than 1 database name in URL");a=r.split("/")[1],r=r.split("/")[0]}r=decodeURIComponent(r);let m={},p=n||"",g=p.split(":",2),w=decodeURIComponent(g[0]);if(g[0]!==encodeURIComponent(w))throw new Error("Username contains an illegal unescaped character");if(g[0]=w,g[1]){let W=decodeURIComponent(g[1]);if(g[1]!==encodeURIComponent(W))throw new Error("Password contains an illegal unescaped character");g[1]=W}g.length===2&&(m.auth={user:g[0],password:g[1]}),t&&t.auth!=null&&(m.auth=t.auth);let O,N,A,M,L={socketOptions:{}},I={read_preference_tags:[]},R={socketOptions:{}},Y={socketOptions:{}};if(m.server_options=L,m.db_options=I,m.rs_options=R,m.mongos_options=Y,e.match(/\.sock/)){let W=e.substring(e.indexOf("mongodb://")+10,e.lastIndexOf(".sock")+5);W.indexOf("@")!==-1&&(W=W.split("@")[1]),W=decodeURIComponent(W),A=[{domain_socket:W}]}else{O=r;let W={};A=O.split(",").map(function(ee){let Ee,V,fe;if(fe=/\[([^\]]+)\](?::(.+))?/.exec(ee))Ee=fe[1],V=parseInt(fe[2],10)||27017;else{let ne=ee.split(":",2);Ee=ne[0]||"localhost",V=ne[1]!=null?parseInt(ne[1],10):27017,Ee.indexOf("?")!==-1&&(Ee=Ee.split(/\?/)[0])}return W[Ee+"_"+V]?null:(W[Ee+"_"+V]=1,{host:Ee,port:V})}).filter(function(ee){return ee!=null})}if(m.dbName=a||"admin",N=(i||"").split(/[&;]/),N.some(W=>W.toLowerCase()==="loadbalanced"))throw new Wp("Load balancer mode requires driver version 4+");if(N.forEach(function(W){if(W){var ee=W.split("="),Ee=ee[0],V=ee[1];switch(Ee){case"slaveOk":case"slave_ok":L.slave_ok=V==="true",I.slaveOk=V==="true";break;case"maxPoolSize":case"poolSize":L.poolSize=parseInt(V,10),R.poolSize=parseInt(V,10);break;case"appname":m.appname=decodeURIComponent(V);break;case"autoReconnect":case"auto_reconnect":L.auto_reconnect=V==="true";break;case"ssl":if(V==="prefer"){L.ssl=V,R.ssl=V,Y.ssl=V;break}L.ssl=V==="true",R.ssl=V==="true",Y.ssl=V==="true";break;case"sslValidate":L.sslValidate=V==="true",R.sslValidate=V==="true",Y.sslValidate=V==="true";break;case"replicaSet":case"rs_name":R.rs_name=V;break;case"reconnectWait":R.reconnectWait=parseInt(V,10);break;case"retries":R.retries=parseInt(V,10);break;case"readSecondary":case"read_secondary":R.read_secondary=V==="true";break;case"fsync":I.fsync=V==="true";break;case"journal":I.j=V==="true";break;case"safe":I.safe=V==="true";break;case"nativeParser":case"native_parser":I.native_parser=V==="true";break;case"readConcernLevel":I.readConcern=new Hae(V);break;case"connectTimeoutMS":L.socketOptions.connectTimeoutMS=parseInt(V,10),R.socketOptions.connectTimeoutMS=parseInt(V,10),Y.socketOptions.connectTimeoutMS=parseInt(V,10);break;case"socketTimeoutMS":L.socketOptions.socketTimeoutMS=parseInt(V,10),R.socketOptions.socketTimeoutMS=parseInt(V,10),Y.socketOptions.socketTimeoutMS=parseInt(V,10);break;case"w":I.w=parseInt(V,10),isNaN(I.w)&&(I.w=V);break;case"authSource":I.authSource=V;break;case"gssapiServiceName":I.gssapiServiceName=V;break;case"authMechanism":if(V==="GSSAPI")if(m.auth==null){let fe=decodeURIComponent(p);if(fe.indexOf("@")===-1)throw new Error("GSSAPI requires a provided principal");m.auth={user:fe,password:null}}else m.auth.user=decodeURIComponent(m.auth.user);else V==="MONGODB-X509"&&(m.auth={user:decodeURIComponent(p)});if(V!=="GSSAPI"&&V!=="MONGODB-X509"&&V!=="MONGODB-CR"&&V!=="DEFAULT"&&V!=="SCRAM-SHA-1"&&V!=="SCRAM-SHA-256"&&V!=="PLAIN")throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");I.authMechanism=V;break;case"authMechanismProperties":{let fe=V.split(","),ne={};fe.forEach(function(J){let K=J.split(":");ne[K[0]]=K[1]}),I.authMechanismProperties=ne,typeof ne.SERVICE_NAME=="string"&&(I.gssapiServiceName=ne.SERVICE_NAME),typeof ne.SERVICE_REALM=="string"&&(I.gssapiServiceRealm=ne.SERVICE_REALM),typeof ne.CANONICALIZE_HOST_NAME=="string"&&(I.gssapiCanonicalizeHostName=ne.CANONICALIZE_HOST_NAME==="true")}break;case"wtimeoutMS":I.wtimeout=parseInt(V,10);break;case"readPreference":if(!Fae.isValid(V))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");I.readPreference=V;break;case"maxStalenessSeconds":I.maxStalenessSeconds=parseInt(V,10);break;case"readPreferenceTags":{V=decodeURIComponent(V);let fe={};if(V==null||V===""){I.read_preference_tags.push(fe);break}let ne=V.split(/,/);for(let J=0;J9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");M.zlibCompressionLevel=fe,L.compression=M}break;case"retryWrites":I.retryWrites=V==="true";break;case"minSize":I.minSize=parseInt(V,10);break;default:zae("URL Parser").warn(`${Ee} is not supported as a connection string option`);break}}}),I.read_preference_tags.length===0&&(I.read_preference_tags=null),(I.w===-1||I.w===0)&&(I.journal===!0||I.fsync===!0||I.safe===!0))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");return I.readPreference||(I.readPreference="primary"),I=Object.assign(I,t),m.servers=A,m}s(kae,"parseConnectionString")});var YE=E((awe,oL)=>{"use strict";var Gae=au(),Ar=jt().retrieveBSON(),sL=X().MongoError,Fp;try{Fp=require("mongodb-client-encryption")}catch{throw new sL("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project")}if(Fp===void 0||typeof Fp.extension!="function")throw new sL("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`");var Kae=Fp.extension(kE()).AutoEncrypter,Wi=Symbol("internalClient"),$p=class $p{constructor(t,r){this.bypassAutoEncryption=!!r.autoEncryption.bypassAutoEncryption,this.needsConnecting=!1,r.maxPoolSize===0&&r.autoEncryption.keyVaultClient==null?r.autoEncryption.keyVaultClient=t:r.autoEncryption.keyVaultClient==null&&(r.autoEncryption.keyVaultClient=this.getInternalClient(t)),this.bypassAutoEncryption?r.autoEncryption.metadataClient=void 0:r.maxPoolSize===0?r.autoEncryption.metadataClient=t:r.autoEncryption.metadataClient=this.getInternalClient(t),r.autoEncryption.bson=$p.makeBSON(r),this.autoEncrypter=new Kae(t,r.autoEncryption)}getInternalClient(t){if(!this[Wi]){let r={};for(let i of Object.keys(t.s.options))["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(i)===-1&&(r[i]=t.s.options[i]);r.minPoolSize=0;let n=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[Wi]=new Gae(t.s.url,r);for(let i of n)for(let a of t.listeners(i))this[Wi].on(i,a);t.on("newListener",(i,a)=>{this[Wi].on(i,a)}),this.needsConnecting=!0}return this[Wi]}connectInternalClient(t){return this.needsConnecting?(this.needsConnecting=!1,this[Wi].connect(t)):t()}close(t,r,n){this.autoEncrypter.teardown(i=>{if(this[Wi]&&t!==this[Wi])return this[Wi].close(r,n);n(i)})}static makeBSON(t){return(t||{}).bson||new Ar([Ar.Binary,Ar.Code,Ar.DBRef,Ar.Decimal128,Ar.Double,Ar.Int32,Ar.Long,Ar.Map,Ar.MaxKey,Ar.MinKey,Ar.ObjectId,Ar.BSONRegExp,Ar.Symbol,Ar.Timestamp])}};s($p,"Encrypter");var VE=$p;oL.exports={Encrypter:VE}});var nT=E((cwe,gL)=>{"use strict";var Xae=require("util").deprecate,Jae=G().Logger,Zae=G().MongoCredentials,ZE=G().MongoError,uL=FE(),cL=UE(),Qae=G().parseConnectionString,eue=ho(),QE=G().ReadPreference,fL=zE(),KE=wf(),tue=G().Sessions.ServerSessionPool,rue=x().emitDeprecationWarning,XE=x().emitWarningOnce,nue=require("fs"),lL=wi(),iue=kc().CMAP_EVENT_NAMES,GE;function sue(){return GE||(GE=au()),GE}s(sue,"loadClient");var oue=Xae(iL(),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),aue={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},hL=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],uue=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),JE=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","bsonRegExp","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","serverApi","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],cue=["native_parser"],aL=["server","replset","replSet","mongos","db"];function fue(e){let t=JE.concat(aL);for(let r in e)if(cue.indexOf(r)===-1){if(t.indexOf(r)===-1){if(e.validateOptions)return new ZE(`option ${r} is not supported`);XE(`the options [${r}] is not supported`)}aL.indexOf(r)!==-1&&XE(`the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [${JE}]`)}}s(fue,"validOptions");var lue=JE.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function eT(e,t){t.on("authenticated",Fi(e,"authenticated")),t.on("error",Fi(e,"error")),t.on("timeout",Fi(e,"timeout")),t.on("close",Fi(e,"close")),t.on("parseError",Fi(e,"parseError")),t.once("open",Fi(e,"open")),t.once("fullsetup",Fi(e,"fullsetup")),t.once("all",Fi(e,"all")),t.on("reconnect",Fi(e,"reconnect"))}s(eT,"addListeners");function tT(e,t){e.topology=t,t instanceof cL||(t.s.sessionPool=new tue(t.s.coreTopology))}s(tT,"assignTopology");function hue(e){hL.forEach(t=>e.removeAllListeners(t))}s(hue,"clearAllEvents");function due(e,t){let r=sue(),n=[];return e instanceof r&&hL.forEach(i=>{t.on(i,(a,u)=>{i==="open"?n.push({event:i,object1:e}):n.push({event:i,object1:a,object2:u})})}),n}s(due,"collectEvents");function pue(e){e.tls!=null&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=nue.readFileSync(e[t]))})}s(pue,"resolveTLSOptions");function mue(e,t,r,n){if(r=Object.assign({},r),n==null)throw new Error("no callback function provided");let i=!1,a=Jae("MongoClient",r);if(t instanceof KE||t instanceof fL||t instanceof uL)return gue(e,t,r,h);let u=r.useNewUrlParser!==!1,f=u?Qae:oue,l=u?Oue:wue;f(t,r,(m,p)=>{if(m)return n(m);let g=l(p),w=dL(g,r);if(w.socketTimeoutMS==null&&(w.socketTimeoutMS=0),w.connectTimeoutMS==null&&(w.connectTimeoutMS=1e4),w.retryWrites==null&&(w.retryWrites=!0),w.useRecoveryToken==null&&(w.useRecoveryToken=!0),w.readPreference==null&&(w.readPreference="primary"),w.db_options&&w.db_options.auth&&delete w.db_options.auth,pue(w),e.s.options=w,e.s.readPreference=QE.fromOptions(w),e.s.writeConcern=lL.fromOptions(w),g.servers.length===0)return n(new Error("connection string must contain at least one seed host"));if(w.auth&&!w.credentials)try{i=!0,w.credentials=pL(e,w.auth.user,w.auth.password,w)}catch(O){return n(O)}return w.useUnifiedTopology?zp(e,"unified",w,h):(XE("Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor."),w.replicaSet||w.rs_name?zp(e,"replicaset",w,h):g.servers.length>1?zp(e,"mongos",w,h):yue(e,w,h))});function h(m,p){let g="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(m&&m.message==="no mongos proxies found in seed list")return a.isWarn()&&a.warn(g),n(new ZE(g));i&&e.emit("authenticated",null,!0),n(m,p)}s(h,"connectCallback")}s(mue,"connect");function gue(e,t,r,n){tT(e,t),eT(e,t),rT(e,t);let i=Object.assign({},r);if((typeof r.readPreference=="string"||typeof r.read_preference=="string")&&(i.readPreference=new QE(r.readPreference||r.read_preference)),(i.user||i.password||i.authMechanism)&&!i.credentials)try{i.credentials=pL(e,i.user,i.password,i)}catch(u){return n(u,t)}return t.connect(i,n)}s(gue,"connectWithUrl");function Fi(e,t){let r=new Set(["all","fullsetup","open","reconnect"]);return(n,i)=>{if(r.has(t))return e.emit(t,e);e.emit(t,n,i)}}s(Fi,"createListener");function yue(e,t,r){t.promiseLibrary=e.s.promiseLibrary;let i=mL(t)[0],a=due(e,i);i.connect(t,(u,f)=>{if(u)return i.close(!0),r(u);hue(i),rT(e,i),eT(e,i);let l=f.lastIsMaster();if(tT(e,f),l&&l.msg==="isdbgrid")return f.close(),zp(e,"mongos",t,r);vue(e,a),r(u,f)})}s(yue,"createServer");var Sue=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function _ue(e){e.on("newListener",t=>{Sue.has(t)&&rue(`The \`${t}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}s(_ue,"registerDeprecatedEventNotifiers");function zp(e,t,r,n){r.promiseLibrary=e.s.promiseLibrary;let i={};t==="unified"&&(i.createServers=!1);let a=mL(r,i);if(r.autoEncryption!=null){let f=YE().Encrypter;r.encrypter=new f(e,r),r.autoEncrypter=r.encrypter.autoEncrypter}let u;if(t==="mongos"?u=new uL(a,r):t==="replicaset"?u=new fL(a,r):t==="unified"&&(u=new cL(r.servers,r),_ue(e)),eT(e,u),rT(e,u),tT(e,u),r.autoEncrypter){r.autoEncrypter.init(f=>{if(f){n(f);return}u.connect(r,l=>{if(l){u.close(!0),n(l);return}r.encrypter.connectInternalClient(h=>{if(h)return n(h);n(void 0,u)})})});return}u.connect(r,f=>{if(f)return u.close(!0),n(f);n(void 0,u)})}s(zp,"createTopology");function dL(e,t){let r=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],n=["readconcern","compression","autoencryption"],i=["w","wtimeout","j","journal","fsync","writeconcern"];for(let u in t)i.indexOf(u.toLowerCase())===-1&&(n.indexOf(u.toLowerCase())!==-1?e[u]=t[u]:r.indexOf(u.toLowerCase())!==-1?e=Hp(e,t[u],!1):t[u]&&typeof t[u]=="object"&&!Buffer.isBuffer(t[u])&&!Array.isArray(t[u])?e=Hp(e,t[u],!0):e[u]=t[u]);let a=lL.fromOptions(t);return a&&(e.writeConcern=Object.assign({},e.writeConcern,a)),e}s(dL,"createUnifiedOptions");function pL(e,t,r,n){n=Object.assign({},n);let i=n.authSource||n.authdb||n.dbName,a=n.authMechanism||"DEFAULT",u=a.toUpperCase(),f=n.authMechanismProperties;if(!uue.has(u))throw ZE.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:!0});return new Zae({mechanism:aue[u],mechanismProperties:f,source:i,username:t,password:r})}s(pL,"generateCredentials");function wue(e){return Hp(dL({},e),e,!1)}s(wue,"legacyTransformUrlOptions");function Hp(e,t,r){for(let n in t)t[n]&&typeof t[n]=="object"&&r?e=Hp(e,t[n],r):e[n]=t[n];return e}s(Hp,"mergeOptions");function rT(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(iue).forEach(n=>{t.on(n,(i,a)=>{e.emit(n,i,a)})})}s(rT,"relayEvents");function vue(e,t){for(let r=0;rr.domain_socket?new KE(r.domain_socket,27017,e):new KE(r.host,r.port,e))}s(mL,"translateOptions");gL.exports={validOptions:fue,connect:mue}});var au=E((lwe,vL)=>{"use strict";var Eue=Ip(),Tue=gf(),SL=require("events").EventEmitter,Nue=require("util").inherits,Vp=G().MongoError,iT=G().ValidServerApiVersions,_L=require("util").deprecate,bue=wi(),Aue=x().MongoDBNamespace,yL=Vt(),wL=x().maybePromise,Cue=UE(),Iue=nT().connect,Bue=nT().validOptions;function Xt(e,t){if(t=t||{},!(this instanceof Xt))return new Xt(e,t);if(SL.call(this),t.autoEncryption&&YE(),t.serverApi){let r=typeof t.serverApi=="string"?{version:t.serverApi}:t.serverApi,n=r&&r.version;if(!n)throw new Vp(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${iT.join('", "')}"]`);if(!iT.some(i=>i===n))throw new Vp(`Invalid server API version=${n}; must be in the following enum: ["${iT.join('", "')}"]`);t.serverApi=r}this.s={url:e,options:t,promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:bue.fromOptions(t),readPreference:yL.fromOptions(t)||yL.primary,namespace:new Aue("admin")}}s(Xt,"MongoClient");Nue(Xt,SL);Object.defineProperty(Xt.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}});Object.defineProperty(Xt.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference}});Xt.prototype.connect=function(e){if(typeof e=="string")throw new TypeError("`connect` only accepts a callback");let t=this;return wL(this,e,r=>{let n=Bue(t.s.options);if(n)return r(n);Iue(t,t.s.url,t.s.options,i=>{if(i)return r(i);r(null,t)})})};Xt.prototype.logout=_L(function(e,t){typeof e=="function"&&(t=e,e={}),typeof t=="function"&&t(null,!0)},"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient");Xt.prototype.close=function(e,t){typeof e=="function"&&(t=e,e=!1);let r=this;return wL(this,t,n=>{let i=s(a=>{if(r.emit("close",r),!(r.topology instanceof Cue))for(let u of r.s.dbCache)u[1].emit("close",r);r.removeAllListeners("close"),n(a)},"completeClose");if(r.topology==null){i();return}r.topology.close(e,a=>{let u=r.topology.s.options.encrypter;if(u)return u.close(r,e,f=>{i(a||f)});i(a)})})};Xt.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);let r=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&r.returnNonCachedInstance!==!0)return this.s.dbCache.get(e);if(r.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new Vp("MongoClient must be connected before calling MongoClient.prototype.db");let n=new Tue(e,this.topology,r);return this.s.dbCache.set(e,n),n};Xt.prototype.isConnected=_L(function(e){return e=e||{},this.topology?this.topology.isConnected(e):!1},"isConnected is deprecated and will be removed in the next major version");Xt.connect=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);return r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift():null,t=t||{},new Xt(e,t).connect(r)};Xt.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new Vp("Must connect to a server before calling this method");return this.topology.startSession(e,this.s.options)};Xt.prototype.withSession=function(e,t){typeof e=="function"&&(t=e,e=void 0);let r=this.startSession(e),n=s((i,a,u)=>{if(n=s(()=>{throw new ReferenceError("cleanupHandler was called too many times")},"cleanupHandler"),u=Object.assign({throw:!0},u),r.endSession(),i){if(u.throw)throw i;return Promise.reject(i)}},"cleanupHandler");try{let i=t(r);return Promise.resolve(i).then(a=>n(null,a)).catch(a=>n(a,null,{throw:!0}))}catch(i){return n(i,null,{throw:!1})}};Xt.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new Eue(this,e,t)};Xt.prototype.getLogger=function(){return this.s.options.logger};vL.exports=Xt});var sT=E((dwe,OL)=>{"use strict";var Yp=G().BSON.Binary,Rue=G().BSON.ObjectID,kp=qn().Buffer,Wr=s(function(e,t,r){if(!(this instanceof Wr))return new Wr(e,t);this.file=e;var n=t??{};if(this.writeConcern=r||{w:1},this.objectId=n._id==null?new Rue:n._id,this.chunkNumber=n.n==null?0:n.n,this.data=new Yp,typeof n.data=="string"){var i=kp.alloc(n.data.length);i.write(n.data,0,n.data.length,"binary"),this.data=new Yp(i)}else if(Array.isArray(n.data)){i=kp.alloc(n.data.length);var a=n.data.join("");i.write(a,0,a.length,"binary"),this.data=new Yp(i)}else if(n.data&&n.data._bsontype==="Binary")this.data=n.data;else if(!kp.isBuffer(n.data)&&n.data!=null)throw Error("Illegal chunk format");this.internalPosition=0},"Chunk");Wr.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),t!=null?t(null,this):this};Wr.prototype.read=function(e){if(e=e==null||e===0?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}else return""};Wr.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return this.data.buffer!=null?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=kp.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}else return null};Wr.prototype.eof=function(){return this.internalPosition===this.length()};Wr.prototype.getc=function(){return this.read(1)};Wr.prototype.rewind=function(){this.internalPosition=0,this.data=new Yp};Wr.prototype.save=function(e,t){var r=this;typeof e=="function"&&(t=e,e={}),r.file.chunkCollection(function(n,i){if(n)return t(n);var a={upsert:!0};for(var u in e)a[u]=e[u];for(u in r.writeConcern)a[u]=r.writeConcern[u];r.data.length()>0?r.buildMongoObject(function(f){var l={forceServerObjectId:!0};for(var h in r.writeConcern)l[h]=r.writeConcern[h];i.replaceOne({_id:r.objectId},f,a,function(m){t(m,r)})}):t(null,r)})};Wr.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};this.objectId!=null&&(t._id=this.objectId),e(t)};Wr.prototype.length=function(){return this.data.length()};Object.defineProperty(Wr.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}});Wr.DEFAULT_CHUNK_SIZE=1024*255;OL.exports=Wr});var CL=E((mwe,AL)=>{"use strict";var rn=sT(),aT=G().BSON.ObjectID,uT=G().ReadPreference,Xp=qn().Buffer,Gp=require("fs"),cT=require("util").format,xue=require("util"),$i=G().MongoError,Mue=xue.inherits,bL=require("stream").Duplex,Due=x().shallowClone,fr=x().executeLegacyOperation,que=require("util").deprecate,Pue=0,vf=1,Lue=que(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead"),Me=s(function e(t,r,n,i,a){if(Lue(),!(this instanceof e))return new e(t,r,n,i,a);this.db=t,typeof a>"u"&&(a={}),typeof i>"u"?(i=n,n=void 0):typeof i=="object"&&(a=i,i=n,n=void 0),r&&r._bsontype==="ObjectID"?(this.referenceBy=vf,this.fileId=r,this.filename=n):typeof n>"u"?(this.referenceBy=Pue,this.filename=r,i.indexOf("w")!=null&&(this.fileId=new aT)):(this.referenceBy=vf,this.fileId=r,this.filename=n),this.mode=i??"r",this.options=a||{},this.isOpen=!1,this.root=this.options.root==null?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||uT.primary,this.writeConcern=fT(t,this.options),this.internalChunkSize=this.options.chunkSize==null?rn.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var u=this.options.promiseLibrary||Promise;this.promiseLibrary=u,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(f){this.mode[0]==="w"&&this.position===0&&this.uploadDate==null?this.internalChunkSize=f:this.internalChunkSize=this.internalChunkSize}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})},"GridStore");Me.prototype.open=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},this.mode!=="w"&&this.mode!=="w+"&&this.mode!=="r")throw $i.create({message:"Illegal mode "+this.mode,driver:!0});return fr(this.db.s.topology,Uue,[this,e,t],{skipSessions:!0})};var Uue=s(function(e,t,r){var n=fT(e.db,e.options);if(e.mode==="w"||e.mode==="w+"){var i=e.collection();i.ensureIndex([["filename",1]],n,function(){var a=e.chunkCollection(),u=Due(n);u.unique=!0,a.ensureIndex([["files_id",1],["n",1]],u,function(){EL(e,n,function(f,l){if(f)return r(f);e.isOpen=!0,r(f,l)})})})}else EL(e,n,function(a,u){if(a)return r(a);e.isOpen=!0,r(a,u)})},"open");Me.prototype.eof=function(){return this.position===this.length};Me.prototype.getc=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},fr(this.db.s.topology,jue,[this,e,t],{skipSessions:!0})};var jue=s(function(e,t,r){e.eof()?r(null,null):e.currentChunk.eof()?cu(e,e.currentChunk.chunkNumber+1,function(n,i){e.currentChunk=i,e.position=e.position+1,r(n,e.currentChunk.getc())}):(e.position=e.position+1,r(null,e.currentChunk.getc()))},"getc");Me.prototype.puts=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};var n=e.match(/\n$/)==null?e+` +`:e;return fr(this.db.s.topology,this.write.bind(this),[n,t,r],{skipSessions:!0})};Me.prototype.stream=function(){return new zi(this)};Me.prototype.write=s(function(t,r,n,i){return typeof n=="function"&&(i=n,n={}),n=n||{},fr(this.db.s.topology,Zue,[this,t,r,n,i],{skipSessions:!0})},"write");Me.prototype.destroy=s(function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},"destroy");Me.prototype.writeFile=function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},fr(this.db.s.topology,Wue,[this,e,t,r],{skipSessions:!0})};var Wue=s(function(e,t,r,n){if(typeof t=="string"){Gp.open(t,"r",function(i,a){if(i)return n(i);e.writeFile(a,n)});return}e.open(function(i,a){if(i)return n(i,a);Gp.fstat(t,function(u,f){if(u)return n(u,a);var l=0,h=0,m=s(function(){var p=Xp.alloc(a.chunkSize);Gp.read(t,p,0,p.length,l,function(g,w,O){if(g)return n(g,a);l=l+w;var N=new rn(a,{n:h++},a.writeConcern);N.write(O.slice(0,w),function(A,M){if(A)return n(A,a);M.save({},function(L){if(L)return n(L,a);if(a.position=a.position+w,a.currentChunk=M,l>=f.size)Gp.close(t,function(I){if(I)return n(I);a.close(function(R){return n(R||null,a)})});else return process.nextTick(m)})})})},"writeChunk");process.nextTick(m)})})},"writeFile");Me.prototype.close=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},fr(this.db.s.topology,Fue,[this,e,t],{skipSessions:!0})};var Fue=s(function(e,t,r){e.mode[0]==="w"?(t=Object.assign({},e.writeConcern,t),e.currentChunk!=null&&e.currentChunk.position>0?e.currentChunk.save({},function(n){if(n&&typeof r=="function")return r(n);e.collection(function(i,a){if(i&&typeof r=="function")return r(i);e.uploadDate!=null?oT(e,function(u,f){if(u){if(typeof r=="function")return r(u);throw u}a.save(f,t,function(l){typeof r=="function"&&r(l,f)})}):(e.uploadDate=new Date,oT(e,function(u,f){if(u){if(typeof r=="function")return r(u);throw u}a.save(f,t,function(l){typeof r=="function"&&r(l,f)})}))})}):e.collection(function(n,i){if(n&&typeof r=="function")return r(n);e.uploadDate=new Date,oT(e,function(a,u){if(a){if(typeof r=="function")return r(a);throw a}i.save(u,t,function(f){typeof r=="function"&&r(f,u)})})})):e.mode[0]==="r"?typeof r=="function"&&r(null,null):typeof r=="function"&&r($i.create({message:cT("Illegal mode %s",e.mode),driver:!0}))},"close");Me.prototype.chunkCollection=function(e){return typeof e=="function"?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")};Me.prototype.unlink=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},fr(this.db.s.topology,$ue,[this,e,t],{skipSessions:!0})};var $ue=s(function(e,t,r){Of(e,function(n){if(n!==null)return n.message="at deleteChunks: "+n.message,r(n);e.collection(function(i,a){if(i!==null)return i.message="at collection: "+i.message,r(i);a.remove({_id:e.fileId},e.writeConcern,function(u){r(u,e)})})})},"unlink");Me.prototype.collection=function(e){return typeof e=="function"&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")};Me.prototype.readlines=function(e,t,r){var n=Array.prototype.slice.call(arguments,0);return r=typeof n[n.length-1]=="function"?n.pop():void 0,e=n.length?n.shift():` +`,e=e||` +`,t=n.length?n.shift():{},fr(this.db.s.topology,zue,[this,e,t,r],{skipSessions:!0})};var zue=s(function(e,t,r,n){e.read(function(i,a){if(i)return n(i);var u=a.toString().split(t);u=u.length>0?u.splice(0,u.length-1):[];for(var f=0;f=a){var f=e.currentChunk.readSlice(a-u._index);return f.copy(u,u._index),e.position=e.position+u.length,a===0&&u.length===0?i($i.create({message:"File does not exist",driver:!0}),null):i(null,u)}f=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position),f.copy(u,u._index),u._index+=f.length,cu(e,e.currentChunk.chunkNumber+1,function(l,h){if(l)return i(l);h.length()>0?(e.currentChunk=h,e.read(t,u,i)):u._index>0?i(null,u):i($i.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)})},"read");Me.prototype.tell=function(e){var t=this;return typeof e=="function"?e(null,this.position):new t.promiseLibrary(function(r){r(t.position)})};Me.prototype.seek=function(e,t,r,n){var i=Array.prototype.slice.call(arguments,1);return n=typeof i[i.length-1]=="function"?i.pop():void 0,t=i.length?i.shift():null,r=i.length?i.shift():{},fr(this.db.s.topology,Yue,[this,e,t,r,n],{skipSessions:!0})};var Yue=s(function(e,t,r,n,i){if(e.mode!=="r")return i($i.create({message:"seek is only supported for mode r",driver:!0}));var a=r??Me.IO_SEEK_SET,u=t,f=0;a===Me.IO_SEEK_CUR?f=e.position+u:a===Me.IO_SEEK_END?f=e.length+u:f=u;var l=Math.floor(f/e.chunkSize),h=s(function(){cu(e,l,function(m,p){if(m)return i(m,null);if(p==null)return i(new Error("no chunk found"));e.currentChunk=p,e.position=f,e.currentChunk.position=e.position%e.chunkSize,i(m,e)})},"seekChunk");h()},"seek"),EL=s(function(e,t,r){var n=e.collection(),i=e.referenceBy===vf?{_id:e.fileId}:{filename:e.filename};i=e.fileId==null&&e.filename==null?null:i,t.readPreference=e.readPreference,i!=null?n.findOne(i,t,function(u,f){if(u)return a(u);if(f!=null)e.fileId=f._id,e.filename=e.mode==="r"||e.filename===void 0?f.filename:e.filename,e.contentType=f.contentType,e.internalChunkSize=f.chunkSize,e.uploadDate=f.uploadDate,e.aliases=f.aliases,e.length=f.length,e.metadata=f.metadata,e.internalMd5=f.md5;else if(e.mode!=="r")e.fileId=e.fileId==null?new aT:e.fileId,e.contentType=Me.DEFAULT_CONTENT_TYPE,e.internalChunkSize=e.internalChunkSize==null?rn.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0;else{e.length=0;var l=e.fileId._bsontype==="ObjectID"?e.fileId.toHexString():e.fileId;return a($i.create({message:cT("file with id %s not opened for writing",e.referenceBy===vf?l:e.filename),driver:!0}),e)}e.mode==="r"?cu(e,0,t,function(h,m){if(h)return a(h);e.currentChunk=m,e.position=0,r(null,e)}):e.mode==="w"&&f?Of(e,t,function(h){if(h)return a(h);e.currentChunk=new rn(e,{n:0},e.writeConcern),e.contentType=e.options.content_type==null?e.contentType:e.options.content_type,e.internalChunkSize=e.options.chunk_size==null?e.internalChunkSize:e.options.chunk_size,e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=0,r(null,e)}):e.mode==="w"?(e.currentChunk=new rn(e,{n:0},e.writeConcern),e.contentType=e.options.content_type==null?e.contentType:e.options.content_type,e.internalChunkSize=e.options.chunk_size==null?e.internalChunkSize:e.options.chunk_size,e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=0,r(null,e)):e.mode==="w+"&&cu(e,NL(e),t,function(h,m){if(h)return a(h);e.currentChunk=m??new rn(e,{n:0},e.writeConcern),e.currentChunk.position=e.currentChunk.data.length(),e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=e.length,r(null,e)})}):(e.fileId=e.fileId==null?new aT:e.fileId,e.contentType=Me.DEFAULT_CONTENT_TYPE,e.internalChunkSize=e.internalChunkSize==null?rn.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,e.mode==="w"?Of(e,t,function(u){if(u)return a(u);e.currentChunk=new rn(e,{n:0},e.writeConcern),e.contentType=e.options.content_type==null?e.contentType:e.options.content_type,e.internalChunkSize=e.options.chunk_size==null?e.internalChunkSize:e.options.chunk_size,e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=0,r(null,e)}):e.mode==="w+"&&cu(e,NL(e),t,function(u,f){if(u)return a(u);e.currentChunk=f??new rn(e,{n:0},e.writeConcern),e.currentChunk.position=e.currentChunk.data.length(),e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=e.length,r(null,e)}));function a(u){a.err||r(a.err=u)}s(a,"error")},"_open"),TL=s(function(e,t,r,n){typeof r=="function"&&(n=r,r=null);var i=typeof r=="boolean"?r:!1;if(e.mode!=="w")n($i.create({message:cT("file with id %s not opened for writing",e.referenceBy===vf?e.referenceBy:e.filename),driver:!0}),null);else if(e.currentChunk.position+t.length>=e.chunkSize){for(var a=e.currentChunk.chunkNumber,u=e.chunkSize-e.currentChunk.position,f=t.slice(0,u),l=t.slice(u),h=[e.currentChunk.write(f)];l.length>=e.chunkSize;){var m=new rn(e,{n:a+1},e.writeConcern);f=l.slice(0,e.chunkSize),l=l.slice(e.chunkSize),a=a+1,m.write(f),h.push(m)}e.currentChunk=new rn(e,{n:a+1},e.writeConcern),l.length>0&&e.currentChunk.write(l),e.position=e.position+t.length;for(var p=h.length,g=0;g=f.length)return a("offset larger than size of file",null);if(r&&r>f.length)return a("length is larger than the size of the file",null);if(n&&r&&n+r>f.length)return a("offset and length is larger than the size of the file",null);n!=null?f.seek(n,function(l,h){if(l)return a(l);h.read(r,a)}):f.read(r,a)})},"readStatic");Me.readlines=function(e,t,r,n,i){var a=Array.prototype.slice.call(arguments,2);return i=typeof a[a.length-1]=="function"?a.pop():void 0,r=a.length?a.shift():null,n=a.length?a.shift():null,n=n||{},fr(e.s.topology,Xue,[e,t,r,n,i],{skipSessions:!0})};var Xue=s(function(e,t,r,n,i){var a=r??` +`;new Me(e,t,"r",n).open(function(u,f){if(u)return i(u);f.readlines(a,i)})},"readlinesStatic");Me.unlink=function(e,t,r,n){var i=Array.prototype.slice.call(arguments,2);return n=typeof i[i.length-1]=="function"?i.pop():void 0,r=i.length?i.shift():{},r=r||{},fr(e.s.topology,Jue,[this,e,t,r,n],{skipSessions:!0})};var Jue=s(function(e,t,r,n,i){var a=fT(t,n);if(r.constructor===Array)for(var u=0,f=0;fe.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-i._index,e.push(i.slice(0,i._index))),e.totalBytesToRead<=0&&(e.endCalled=!0)})},"read"),r=e.gs.length{"use strict";var IL=require("stream"),Que=require("util");RL.exports=fu;function fu(e,t,r,n,i){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:n,init:!1,expectedEnd:0,file:null,options:i,readPreference:r},IL.Readable.call(this)}s(fu,"GridFSBucketReadStream");Que.inherits(fu,IL.Readable);fu.prototype._read=function(){var e=this;this.destroyed||rce(e,function(){ece(e)})};fu.prototype.start=function(e){return BL(this),this.s.options.start=e,this};fu.prototype.end=function(e){return BL(this),this.s.options.end=e,this};fu.prototype.abort=function(e){var t=this;this.push(null),this.destroyed=!0,this.s.cursor?this.s.cursor.close(function(r){t.emit("close"),e&&e(r)}):(this.s.init||t.emit("close"),e&&e())};function BL(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}s(BL,"throwIfInitialized");function ece(e){e.destroyed||e.s.cursor.next(function(t,r){if(e.destroyed)return;if(t)return si(e,t);if(!r){e.push(null),process.nextTick(()=>{e.s.cursor.close(function(g){if(g){si(e,g);return}e.emit("close")})});return}var n=e.s.file.length-e.s.bytesRead,i=e.s.expected++,a=Math.min(e.s.file.chunkSize,n);if(r.n>i){var u="ChunkIsMissing: Got unexpected n: "+r.n+", expected: "+i;return si(e,new Error(u))}if(r.n0&&(f.n={$gte:l})}e.s.cursor=e.s.chunks.find(f).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=ice(e,n,e.s.cursor,e.s.options)}catch(h){return si(e,h)}e.emit("file",n)})}s(tce,"init");function rce(e,t){if(e.s.file)return t();e.s.init||(tce(e),e.s.init=!0),e.once("file",function(){t()})}s(rce,"waitForFile");function nce(e,t,r){if(r&&r.start!=null){if(r.start>t.length)throw new Error("Stream start ("+r.start+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream start ("+r.start+") must not be negative");if(r.end!=null&&r.endt.length)throw new Error("Stream end ("+n.end+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream end ("+n.end+") must not be negative");var i=n.start!=null?Math.floor(n.start/t.chunkSize):0;return r.limit(Math.ceil(n.end/t.chunkSize)-i),e.s.expectedEnd=Math.ceil(n.end/t.chunkSize),Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}}s(ice,"handleEndOption");function si(e,t){e.emit("error",t)}s(si,"__handleError")});var WL=E((_we,jL)=>{"use strict";var DL=ro().MONGODB_ERROR_CODES,qL=G(),sce=require("crypto"),PL=require("stream"),oce=require("util"),Ef=qn().Buffer,ace=x().deprecateOptions,Nf=ace({name:"GridFSBucketWriteStream",deprecatedOptions:["disableMD5"],optionsIndex:2},function(e,t,r){if(r=r||{},PL.Writable.call(this,r),this.bucket=e,this.chunks=e.s._chunksCollection,this.filename=t,this.files=e.s._filesCollection,this.options=r,this.done=!1,this.id=r.id?r.id:qL.BSON.ObjectId(),this.chunkSizeBytes=this.options.chunkSizeBytes,this.bufToStore=Ef.alloc(this.chunkSizeBytes),this.length=0,this.md5=!r.disableMD5&&sce.createHash("md5"),this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1,promiseLibrary:this.bucket.s.promiseLibrary},!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=!0;var n=this;uce(this,function(){n.bucket.s.checkedIndexes=!0,n.bucket.emit("index")})}});oce.inherits(Nf,PL.Writable);Nf.prototype.write=function(e,t,r){var n=this;return UL(this,function(){return fce(n,e,t,r)})};Nf.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return typeof e=="function"?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),typeof e=="function"?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},function(r){typeof e=="function"&&e(r)})};Nf.prototype.end=function(e,t,r){var n=this;if(typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),!Tf(this,r)){if(this.state.streamEnd=!0,r&&this.once("finish",function(i){r(null,i)}),!e){UL(this,function(){ML(n)});return}this.write(e,t,function(){ML(n)})}};function dT(e,t,r){if(!e.state.errored){if(e.state.errored=!0,r)return r(t);e.emit("error",t)}}s(dT,"__handleError");function LL(e,t,r){return{_id:qL.BSON.ObjectId(),files_id:e,n:t,data:r}}s(LL,"createChunkDoc");function lT(e,t){e.chunks.listIndexes().toArray(function(r,n){if(r){if(r.code===DL.NamespaceNotFound){var i={files_id:1,n:1};e.chunks.createIndex(i,{background:!1,unique:!0},function(f){if(f)return t(f);t()});return}return t(r)}var a=!1;if(n.forEach(function(f){if(f.key){var l=Object.keys(f.key);l.length===2&&f.key.files_id===1&&f.key.n===1&&(a=!0)}}),a)t();else{i={files_id:1,n:1};var u=bf(e);u.background=!1,u.unique=!0,e.chunks.createIndex(i,u,function(f){if(f)return t(f);t()})}})}s(lT,"checkChunksIndex");function hT(e,t){if(e.done)return!0;if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=!0;var r=cce(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);return Tf(e,t)?!1:(e.files.insertOne(r,bf(e),function(n){if(n)return dT(e,n,t);e.emit("finish",r),e.emit("close")}),!0)}return!1}s(hT,"checkDone");function uce(e,t){e.files.findOne({},{_id:1},function(r,n){if(r)return t(r);if(n)return t();e.files.listIndexes().toArray(function(i,a){if(i){if(i.code===DL.NamespaceNotFound){var u={filename:1,uploadDate:1};e.files.createIndex(u,{background:!1},function(h){if(h)return t(h);lT(e,t)});return}return t(i)}var f=!1;if(a.forEach(function(h){var m=Object.keys(h.key);m.length===2&&h.key.filename===1&&h.key.uploadDate===1&&(f=!0)}),f)lT(e,t);else{u={filename:1,uploadDate:1};var l=bf(e);l.background=!1,e.files.createIndex(u,l,function(h){if(h)return t(h);lT(e,t)})}})})}s(uce,"checkIndexes");function cce(e,t,r,n,i,a,u,f){var l={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:i};return n&&(l.md5=n),a&&(l.contentType=a),u&&(l.aliases=u),f&&(l.metadata=f),l}s(cce,"createFilesDoc");function fce(e,t,r,n){if(Tf(e,n))return!1;var i=Ef.isBuffer(t)?t:Ef.from(t,r);if(e.length+=i.length,e.pos+i.length0;){var h=i.length-a;if(i.copy(e.bufToStore,e.pos,h,h+f),e.pos+=f,u-=f,u===0){e.md5&&e.md5.update(e.bufToStore);var m=LL(e.id,e.n,Ef.from(e.bufToStore));if(++e.state.outstandingRequests,++l,Tf(e,n))return!1;e.chunks.insertOne(m,bf(e),function(p){if(p)return dT(e,p);--e.state.outstandingRequests,--l,l||(e.emit("drain",m),n&&n(),hT(e))}),u=e.chunkSizeBytes,e.pos=0,++e.n}a-=f,f=Math.min(u,a)}return!1}s(fce,"doWrite");function bf(e){var t={};return e.options.writeConcern&&(t.w=e.options.writeConcern.w,t.wtimeout=e.options.writeConcern.wtimeout,t.j=e.options.writeConcern.j),t}s(bf,"getWriteOptions");function UL(e,t){return e.bucket.s.checkedIndexes?t(!1):(e.bucket.once("index",function(){t(!0)}),!0)}s(UL,"waitForIndexes");function ML(e,t){if(e.pos===0)return hT(e,t);++e.state.outstandingRequests;var r=Ef.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos),e.md5&&e.md5.update(r);var n=LL(e.id,e.n,r);if(Tf(e,t))return!1;e.chunks.insertOne(n,bf(e),function(i){if(i)return dT(e,i);--e.state.outstandingRequests,hT(e)})}s(ML,"writeRemnant");function Tf(e,t){return e.state.aborted?(typeof t=="function"&&t(new Error("this stream has been aborted")),!0):!1}s(Tf,"checkAborted");jL.exports=Nf});var YL=E((vwe,VL)=>{"use strict";var FL=require("events").EventEmitter,$L=xL(),zL=WL(),mT=x().shallowClone,lce=x().toError,hce=require("util"),gT=x().executeLegacyOperation,HL=x().deprecateOptions,pT={bucketName:"fs",chunkSizeBytes:255*1024};VL.exports=jn;function jn(e,t){if(FL.apply(this),this.setMaxListeners(0),t&&typeof t=="object"){t=mT(t);for(var r=Object.keys(pT),n=0;n=0?(r={uploadDate:1},n=t.revision):n=-t.revision-1);var i={filename:e};return t={sort:r,skip:n,start:t&&t.start,end:t&&t.end},new $L(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,i,t)};jn.prototype.rename=function(e,t,r){return gT(this.s.db.s.topology,pce,[this,e,t,r],{skipSessions:!0})};function pce(e,t,r,n){var i={_id:t},a={$set:{filename:r}};e.s._filesCollection.updateOne(i,a,function(u,f){if(u)return n(u);if(!f.result.n)return n(lce("File with id "+t+" not found"));n()})}s(pce,"_rename");jn.prototype.drop=function(e){return gT(this.s.db.s.topology,mce,[this,e],{skipSessions:!0})};jn.prototype.getLogger=function(){return this.s.db.s.logger};function mce(e,t){e.s._filesCollection.drop(function(r){if(r)return t(r);e.s._chunksCollection.drop(function(n){return n?t(n):t()})})}s(mce,"_drop")});var kE=E((Ewe,kL)=>{"use strict";var at=G(),gce=xM(),ye=au().connect;ye.MongoError=at.MongoError;ye.MongoNetworkError=at.MongoNetworkError;ye.MongoTimeoutError=at.MongoTimeoutError;ye.MongoServerSelectionError=at.MongoServerSelectionError;ye.MongoParseError=at.MongoParseError;ye.MongoWriteConcernError=at.MongoWriteConcernError;ye.MongoBulkWriteError=Zd().BulkWriteError;ye.BulkWriteError=ye.MongoBulkWriteError;ye.ServerApiVersion=at.ServerApiVersion;ye.Admin=dE();ye.MongoClient=au();ye.Db=gf();ye.Collection=tu();ye.Server=wf();ye.ReplSet=zE();ye.Mongos=FE();ye.ReadPreference=at.ReadPreference;ye.GridStore=CL();ye.Chunk=sT();ye.Logger=at.Logger;ye.AggregationCursor=ep();ye.CommandCursor=rp();ye.Cursor=ri();ye.GridFSBucket=YL();ye.CoreServer=at.Server;ye.CoreConnection=at.Connection;ye.Binary=at.BSON.Binary;ye.Code=at.BSON.Code;ye.Map=at.BSON.Map;ye.DBRef=at.BSON.DBRef;ye.Double=at.BSON.Double;ye.Int32=at.BSON.Int32;ye.Long=at.BSON.Long;ye.MinKey=at.BSON.MinKey;ye.MaxKey=at.BSON.MaxKey;ye.ObjectID=at.BSON.ObjectID;ye.ObjectId=at.BSON.ObjectID;ye.Symbol=at.BSON.Symbol;ye.Timestamp=at.BSON.Timestamp;ye.BSONRegExp=at.BSON.BSONRegExp;ye.Decimal128=at.BSON.Decimal128;ye.connect=ye;ye.instrument=function(e,t){typeof e=="function"&&(t=e,e={});let r=new gce;return r.instrument(ye.MongoClient,t),r};kL.exports=ye});var Af=E((GL,KL)=>{var yce=require("stream");GL=KL.exports=yT;yT.through=yT;function yT(e,t,r){e=e||function(m){this.queue(m)},t=t||function(){this.queue(null)};var n=!1,i=!1,a=[],u=!1,f=new yce;f.readable=f.writable=!0,f.paused=!1,f.autoDestroy=!(r&&r.autoDestroy===!1),f.write=function(m){return e.call(this,m),!f.paused};function l(){for(;a.length&&!f.paused;){var m=a.shift();if(m===null)return f.emit("end");f.emit("data",m)}}s(l,"drain"),f.queue=f.push=function(m){return u||(m===null&&(u=!0),a.push(m),l()),f},f.on("end",function(){f.readable=!1,!f.writable&&f.autoDestroy&&process.nextTick(function(){f.destroy()})});function h(){f.writable=!1,t.call(f),!f.readable&&f.autoDestroy&&f.destroy()}return s(h,"_end"),f.end=function(m){if(!n)return n=!0,arguments.length&&f.write(m),h(),f},f.destroy=function(){if(!i)return i=!0,n=!0,a.length=0,f.writable=f.readable=!1,f.emit("close"),f},f.pause=function(){if(!f.paused)return f.paused=!0,f},f.resume=function(){return f.paused&&(f.paused=!1,f.emit("resume")),l(),f.paused||f.emit("drain"),f},f}s(yT,"through")});var JL=E((Nwe,XL)=>{"use strict";var Sce=require("stream");XL.exports=s(function e(t){if(Array.isArray(t)){var r=0,n=t.length;return e(function(f){return r{var _ce=require("stream"),wce=["write","end","destroy"],vce=["resume","pause"],Oce=["data","close"],ZL=Array.prototype.slice;QL.exports=Ece;function ST(e,t){if(e.forEach)return e.forEach(t);for(var r=0;r{var Tce=require("stream").Stream;e2.exports=function(e,t){var r=new Tce,n=0,i=0,a=!1,u=!1,f=!1,l=0,h=!1;t=t||{};var m=t.failures?"failure":"error",p={};r.writable=!0,r.readable=!0;function g(A,M){var L=l+1;if(M===L?(A!==void 0&&r.emit.apply(r,["data",A]),l++,L++):p[M]=A,p.hasOwnProperty(L)){var I=p[L];return delete p[L],g(I,L)}i++,n===i&&(u&&(u=!1,r.emit("drain")),a&&N())}s(g,"queueData");function w(A,M,L){f||(h=!0,(!A||t.failures)&&g(M,L),A&&r.emit.apply(r,[m,A]),h=!1)}s(w,"next");function O(A,M,L){return e.call(null,A,function(I,R){L(I,R,M)})}s(O,"wrappedMapper"),r.write=function(A){if(a)throw new Error("map stream is not writable");h=!1,n++;try{var M=O(A,n,w);return u=M===!1,!u}catch(L){if(h)throw L;return w(L),!u}};function N(A){if(a=!0,r.writable=!1,A!==void 0)return g(A,n);n==i&&(r.readable=!1,r.emit("end"),r.destroy())}return s(N,"end"),r.end=function(A){a||N(A)},r.destroy=function(){a=f=!0,r.writable=r.readable=u=!1,process.nextTick(function(){r.emit("close")})},r.pause=function(){u=!0},r.resume=function(){u=!1},r}});var n2=E((Rwe,r2)=>{r2.exports=Af()});var s2=E((xwe,i2)=>{var Nce=Af(),bce=require("string_decoder").StringDecoder;i2.exports=Ace;function Ace(e,t,r){var n=new bce,i="",a=r&&r.maxLength,u=!(r&&r.trailing===!1);typeof e=="function"&&(t=e,e=null),e||(e=/\r?\n/);function f(h,m){if(t){try{m=t(m)}catch(p){return h.emit("error",p)}typeof m<"u"&&h.queue(m)}else h.queue(m)}s(f,"emit");function l(h,m){var p=((i??"")+m).split(e);if(i=p.pop(),a&&i.length>a)return h.emit("error",new Error("maximum buffer reached"));for(var g=0;g{var Cce=_T(),Ice=Af();o2.exports=function(){var e;if(arguments.length==1&&Array.isArray(arguments[0])?e=arguments[0]:e=[].slice.call(arguments),e.length==0)return Ice();if(e.length==1)return e[0];var t=e[0],r=e[e.length-1],n=Cce(t,r);function i(f){f.length<2||(f[0].pipe(f[1]),i(f.slice(1)))}s(i,"recurse"),i(e);function a(){var f=[].slice.call(arguments);f.unshift("error"),n.emit.apply(n,f)}s(a,"onerror");for(var u=1;u{var Cf=require("stream").Stream,Ae=u2,Bce=Af(),Rce=JL(),xce=_T(),Mce=t2(),Dce=n2(),qce=s2(),Pce=a2(),Lce=global.setImmediate||process.nextTick;Ae.Stream=Cf;Ae.through=Bce;Ae.from=Rce;Ae.duplex=xce;Ae.map=Mce;Ae.pause=Dce;Ae.split=qce;Ae.pipeline=Ae.connect=Ae.pipe=Pce;Ae.concat=Ae.merge=function(){var e=[].slice.call(arguments);e.length===1&&e[0]instanceof Array&&(e=e[0]);var t=new Cf;t.setMaxListeners(0);var r=0;return t.writable=t.readable=!0,e.length?e.forEach(function(n){n.pipe(t,{end:!1});var i=!1;n.on("end",function(){i||(i=!0,r++,r==e.length&&t.emit("end"))})}):process.nextTick(function(){t.emit("end")}),t.write=function(n){this.emit("data",n)},t.destroy=function(){e.forEach(function(n){n.destroy&&n.destroy()})},t};Ae.collect=Ae.writeArray=function(e){if(typeof e!="function")throw new Error("function writeArray (done): done must be function");var t=new Cf,r=[],n=!1;return t.write=function(i){r.push(i)},t.end=function(){n=!0,e(null,r)},t.writable=!0,t.readable=!1,t.destroy=function(){t.writable=t.readable=!1,!n&&e(new Error("destroyed before end"),r)},t};Ae.readArray=function(e){var t=new Cf,r=0,n=!1,i=!1;if(t.readable=!0,t.writable=!1,!Array.isArray(e))throw new Error("event-stream.read expects an array");return t.resume=function(){if(!i){n=!1;for(var a=e.length;r1&&r.emit("data",h),Lce(function(){if(!(a||i||u))try{u=!0,e.call(r,n++,function(){u=!1,f.apply(null,arguments)})}catch(m){r.emit("error",m)}})}return s(f,"get"),r.resume=function(){i=!1,f()},process.nextTick(f),r.pause=function(){i=!0},r.destroy=function(){r.emit("end"),r.emit("close"),a=!0},r};Ae.mapSync=function(e){return Ae.through(s(function(r){var n;try{n=e(r)}catch(i){return this.emit("error",i)}n!==void 0&&this.emit("data",n)},"write"))};Ae.filterSync=function(e){return Ae.through(function(t){var r=this;e(t)&&r.queue(t)})};Ae.flatmapSync=function(e){return Ae.through(function(t){var r=this;t.forEach(function(n){r.queue(e(n))})})};Ae.log=function(e){return Ae.through(function(t){var r=[].slice.call(arguments);e?console.error(e,t):console.error(t),this.emit("data",t)})};Ae.child=function(e){return Ae.duplex(e.stdin,e.stdout)};Ae.parse=function(e){var t=!!(e&&e.error);return Ae.through(function(r){var n;try{r&&(n=JSON.parse(r.toString()))}catch(i){return t?this.emit("error",i):console.error(i,"attempting to parse:",r)}n!==void 0&&this.emit("data",n)})};Ae.stringify=function(){var e=require("buffer").Buffer;return Ae.mapSync(function(t){return JSON.stringify(e.isBuffer(t)?t.toString():t)+` +`})};Ae.replace=function(e,t){return Ae.pipeline(Ae.split(e),Ae.join(t))};Ae.join=function(e){if(typeof e=="function")return Ae.wait(e);var t=!0;return Ae.through(function(r){return t||this.emit("data",e),t=!1,this.emit("data",r),!0})};Ae.wait=function(e){var t=[];return Ae.through(function(r){t.push(r)},function(){var r=Buffer.isBuffer(t[0])?Buffer.concat(t):t.join("");this.emit("data",r),this.emit("end"),e&&e(null,r)})};Ae.pipeable=function(){throw new Error("[EVENT-STREAM] es.pipeable is deprecated")}});var N2=E((_e,T2)=>{_e=T2.exports=We;var Ze;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?Ze=s(function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)},"debug"):Ze=s(function(){},"debug");_e.SEMVER_SPEC_VERSION="2.0.0";var If=256,Jp=Number.MAX_SAFE_INTEGER||9007199254740991,vT=16,Uce=If-6,Bf=_e.re=[],ut=_e.safeRe=[],H=_e.src=[],Ue=0,bT="[a-zA-Z0-9-]",OT=[["\\s",1],["\\d",If],[bT,Uce]];function nm(e){for(var t=0;t)?=?)";var Zp=Ue++;H[Zp]=H[hu]+"|x|X|\\*";var Qp=Ue++;H[Qp]=H[lu]+"|x|X|\\*";var Po=Ue++;H[Po]="[v=\\s]*("+H[Qp]+")(?:\\.("+H[Qp]+")(?:\\.("+H[Qp]+")(?:"+H[CT]+")?"+H[xf]+"?)?)?";var pu=Ue++;H[pu]="[v=\\s]*("+H[Zp]+")(?:\\.("+H[Zp]+")(?:\\.("+H[Zp]+")(?:"+H[IT]+")?"+H[xf]+"?)?)?";var d2=Ue++;H[d2]="^"+H[yu]+"\\s*"+H[Po]+"$";var p2=Ue++;H[p2]="^"+H[yu]+"\\s*"+H[pu]+"$";var m2=Ue++;H[m2]="(?:^|[^\\d])(\\d{1,"+vT+"})(?:\\.(\\d{1,"+vT+"}))?(?:\\.(\\d{1,"+vT+"}))?(?:$|[^\\d])";var im=Ue++;H[im]="(?:~>?)";var mu=Ue++;H[mu]="(\\s*)"+H[im]+"\\s+";Bf[mu]=new RegExp(H[mu],"g");ut[mu]=new RegExp(nm(H[mu]),"g");var jce="$1~",g2=Ue++;H[g2]="^"+H[im]+H[Po]+"$";var y2=Ue++;H[y2]="^"+H[im]+H[pu]+"$";var sm=Ue++;H[sm]="(?:\\^)";var gu=Ue++;H[gu]="(\\s*)"+H[sm]+"\\s+";Bf[gu]=new RegExp(H[gu],"g");ut[gu]=new RegExp(nm(H[gu]),"g");var Wce="$1^",S2=Ue++;H[S2]="^"+H[sm]+H[Po]+"$";var _2=Ue++;H[_2]="^"+H[sm]+H[pu]+"$";var MT=Ue++;H[MT]="^"+H[yu]+"\\s*("+RT+")$|^$";var DT=Ue++;H[DT]="^"+H[yu]+"\\s*("+h2+")$|^$";var Lo=Ue++;H[Lo]="(\\s*)"+H[yu]+"\\s*("+RT+"|"+H[Po]+")";Bf[Lo]=new RegExp(H[Lo],"g");ut[Lo]=new RegExp(nm(H[Lo]),"g");var Fce="$1$2$3",w2=Ue++;H[w2]="^\\s*("+H[Po]+")\\s+-\\s+("+H[Po]+")\\s*$";var v2=Ue++;H[v2]="^\\s*("+H[pu]+")\\s+-\\s+("+H[pu]+")\\s*$";var O2=Ue++;H[O2]="(<|>)?=?\\s*\\*";for(oi=0;oiIf)return null;var r=t.loose?ut[xT]:ut[BT];if(!r.test(e))return null;try{return new We(e,t)}catch{return null}}s(Uo,"parse");_e.valid=$ce;function $ce(e,t){var r=Uo(e,t);return r?r.version:null}s($ce,"valid");_e.clean=zce;function zce(e,t){var r=Uo(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}s(zce,"clean");_e.SemVer=We;function We(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof We){if(e.loose===t.loose)return e;e=e.version}else if(typeof e!="string")throw new TypeError("Invalid Version: "+e);if(e.length>If)throw new TypeError("version is longer than "+If+" characters");if(!(this instanceof We))return new We(e,t);Ze("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?ut[xT]:ut[BT]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Jp||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Jp||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Jp||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(function(n){if(/^[0-9]+$/.test(n)){var i=+n;if(i>=0&&i=0;)typeof this.prerelease[r]=="number"&&(this.prerelease[r]++,r=-2);r===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this};_e.inc=Hce;function Hce(e,t,r,n){typeof r=="string"&&(n=r,r=void 0);try{return new We(e,r).inc(t,n).version}catch{return null}}s(Hce,"inc");_e.diff=Vce;function Vce(e,t){if(qT(e,t))return null;var r=Uo(e),n=Uo(t),i="";if(r.prerelease.length||n.prerelease.length){i="pre";var a="prerelease"}for(var u in r)if((u==="major"||u==="minor"||u==="patch")&&r[u]!==n[u])return i+u;return a}s(Vce,"diff");_e.compareIdentifiers=du;var c2=/^[0-9]+$/;function du(e,t){var r=c2.test(e),n=c2.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e0}s(Rf,"gt");_e.lt=em;function em(e,t,r){return Hi(e,t,r)<0}s(em,"lt");_e.eq=qT;function qT(e,t,r){return Hi(e,t,r)===0}s(qT,"eq");_e.neq=E2;function E2(e,t,r){return Hi(e,t,r)!==0}s(E2,"neq");_e.gte=PT;function PT(e,t,r){return Hi(e,t,r)>=0}s(PT,"gte");_e.lte=LT;function LT(e,t,r){return Hi(e,t,r)<=0}s(LT,"lte");_e.cmp=tm;function tm(e,t,r,n){switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return qT(e,r,n);case"!=":return E2(e,r,n);case">":return Rf(e,r,n);case">=":return PT(e,r,n);case"<":return em(e,r,n);case"<=":return LT(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}s(tm,"cmp");_e.Comparator=En;function En(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof En){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof En))return new En(e,t);e=e.trim().split(/\s+/).join(" "),Ze("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Mf?this.value="":this.value=this.operator+this.semver.version,Ze("comp",this)}s(En,"Comparator");var Mf={};En.prototype.parse=function(e){var t=this.options.loose?ut[MT]:ut[DT],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1],this.operator==="="&&(this.operator=""),r[2]?this.semver=new We(r[2],this.options.loose):this.semver=Mf};En.prototype.toString=function(){return this.value};En.prototype.test=function(e){return Ze("Comparator.test",e,this.options.loose),this.semver===Mf?!0:(typeof e=="string"&&(e=new We(e,this.options)),tm(e,this.operator,this.semver,this.options))};En.prototype.intersects=function(e,t){if(!(e instanceof En))throw new TypeError("a Comparator is required");(!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1});var r;if(this.operator==="")return r=new St(e.value,t),rm(this.value,r,t);if(e.operator==="")return r=new St(this.value,t),rm(e.semver,r,t);var n=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),i=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),a=this.semver.version===e.semver.version,u=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),f=tm(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=tm(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return n||i||a&&u||f||l};_e.Range=St;function St(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof St)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new St(e.raw,t);if(e instanceof En)return new St(e.value,t);if(!(this instanceof St))return new St(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(function(r){return this.parseRange(r.trim())},this).filter(function(r){return r.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+this.raw);this.format()}s(St,"Range");St.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};St.prototype.toString=function(){return this.range};St.prototype.parseRange=function(e){var t=this.options.loose,r=t?ut[v2]:ut[w2];e=e.replace(r,cfe),Ze("hyphen replace",e),e=e.replace(ut[Lo],Fce),Ze("comparator trim",e,ut[Lo]),e=e.replace(ut[mu],jce),e=e.replace(ut[gu],Wce);var n=t?ut[MT]:ut[DT],i=e.split(" ").map(function(a){return tfe(a,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(i=i.filter(function(a){return!!a.match(n)})),i=i.map(function(a){return new En(a,this.options)},this),i};St.prototype.intersects=function(e,t){if(!(e instanceof St))throw new TypeError("a Range is required");return this.set.some(function(r){return r.every(function(n){return e.set.some(function(i){return i.every(function(a){return n.intersects(a,t)})})})})};_e.toComparators=efe;function efe(e,t){return new St(e,t).set.map(function(r){return r.map(function(n){return n.value}).join(" ").trim().split(" ")})}s(efe,"toComparators");function tfe(e,t){return Ze("comp",e,t),e=ife(e,t),Ze("caret",e),e=rfe(e,t),Ze("tildes",e),e=ofe(e,t),Ze("xrange",e),e=ufe(e,t),Ze("stars",e),e}s(tfe,"parseComparator");function Cr(e){return!e||e.toLowerCase()==="x"||e==="*"}s(Cr,"isX");function rfe(e,t){return e.trim().split(/\s+/).map(function(r){return nfe(r,t)}).join(" ")}s(rfe,"replaceTildes");function nfe(e,t){var r=t.loose?ut[y2]:ut[g2];return e.replace(r,function(n,i,a,u,f){Ze("tilde",e,n,i,a,u,f);var l;return Cr(i)?l="":Cr(a)?l=">="+i+".0.0 <"+(+i+1)+".0.0":Cr(u)?l=">="+i+"."+a+".0 <"+i+"."+(+a+1)+".0":f?(Ze("replaceTilde pr",f),l=">="+i+"."+a+"."+u+"-"+f+" <"+i+"."+(+a+1)+".0"):l=">="+i+"."+a+"."+u+" <"+i+"."+(+a+1)+".0",Ze("tilde return",l),l})}s(nfe,"replaceTilde");function ife(e,t){return e.trim().split(/\s+/).map(function(r){return sfe(r,t)}).join(" ")}s(ife,"replaceCarets");function sfe(e,t){Ze("caret",e,t);var r=t.loose?ut[_2]:ut[S2];return e.replace(r,function(n,i,a,u,f){Ze("caret",e,n,i,a,u,f);var l;return Cr(i)?l="":Cr(a)?l=">="+i+".0.0 <"+(+i+1)+".0.0":Cr(u)?i==="0"?l=">="+i+"."+a+".0 <"+i+"."+(+a+1)+".0":l=">="+i+"."+a+".0 <"+(+i+1)+".0.0":f?(Ze("replaceCaret pr",f),i==="0"?a==="0"?l=">="+i+"."+a+"."+u+"-"+f+" <"+i+"."+a+"."+(+u+1):l=">="+i+"."+a+"."+u+"-"+f+" <"+i+"."+(+a+1)+".0":l=">="+i+"."+a+"."+u+"-"+f+" <"+(+i+1)+".0.0"):(Ze("no pr"),i==="0"?a==="0"?l=">="+i+"."+a+"."+u+" <"+i+"."+a+"."+(+u+1):l=">="+i+"."+a+"."+u+" <"+i+"."+(+a+1)+".0":l=">="+i+"."+a+"."+u+" <"+(+i+1)+".0.0"),Ze("caret return",l),l})}s(sfe,"replaceCaret");function ofe(e,t){return Ze("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return afe(r,t)}).join(" ")}s(ofe,"replaceXRanges");function afe(e,t){e=e.trim();var r=t.loose?ut[p2]:ut[d2];return e.replace(r,function(n,i,a,u,f,l){Ze("xRange",e,n,i,a,u,f,l);var h=Cr(a),m=h||Cr(u),p=m||Cr(f),g=p;return i==="="&&g&&(i=""),h?i===">"||i==="<"?n="<0.0.0":n="*":i&&g?(m&&(u=0),f=0,i===">"?(i=">=",m?(a=+a+1,u=0,f=0):(u=+u+1,f=0)):i==="<="&&(i="<",m?a=+a+1:u=+u+1),n=i+a+"."+u+"."+f):m?n=">="+a+".0.0 <"+(+a+1)+".0.0":p&&(n=">="+a+"."+u+".0 <"+a+"."+(+u+1)+".0"),Ze("xRange return",n),n})}s(afe,"replaceXRange");function ufe(e,t){return Ze("replaceStars",e,t),e.trim().replace(ut[O2],"")}s(ufe,"replaceStars");function cfe(e,t,r,n,i,a,u,f,l,h,m,p,g){return Cr(r)?t="":Cr(n)?t=">="+r+".0.0":Cr(i)?t=">="+r+"."+n+".0":t=">="+t,Cr(l)?f="":Cr(h)?f="<"+(+l+1)+".0.0":Cr(m)?f="<"+l+"."+(+h+1)+".0":p?f="<="+l+"."+h+"."+m+"-"+p:f="<="+f,(t+" "+f).trim()}s(cfe,"hyphenReplace");St.prototype.test=function(e){if(!e)return!1;typeof e=="string"&&(e=new We(e,this.options));for(var t=0;t0){var i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}s(ffe,"testSet");_e.satisfies=rm;function rm(e,t,r){try{t=new St(t,r)}catch{return!1}return t.test(e)}s(rm,"satisfies");_e.maxSatisfying=lfe;function lfe(e,t,r){var n=null,i=null;try{var a=new St(t,r)}catch{return null}return e.forEach(function(u){a.test(u)&&(!n||i.compare(u)===-1)&&(n=u,i=new We(n,r))}),n}s(lfe,"maxSatisfying");_e.minSatisfying=hfe;function hfe(e,t,r){var n=null,i=null;try{var a=new St(t,r)}catch{return null}return e.forEach(function(u){a.test(u)&&(!n||i.compare(u)===1)&&(n=u,i=new We(n,r))}),n}s(hfe,"minSatisfying");_e.minVersion=dfe;function dfe(e,t){e=new St(e,t);var r=new We("0.0.0");if(e.test(r)||(r=new We("0.0.0-0"),e.test(r)))return r;r=null;for(var n=0;n":u.prerelease.length===0?u.patch++:u.prerelease.push(0),u.raw=u.format();case"":case">=":(!r||Rf(r,u))&&(r=u);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+a.operator)}})}return r&&e.test(r)?r:null}s(dfe,"minVersion");_e.validRange=pfe;function pfe(e,t){try{return new St(e,t).range||"*"}catch{return null}}s(pfe,"validRange");_e.ltr=mfe;function mfe(e,t,r){return UT(e,t,"<",r)}s(mfe,"ltr");_e.gtr=gfe;function gfe(e,t,r){return UT(e,t,">",r)}s(gfe,"gtr");_e.outside=UT;function UT(e,t,r,n){e=new We(e,n),t=new St(t,n);var i,a,u,f,l;switch(r){case">":i=Rf,a=LT,u=em,f=">",l=">=";break;case"<":i=em,a=PT,u=Rf,f="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(rm(e,t,n))return!1;for(var h=0;h=0.0.0")),p=p||w,g=g||w,i(w.semver,p.semver,n)?p=w:u(w.semver,g.semver,n)&&(g=w)}),p.operator===f||p.operator===l||(!g.operator||g.operator===f)&&a(e,g.semver))return!1;if(g.operator===l&&u(e,g.semver))return!1}return!0}s(UT,"outside");_e.prerelease=yfe;function yfe(e,t){var r=Uo(e,t);return r&&r.prerelease.length?r.prerelease:null}s(yfe,"prerelease");_e.intersects=Sfe;function Sfe(e,t,r){return e=new St(e,r),t=new St(t,r),e.intersects(t)}s(Sfe,"intersects");_e.coerce=_fe;function _fe(e){if(e instanceof We)return e;if(typeof e!="string")return null;var t=e.match(ut[m2]);return t==null?null:Uo(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}s(_fe,"coerce")});var A2=E((jwe,b2)=>{var Su=1e3,_u=Su*60,wu=_u*60,jo=wu*24,wfe=jo*7,vfe=jo*365.25;b2.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return Ofe(e);if(r==="number"&&isFinite(e))return t.long?Tfe(e):Efe(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Ofe(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*vfe;case"weeks":case"week":case"w":return r*wfe;case"days":case"day":case"d":return r*jo;case"hours":case"hour":case"hrs":case"hr":case"h":return r*wu;case"minutes":case"minute":case"mins":case"min":case"m":return r*_u;case"seconds":case"second":case"secs":case"sec":case"s":return r*Su;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}s(Ofe,"parse");function Efe(e){var t=Math.abs(e);return t>=jo?Math.round(e/jo)+"d":t>=wu?Math.round(e/wu)+"h":t>=_u?Math.round(e/_u)+"m":t>=Su?Math.round(e/Su)+"s":e+"ms"}s(Efe,"fmtShort");function Tfe(e){var t=Math.abs(e);return t>=jo?om(e,t,jo,"day"):t>=wu?om(e,t,wu,"hour"):t>=_u?om(e,t,_u,"minute"):t>=Su?om(e,t,Su,"second"):e+" ms"}s(Tfe,"fmtLong");function om(e,t,r,n){var i=t>=r*1.5;return Math.round(e/r)+" "+n+(i?"s":"")}s(om,"plural")});var jT=E((Fwe,C2)=>{function Nfe(e){r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=i,r.enabled=u,r.humanize=A2(),r.destroy=h,Object.keys(e).forEach(m=>{r[m]=e[m]}),r.names=[],r.skips=[],r.formatters={};function t(m){let p=0;for(let g=0;g{if(W==="%%")return"%";R++;let Ee=r.formatters[ee];if(typeof Ee=="function"){let V=A[R];W=Ee.call(M,V),A.splice(R,1),R--}return W}),r.formatArgs.call(M,A),(M.log||r.log).apply(M,A)}return s(N,"debug"),N.namespace=m,N.useColors=r.useColors(),N.color=r.selectColor(m),N.extend=n,N.destroy=r.destroy,Object.defineProperty(N,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(w!==r.namespaces&&(w=r.namespaces,O=r.enabled(m)),O),set:A=>{g=A}}),typeof r.init=="function"&&r.init(N),N}s(r,"createDebug");function n(m,p){let g=r(this.namespace+(typeof p>"u"?":":p)+m);return g.log=this.log,g}s(n,"extend");function i(m){r.save(m),r.namespaces=m,r.names=[],r.skips=[];let p,g=(typeof m=="string"?m:"").split(/[\s,]+/),w=g.length;for(p=0;p"-"+p)].join(",");return r.enable(""),m}s(a,"disable");function u(m){if(m[m.length-1]==="*")return!0;let p,g;for(p=0,g=r.skips.length;p{nn.formatArgs=Afe;nn.save=Cfe;nn.load=Ife;nn.useColors=bfe;nn.storage=Bfe();nn.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();nn.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function bfe(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}s(bfe,"useColors");function Afe(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+am.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),e.splice(n,0,t)}s(Afe,"formatArgs");nn.log=console.debug||console.log||(()=>{});function Cfe(e){try{e?nn.storage.setItem("debug",e):nn.storage.removeItem("debug")}catch{}}s(Cfe,"save");function Ife(){let e;try{e=nn.storage.getItem("debug")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}s(Ife,"load");function Bfe(){try{return localStorage}catch{}}s(Bfe,"localstorage");am.exports=jT()(nn);var{formatters:Rfe}=am.exports;Rfe.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var R2=E((Hwe,B2)=>{"use strict";B2.exports=(e,t=process.argv)=>{let r=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return n!==-1&&(i===-1||n{"use strict";var xfe=require("os"),x2=require("tty"),Tn=R2(),{env:Wt}=process,js;Tn("no-color")||Tn("no-colors")||Tn("color=false")||Tn("color=never")?js=0:(Tn("color")||Tn("colors")||Tn("color=true")||Tn("color=always"))&&(js=1);"FORCE_COLOR"in Wt&&(Wt.FORCE_COLOR==="true"?js=1:Wt.FORCE_COLOR==="false"?js=0:js=Wt.FORCE_COLOR.length===0?1:Math.min(parseInt(Wt.FORCE_COLOR,10),3));function WT(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}s(WT,"translateLevel");function FT(e,t){if(js===0)return 0;if(Tn("color=16m")||Tn("color=full")||Tn("color=truecolor"))return 3;if(Tn("color=256"))return 2;if(e&&!t&&js===void 0)return 0;let r=js||0;if(Wt.TERM==="dumb")return r;if(process.platform==="win32"){let n=xfe.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in Wt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in Wt)||Wt.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in Wt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Wt.TEAMCITY_VERSION)?1:0;if(Wt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Wt){let n=parseInt((Wt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Wt.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Wt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Wt.TERM)||"COLORTERM"in Wt?1:r}s(FT,"supportsColor");function Mfe(e){let t=FT(e,e&&e.isTTY);return WT(t)}s(Mfe,"getSupportLevel");M2.exports={supportsColor:Mfe,stdout:WT(FT(!0,x2.isatty(1))),stderr:WT(FT(!0,x2.isatty(2)))}});var P2=E((Jt,cm)=>{var Dfe=require("tty"),um=require("util");Jt.init=Ffe;Jt.log=Ufe;Jt.formatArgs=Pfe;Jt.save=jfe;Jt.load=Wfe;Jt.useColors=qfe;Jt.destroy=um.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Jt.colors=[6,2,3,4,5,1];try{let e=D2();e&&(e.stderr||e).level>=2&&(Jt.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Jt.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(i,a)=>a.toUpperCase()),n=process.env[t];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),e[r]=n,e},{});function qfe(){return"colors"in Jt.inspectOpts?!!Jt.inspectOpts.colors:Dfe.isatty(process.stderr.fd)}s(qfe,"useColors");function Pfe(e){let{namespace:t,useColors:r}=this;if(r){let n=this.color,i="\x1B[3"+(n<8?n:"8;5;"+n),a=` ${i};1m${t} \x1B[0m`;e[0]=a+e[0].split(` +`).join(` +`+a),e.push(i+"m+"+cm.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=Lfe()+t+" "+e[0]}s(Pfe,"formatArgs");function Lfe(){return Jt.inspectOpts.hideDate?"":new Date().toISOString()+" "}s(Lfe,"getDate");function Ufe(...e){return process.stderr.write(um.format(...e)+` +`)}s(Ufe,"log");function jfe(e){e?process.env.DEBUG=e:delete process.env.DEBUG}s(jfe,"save");function Wfe(){return process.env.DEBUG}s(Wfe,"load");function Ffe(e){e.inspectOpts={};let t=Object.keys(Jt.inspectOpts);for(let r=0;rt.trim()).join(" ")};q2.O=function(e){return this.inspectOpts.colors=this.useColors,um.inspect(e,this.inspectOpts)}});var fm=E((Gwe,$T)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$T.exports=I2():$T.exports=P2()});var YT=E((Kwe,z2)=>{var U2=9007199254740991,$fe="[object Arguments]",zfe="[object Function]",Hfe="[object GeneratorFunction]",Vfe=/^(?:0|[1-9]\d*)$/;function j2(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}s(j2,"apply");function Yfe(e,t){for(var r=-1,n=Array(e);++r1?r[i-1]:void 0,u=i>2?r[2]:void 0;for(a=e.length>3&&typeof a=="function"?(i--,a):void 0,u&&ele(r[0],r[1],u)&&(a=i<3?void 0:a,i=1),t=Object(t);++n-1&&e%1==0&&e-1&&e%1==0&&e<=U2}s(ale,"isLength");function VT(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}s(VT,"isObject");function ule(e){return!!e&&typeof e=="object"}s(ule,"isObjectLike");var cle=Qfe(function(e,t,r,n){Zfe(t,lle(t),e,n)}),fle=F2(function(e){return e.push(void 0,Kfe),j2(cle,void 0,e)});function lle(e){return HT(e)?Gfe(e,!0):Jfe(e)}s(lle,"keysIn");z2.exports=fle});var GT=E((Jwe,V2)=>{var hle=YT(),H2=require("stream").Readable,dle=require("util").inherits;function kT(e,t,r){this.db=e,this.collectionName=t,this.opts=r,r=hle(r||{},{query:{},size:5,fields:null,raw:!1,sort:{_id:-1},maxTimeMS:void 0,promoteValues:!0}),this.query=r.query||{},this.size=r.size,this.raw=r.raw,this.fields=r.fields,this.sort=r.sort,this.maxTimeMS=r.maxTimeMS,this.promoteValues=r.promoteValues,H2.call(this,{objectMode:!0})}s(kT,"BaseSampler");dle(kT,H2);Object.defineProperty(kT.prototype,"collection",{get:function(){return this.db.collection(this.collectionName,{})}});V2.exports=kT});var k2=E((KT,Y2)=>{(function(e,t){"use strict";typeof KT=="object"?Y2.exports=t():typeof define=="function"&&define.amd?define(t):e.Reservoir=t()})(KT,function(){"use strict";var e=22,t="none";function r(u,i){var a=i||Math.random,u=Math.max(1,Math.floor(u)>>0||1),f=0,l=-1,h=L,m=e*u;t==="R"?h=M:t==="X"?m=1/0:t==="Z"&&(h=I);var p=0,g=Math.exp(-Math.log(a())/u),w=null,O=[];O.pushSome=function(){this.length=Math.min(this.length,u);for(var R=0;R=u;)W++,R++,Y=Math.floor(a()*R);return w=Y,W}s(M,"algorithmR");function L(){var R=f,Y=a(),W=0,ee;if(f<=m){for(R++,p++,ee=p/R;ee>Y;)W++,R++,p++,ee=ee*p/R;return W}else return h=I,h()}s(L,"algorithmX");function I(){for(var R=f-u+1,Y,W,ee;;){var Ee=a(),V=f*(g-1),fe=Math.floor(V),ne=(f+1)/R;ne*=ne;var J=R+fe,K=Math.exp(Math.log(Ee*ne*J/(f+V))/u),ue=(f+V)/J*R/f;if(K<=ue){g=ue/K;break}var me=Ee*(f+1)/R*(f+fe+1)/(f+V);for(u=ee;W--)me=me*W/Y,Y--;if(g=Math.exp(-Math.log(a())/u),Math.exp(Math.log(me)/u)<=(f+V)/f)break}return fe}return s(I,"algorithmZ"),O}return s(r,"_Reservoir"),r})});var Q2=E((eve,Z2)=>{var G2=1/0,X2=9007199254740991,ple=17976931348623157e292,K2=0/0,mle="[object Function]",gle="[object GeneratorFunction]",yle="[object Symbol]",Sle=/^\s+|\s+$/g,_le=/^[-+]0x[0-9a-f]+$/i,wle=/^0b[01]+$/i,vle=/^0o[0-7]+$/i,Ole=/^(?:0|[1-9]\d*)$/,Ele=parseInt,Tle=Object.prototype,J2=Tle.toString,Nle=Math.ceil,ble=Math.max;function Ale(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),r=r>i?i:r,r<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(i);++n-1&&e%1==0&&e-1&&e%1==0&&e<=X2}s(Dle,"isLength");function lm(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}s(lm,"isObject");function qle(e){return!!e&&typeof e=="object"}s(qle,"isObjectLike");function Ple(e){return typeof e=="symbol"||qle(e)&&J2.call(e)==yle}s(Ple,"isSymbol");function Lle(e){if(!e)return e===0?e:0;if(e=jle(e),e===G2||e===-G2){var t=e<0?-1:1;return t*ple}return e===e?e:0}s(Lle,"toFinite");function Ule(e){var t=Lle(e),r=t%1;return t===t?r?t-r:t:0}s(Ule,"toInteger");function jle(e){if(typeof e=="number")return e;if(Ple(e))return K2;if(lm(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=lm(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=e.replace(Sle,"");var r=wle.test(e);return r||vle.test(e)?Ele(e.slice(2),r?2:8):_le.test(e)?K2:+e}s(jle,"toNumber");Z2.exports=Ble});var JT=E((rve,rU)=>{var tU=GT(),Wle=require("util").inherits,hm=wT(),Fle=k2(),$le=YT(),zle=Q2(),eU=fm()("mongodb-collection-sample:reservoir-sampler"),Hle=1e4,Vle=1e3;function Yle(e,t,r){r=$le(r||{},{chunkSize:Vle,promoteValues:!0});var n=new Fle(t),i=hm.through(s(function(u){n.pushSome(u)},"write"),s(function(){var u=zle(n,r.chunkSize),f=u.map(function(l){var h=e.find({_id:{$in:l}},{promoteValues:r.promoteValues,raw:r.raw});return r.fields&&h.project(r.fields),r.maxTimeMS&&h.maxTimeMS(r.maxTimeMS),h.stream()});hm.merge(f).pipe(hm.through(function(l){i.emit("data",l)})).on("end",function(){i.emit("end")})},"end"));return i}s(Yle,"reservoirStream");function XT(e,t,r){this.running=!1,this.chunkSize=r?r.chunkSize:void 0,tU.call(this,e,t,r)}s(XT,"ReservoirSampler");Wle(XT,tU);XT.prototype._read=function(){this.running||(this.running=!0,eU("using query `%j`",this.query),this.collection.countDocuments(this.query,function(e,t){if(e)return this.emit("error",e);eU("sampling %d documents from a collection with %d documents",this.size,t),this.collection.find(this.query,{projection:{_id:1},sort:this.sort,limit:Hle}).stream().pipe(hm.map(function(r,n){return n(null,r._id)})).pipe(Yle(this.collection,this.size,{chunkSize:this.chunkSize,fields:this.fields,maxTimeMS:this.maxTimeMS,raw:this.raw,promoteValues:this.promoteValues})).on("error",this.emit.bind(this,"error")).on("data",this.push.bind(this)).on("end",function(){this.running=!1,this.push(null)}.bind(this))}.bind(this)))};rU.exports=XT});var Nn=E(Ws=>{"use strict";var nU=Ws&&Ws.__extends||function(){var e=s(function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},e(t,r)},"extendStatics");return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}s(n,"__"),t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(Ws,"__esModule",{value:!0});Ws.BSONTypeError=Ws.BSONError=void 0;var kle=function(e){nU(t,e);function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return s(t,"BSONError"),Object.defineProperty(t.prototype,"name",{get:function(){return"BSONError"},enumerable:!1,configurable:!0}),t}(Error);Ws.BSONError=kle;var Gle=function(e){nU(t,e);function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return s(t,"BSONTypeError"),Object.defineProperty(t.prototype,"name",{get:function(){return"BSONTypeError"},enumerable:!1,configurable:!0}),t}(TypeError);Ws.BSONTypeError=Gle});var ZT=E(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});pm.getGlobal=void 0;function dm(e){return e&&e.Math==Math&&e}s(dm,"checkForMath");function Kle(){return dm(typeof globalThis=="object"&&globalThis)||dm(typeof window=="object"&&window)||dm(typeof self=="object"&&self)||dm(typeof global=="object"&&global)||Function("return this")()}s(Kle,"getGlobal");pm.getGlobal=Kle});var Wn=E(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.deprecate=ct.isObjectLike=ct.isDate=ct.haveBuffer=ct.isMap=ct.isRegExp=ct.isBigUInt64Array=ct.isBigInt64Array=ct.isUint8Array=ct.isAnyArrayBuffer=ct.randomBytes=ct.normalizedFunctionString=void 0;var QT=require("buffer"),Xle=ZT();function Jle(e){return e.toString().replace("function(","function (")}s(Jle,"normalizedFunctionString");ct.normalizedFunctionString=Jle;function Zle(){var e=(0,Xle.getGlobal)();return typeof e.navigator=="object"&&e.navigator.product==="ReactNative"}s(Zle,"isReactNative");var iU=s(function(t){var r=Zle()?"BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.":"BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.";console.warn(r);for(var n=QT.Buffer.alloc(t),i=0;i{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});mm.ensureBuffer=void 0;var oU=require("buffer"),che=Nn(),fhe=Wn();function lhe(e){if(ArrayBuffer.isView(e))return oU.Buffer.from(e.buffer,e.byteOffset,e.byteLength);if((0,fhe.isAnyArrayBuffer)(e))return oU.Buffer.from(e);throw new che.BSONTypeError("Must use either Buffer or TypedArray")}s(lhe,"ensureBuffer");mm.ensureBuffer=lhe});var aU=E(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.bufferToUuidHexString=Vi.uuidHexStringToBuffer=Vi.uuidValidateString=void 0;var hhe=require("buffer"),dhe=Nn(),phe=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i,mhe=s(function(e){return typeof e=="string"&&phe.test(e)},"uuidValidateString");Vi.uuidValidateString=mhe;var ghe=s(function(e){if(!(0,Vi.uuidValidateString)(e))throw new dhe.BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');var t=e.replace(/-/g,"");return hhe.Buffer.from(t,"hex")},"uuidHexStringToBuffer");Vi.uuidHexStringToBuffer=ghe;var yhe=s(function(e,t){return t===void 0&&(t=!0),t?e.toString("hex",0,4)+"-"+e.toString("hex",4,6)+"-"+e.toString("hex",6,8)+"-"+e.toString("hex",8,10)+"-"+e.toString("hex",10,16):e.toString("hex")},"bufferToUuidHexString");Vi.bufferToUuidHexString=yhe});var vu=E(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.BSON_BINARY_SUBTYPE_USER_DEFINED=Q.BSON_BINARY_SUBTYPE_COLUMN=Q.BSON_BINARY_SUBTYPE_ENCRYPTED=Q.BSON_BINARY_SUBTYPE_MD5=Q.BSON_BINARY_SUBTYPE_UUID_NEW=Q.BSON_BINARY_SUBTYPE_UUID=Q.BSON_BINARY_SUBTYPE_BYTE_ARRAY=Q.BSON_BINARY_SUBTYPE_FUNCTION=Q.BSON_BINARY_SUBTYPE_DEFAULT=Q.BSON_DATA_MAX_KEY=Q.BSON_DATA_MIN_KEY=Q.BSON_DATA_DECIMAL128=Q.BSON_DATA_LONG=Q.BSON_DATA_TIMESTAMP=Q.BSON_DATA_INT=Q.BSON_DATA_CODE_W_SCOPE=Q.BSON_DATA_SYMBOL=Q.BSON_DATA_CODE=Q.BSON_DATA_DBPOINTER=Q.BSON_DATA_REGEXP=Q.BSON_DATA_NULL=Q.BSON_DATA_DATE=Q.BSON_DATA_BOOLEAN=Q.BSON_DATA_OID=Q.BSON_DATA_UNDEFINED=Q.BSON_DATA_BINARY=Q.BSON_DATA_ARRAY=Q.BSON_DATA_OBJECT=Q.BSON_DATA_STRING=Q.BSON_DATA_NUMBER=Q.JS_INT_MIN=Q.JS_INT_MAX=Q.BSON_INT64_MIN=Q.BSON_INT64_MAX=Q.BSON_INT32_MIN=Q.BSON_INT32_MAX=void 0;Q.BSON_INT32_MAX=2147483647;Q.BSON_INT32_MIN=-2147483648;Q.BSON_INT64_MAX=Math.pow(2,63)-1;Q.BSON_INT64_MIN=-Math.pow(2,63);Q.JS_INT_MAX=Math.pow(2,53);Q.JS_INT_MIN=-Math.pow(2,53);Q.BSON_DATA_NUMBER=1;Q.BSON_DATA_STRING=2;Q.BSON_DATA_OBJECT=3;Q.BSON_DATA_ARRAY=4;Q.BSON_DATA_BINARY=5;Q.BSON_DATA_UNDEFINED=6;Q.BSON_DATA_OID=7;Q.BSON_DATA_BOOLEAN=8;Q.BSON_DATA_DATE=9;Q.BSON_DATA_NULL=10;Q.BSON_DATA_REGEXP=11;Q.BSON_DATA_DBPOINTER=12;Q.BSON_DATA_CODE=13;Q.BSON_DATA_SYMBOL=14;Q.BSON_DATA_CODE_W_SCOPE=15;Q.BSON_DATA_INT=16;Q.BSON_DATA_TIMESTAMP=17;Q.BSON_DATA_LONG=18;Q.BSON_DATA_DECIMAL128=19;Q.BSON_DATA_MIN_KEY=255;Q.BSON_DATA_MAX_KEY=127;Q.BSON_BINARY_SUBTYPE_DEFAULT=0;Q.BSON_BINARY_SUBTYPE_FUNCTION=1;Q.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;Q.BSON_BINARY_SUBTYPE_UUID=3;Q.BSON_BINARY_SUBTYPE_UUID_NEW=4;Q.BSON_BINARY_SUBTYPE_MD5=5;Q.BSON_BINARY_SUBTYPE_ENCRYPTED=6;Q.BSON_BINARY_SUBTYPE_COLUMN=7;Q.BSON_BINARY_SUBTYPE_USER_DEFINED=128});var Eu=E(Fs=>{"use strict";var She=Fs&&Fs.__extends||function(){var e=s(function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},e(t,r)},"extendStatics");return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}s(n,"__"),t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(Fs,"__esModule",{value:!0});Fs.UUID=Fs.Binary=void 0;var Yi=require("buffer"),tN=Pf(),Ou=aU(),uU=Wn(),Wo=Nn(),cU=vu(),Lf=function(){function e(t,r){if(!(this instanceof e))return new e(t,r);if(t!=null&&typeof t!="string"&&!ArrayBuffer.isView(t)&&!(t instanceof ArrayBuffer)&&!Array.isArray(t))throw new Wo.BSONTypeError("Binary can only be constructed from string, Buffer, TypedArray, or Array");this.sub_type=r??e.BSON_BINARY_SUBTYPE_DEFAULT,t==null?(this.buffer=Yi.Buffer.alloc(e.BUFFER_SIZE),this.position=0):(typeof t=="string"?this.buffer=Yi.Buffer.from(t,"binary"):Array.isArray(t)?this.buffer=Yi.Buffer.from(t):this.buffer=(0,tN.ensureBuffer)(t),this.position=this.buffer.byteLength)}return s(e,"Binary"),e.prototype.put=function(t){if(typeof t=="string"&&t.length!==1)throw new Wo.BSONTypeError("only accepts single character String");if(typeof t!="number"&&t.length!==1)throw new Wo.BSONTypeError("only accepts single character Uint8Array or Array");var r;if(typeof t=="string"?r=t.charCodeAt(0):typeof t=="number"?r=t:r=t[0],r<0||r>255)throw new Wo.BSONTypeError("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.length>this.position)this.buffer[this.position++]=r;else{var n=Yi.Buffer.alloc(e.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=r}},e.prototype.write=function(t,r){if(r=typeof r=="number"?r:this.position,this.buffer.lengththis.position?r+t.length:this.position):typeof t=="string"&&(this.buffer.write(t,r,t.length,"binary"),this.position=r+t.length>this.position?r+t.length:this.position)},e.prototype.read=function(t,r){return r=r&&r>0?r:this.position,this.buffer.slice(t,t+r)},e.prototype.value=function(t){return t=!!t,t&&this.buffer.length===this.position?this.buffer:t?this.buffer.slice(0,this.position):this.buffer.toString("binary",0,this.position)},e.prototype.length=function(){return this.position},e.prototype.toJSON=function(){return this.buffer.toString("base64")},e.prototype.toString=function(t){return this.buffer.toString(t)},e.prototype.toExtendedJSON=function(t){t=t||{};var r=this.buffer.toString("base64"),n=Number(this.sub_type).toString(16);return t.legacy?{$binary:r,$type:n.length===1?"0"+n:n}:{$binary:{base64:r,subType:n.length===1?"0"+n:n}}},e.prototype.toUUID=function(){if(this.sub_type===e.SUBTYPE_UUID)return new rN(this.buffer.slice(0,this.position));throw new Wo.BSONError('Binary sub_type "'.concat(this.sub_type,'" is not supported for converting to UUID. Only "').concat(e.SUBTYPE_UUID,'" is currently supported.'))},e.fromExtendedJSON=function(t,r){r=r||{};var n,i;if("$binary"in t?r.legacy&&typeof t.$binary=="string"&&"$type"in t?(i=t.$type?parseInt(t.$type,16):0,n=Yi.Buffer.from(t.$binary,"base64")):typeof t.$binary!="string"&&(i=t.$binary.subType?parseInt(t.$binary.subType,16):0,n=Yi.Buffer.from(t.$binary.base64,"base64")):"$uuid"in t&&(i=4,n=(0,Ou.uuidHexStringToBuffer)(t.$uuid)),!n)throw new Wo.BSONTypeError("Unexpected Binary Extended JSON format ".concat(JSON.stringify(t)));return i===cU.BSON_BINARY_SUBTYPE_UUID_NEW?new rN(n):new e(n,i)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.value(!0);return'new Binary(Buffer.from("'.concat(t.toString("hex"),'", "hex"), ').concat(this.sub_type,")")},e.BSON_BINARY_SUBTYPE_DEFAULT=0,e.BUFFER_SIZE=256,e.SUBTYPE_DEFAULT=0,e.SUBTYPE_FUNCTION=1,e.SUBTYPE_BYTE_ARRAY=2,e.SUBTYPE_UUID_OLD=3,e.SUBTYPE_UUID=4,e.SUBTYPE_MD5=5,e.SUBTYPE_ENCRYPTED=6,e.SUBTYPE_COLUMN=7,e.SUBTYPE_USER_DEFINED=128,e}();Fs.Binary=Lf;Object.defineProperty(Lf.prototype,"_bsontype",{value:"Binary"});var eN=16,rN=function(e){She(t,e);function t(r){var n=this,i,a;if(r==null)i=t.generate();else if(r instanceof t)i=Yi.Buffer.from(r.buffer),a=r.__id;else if(ArrayBuffer.isView(r)&&r.byteLength===eN)i=(0,tN.ensureBuffer)(r);else if(typeof r=="string")i=(0,Ou.uuidHexStringToBuffer)(r);else throw new Wo.BSONTypeError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");return n=e.call(this,i,cU.BSON_BINARY_SUBTYPE_UUID_NEW)||this,n.__id=a,n}return s(t,"UUID"),Object.defineProperty(t.prototype,"id",{get:function(){return this.buffer},set:function(r){this.buffer=r,t.cacheHexString&&(this.__id=(0,Ou.bufferToUuidHexString)(r))},enumerable:!1,configurable:!0}),t.prototype.toHexString=function(r){if(r===void 0&&(r=!0),t.cacheHexString&&this.__id)return this.__id;var n=(0,Ou.bufferToUuidHexString)(this.id,r);return t.cacheHexString&&(this.__id=n),n},t.prototype.toString=function(r){return r?this.id.toString(r):this.toHexString()},t.prototype.toJSON=function(){return this.toHexString()},t.prototype.equals=function(r){if(!r)return!1;if(r instanceof t)return r.id.equals(this.id);try{return new t(r).id.equals(this.id)}catch{return!1}},t.prototype.toBinary=function(){return new Lf(this.id,Lf.SUBTYPE_UUID)},t.generate=function(){var r=(0,uU.randomBytes)(eN);return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Yi.Buffer.from(r)},t.isValid=function(r){return r?r instanceof t?!0:typeof r=="string"?(0,Ou.uuidValidateString)(r):(0,uU.isUint8Array)(r)?r.length!==eN?!1:(r[6]&240)===64&&(r[8]&128)===128:!1:!1},t.createFromHexString=function(r){var n=(0,Ou.uuidHexStringToBuffer)(r);return new t(n)},t.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},t.prototype.inspect=function(){return'new UUID("'.concat(this.toHexString(),'")')},t}(Lf);Fs.UUID=rN});var ym=E(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});gm.Code=void 0;var fU=function(){function e(t,r){if(!(this instanceof e))return new e(t,r);this.code=t,this.scope=r}return s(e,"Code"),e.prototype.toJSON=function(){return{code:this.code,scope:this.scope}},e.prototype.toExtendedJSON=function(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}},e.fromExtendedJSON=function(t){return new e(t.$code,t.$scope)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.toJSON();return'new Code("'.concat(String(t.code),'"').concat(t.scope?", ".concat(JSON.stringify(t.scope)):"",")")},e}();gm.Code=fU;Object.defineProperty(fU.prototype,"_bsontype",{value:"Code"})});var Sm=E(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.DBRef=Tu.isDBRefLike=void 0;var _he=Wn();function whe(e){return(0,_he.isObjectLike)(e)&&e.$id!=null&&typeof e.$ref=="string"&&(e.$db==null||typeof e.$db=="string")}s(whe,"isDBRefLike");Tu.isDBRefLike=whe;var lU=function(){function e(t,r,n,i){if(!(this instanceof e))return new e(t,r,n,i);var a=t.split(".");a.length===2&&(n=a.shift(),t=a.shift()),this.collection=t,this.oid=r,this.db=n,this.fields=i||{}}return s(e,"DBRef"),Object.defineProperty(e.prototype,"namespace",{get:function(){return this.collection},set:function(t){this.collection=t},enumerable:!1,configurable:!0}),e.prototype.toJSON=function(){var t=Object.assign({$ref:this.collection,$id:this.oid},this.fields);return this.db!=null&&(t.$db=this.db),t},e.prototype.toExtendedJSON=function(t){t=t||{};var r={$ref:this.collection,$id:this.oid};return t.legacy||(this.db&&(r.$db=this.db),r=Object.assign(r,this.fields)),r},e.fromExtendedJSON=function(t){var r=Object.assign({},t);return delete r.$ref,delete r.$id,delete r.$db,new e(t.$ref,t.$id,t.$db,r)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return'new DBRef("'.concat(this.namespace,'", new ObjectId("').concat(String(t),'")').concat(this.db?', "'.concat(this.db,'"'):"",")")},e}();Tu.DBRef=lU;Object.defineProperty(lU.prototype,"_bsontype",{value:"DBRef"})});var Fo=E(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});_m.Long=void 0;var vhe=Wn(),bn=void 0;try{bn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var hU=65536,Ohe=1<<24,Nu=hU*hU,gU=Nu*Nu,dU=gU/2,pU={},mU={},nN=function(){function e(t,r,n){if(t===void 0&&(t=0),!(this instanceof e))return new e(t,r,n);typeof t=="bigint"?Object.assign(this,e.fromBigInt(t,!!r)):typeof t=="string"?Object.assign(this,e.fromString(t,!!r)):(this.low=t|0,this.high=r|0,this.unsigned=!!n),Object.defineProperty(this,"__isLong__",{value:!0,configurable:!1,writable:!1,enumerable:!1})}return s(e,"Long"),e.fromBits=function(t,r,n){return new e(t,r,n)},e.fromInt=function(t,r){var n,i,a;return r?(t>>>=0,(a=0<=t&&t<256)&&(i=mU[t],i)?i:(n=e.fromBits(t,(t|0)<0?-1:0,!0),a&&(mU[t]=n),n)):(t|=0,(a=-128<=t&&t<128)&&(i=pU[t],i)?i:(n=e.fromBits(t,t<0?-1:0,!1),a&&(pU[t]=n),n))},e.fromNumber=function(t,r){if(isNaN(t))return r?e.UZERO:e.ZERO;if(r){if(t<0)return e.UZERO;if(t>=gU)return e.MAX_UNSIGNED_VALUE}else{if(t<=-dU)return e.MIN_VALUE;if(t+1>=dU)return e.MAX_VALUE}return t<0?e.fromNumber(-t,r).neg():e.fromBits(t%Nu|0,t/Nu|0,r)},e.fromBigInt=function(t,r){return e.fromString(t.toString(),r)},e.fromString=function(t,r,n){if(t.length===0)throw Error("empty string");if(t==="NaN"||t==="Infinity"||t==="+Infinity"||t==="-Infinity")return e.ZERO;if(typeof r=="number"?(n=r,r=!1):r=!!r,n=n||10,n<2||360)throw Error("interior hyphen");if(i===0)return e.fromString(t.substring(1),r,n).neg();for(var a=e.fromNumber(Math.pow(n,8)),u=e.ZERO,f=0;f>>16,n=this.high&65535,i=this.low>>>16,a=this.low&65535,u=t.high>>>16,f=t.high&65535,l=t.low>>>16,h=t.low&65535,m=0,p=0,g=0,w=0;return w+=a+h,g+=w>>>16,w&=65535,g+=i+l,p+=g>>>16,g&=65535,p+=n+f,m+=p>>>16,p&=65535,m+=r+u,m&=65535,e.fromBits(g<<16|w,m<<16|p,this.unsigned)},e.prototype.and=function(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low&t.low,this.high&t.high,this.unsigned)},e.prototype.compare=function(t){if(e.isLong(t)||(t=e.fromValue(t)),this.eq(t))return 0;var r=this.isNegative(),n=t.isNegative();return r&&!n?-1:!r&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},e.prototype.comp=function(t){return this.compare(t)},e.prototype.divide=function(t){if(e.isLong(t)||(t=e.fromValue(t)),t.isZero())throw Error("division by zero");if(bn){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var r=(this.unsigned?bn.div_u:bn.div_s)(this.low,this.high,t.low,t.high);return e.fromBits(r,bn.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?e.UZERO:e.ZERO;var n,i,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return e.UZERO;if(t.gt(this.shru(1)))return e.UONE;a=e.UZERO}else{if(this.eq(e.MIN_VALUE)){if(t.eq(e.ONE)||t.eq(e.NEG_ONE))return e.MIN_VALUE;if(t.eq(e.MIN_VALUE))return e.ONE;var u=this.shr(1);return n=u.div(t).shl(1),n.eq(e.ZERO)?t.isNegative()?e.ONE:e.NEG_ONE:(i=this.sub(t.mul(n)),a=n.add(i.div(t)),a)}else if(t.eq(e.MIN_VALUE))return this.unsigned?e.UZERO:e.ZERO;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=e.ZERO}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var f=Math.ceil(Math.log(n)/Math.LN2),l=f<=48?1:Math.pow(2,f-48),h=e.fromNumber(n),m=h.mul(t);m.isNegative()||m.gt(i);)n-=l,h=e.fromNumber(n,this.unsigned),m=h.mul(t);h.isZero()&&(h=e.ONE),a=a.add(h),i=i.sub(m)}return a},e.prototype.div=function(t){return this.divide(t)},e.prototype.equals=function(t){return e.isLong(t)||(t=e.fromValue(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low},e.prototype.eq=function(t){return this.equals(t)},e.prototype.getHighBits=function(){return this.high},e.prototype.getHighBitsUnsigned=function(){return this.high>>>0},e.prototype.getLowBits=function(){return this.low},e.prototype.getLowBitsUnsigned=function(){return this.low>>>0},e.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.eq(e.MIN_VALUE)?64:this.neg().getNumBitsAbs();var t=this.high!==0?this.high:this.low,r;for(r=31;r>0&&!(t&1<0},e.prototype.gt=function(t){return this.greaterThan(t)},e.prototype.greaterThanOrEqual=function(t){return this.comp(t)>=0},e.prototype.gte=function(t){return this.greaterThanOrEqual(t)},e.prototype.ge=function(t){return this.greaterThanOrEqual(t)},e.prototype.isEven=function(){return(this.low&1)===0},e.prototype.isNegative=function(){return!this.unsigned&&this.high<0},e.prototype.isOdd=function(){return(this.low&1)===1},e.prototype.isPositive=function(){return this.unsigned||this.high>=0},e.prototype.isZero=function(){return this.high===0&&this.low===0},e.prototype.lessThan=function(t){return this.comp(t)<0},e.prototype.lt=function(t){return this.lessThan(t)},e.prototype.lessThanOrEqual=function(t){return this.comp(t)<=0},e.prototype.lte=function(t){return this.lessThanOrEqual(t)},e.prototype.modulo=function(t){if(e.isLong(t)||(t=e.fromValue(t)),bn){var r=(this.unsigned?bn.rem_u:bn.rem_s)(this.low,this.high,t.low,t.high);return e.fromBits(r,bn.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},e.prototype.mod=function(t){return this.modulo(t)},e.prototype.rem=function(t){return this.modulo(t)},e.prototype.multiply=function(t){if(this.isZero())return e.ZERO;if(e.isLong(t)||(t=e.fromValue(t)),bn){var r=bn.mul(this.low,this.high,t.low,t.high);return e.fromBits(r,bn.get_high(),this.unsigned)}if(t.isZero())return e.ZERO;if(this.eq(e.MIN_VALUE))return t.isOdd()?e.MIN_VALUE:e.ZERO;if(t.eq(e.MIN_VALUE))return this.isOdd()?e.MIN_VALUE:e.ZERO;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(e.TWO_PWR_24)&&t.lt(e.TWO_PWR_24))return e.fromNumber(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=this.high&65535,a=this.low>>>16,u=this.low&65535,f=t.high>>>16,l=t.high&65535,h=t.low>>>16,m=t.low&65535,p=0,g=0,w=0,O=0;return O+=u*m,w+=O>>>16,O&=65535,w+=a*m,g+=w>>>16,w&=65535,w+=u*h,g+=w>>>16,w&=65535,g+=i*m,p+=g>>>16,g&=65535,g+=a*h,p+=g>>>16,g&=65535,g+=u*l,p+=g>>>16,g&=65535,p+=n*m+i*h+a*l+u*f,p&=65535,e.fromBits(w<<16|O,p<<16|g,this.unsigned)},e.prototype.mul=function(t){return this.multiply(t)},e.prototype.negate=function(){return!this.unsigned&&this.eq(e.MIN_VALUE)?e.MIN_VALUE:this.not().add(e.ONE)},e.prototype.neg=function(){return this.negate()},e.prototype.not=function(){return e.fromBits(~this.low,~this.high,this.unsigned)},e.prototype.notEquals=function(t){return!this.equals(t)},e.prototype.neq=function(t){return this.notEquals(t)},e.prototype.ne=function(t){return this.notEquals(t)},e.prototype.or=function(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low|t.low,this.high|t.high,this.unsigned)},e.prototype.shiftLeft=function(t){return e.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?e.fromBits(this.low<>>32-t,this.unsigned):e.fromBits(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):e.fromBits(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},e.prototype.shr=function(t){return this.shiftRight(t)},e.prototype.shiftRightUnsigned=function(t){if(e.isLong(t)&&(t=t.toInt()),t&=63,t===0)return this;var r=this.high;if(t<32){var n=this.low;return e.fromBits(n>>>t|r<<32-t,r>>>t,this.unsigned)}else return t===32?e.fromBits(r,0,this.unsigned):e.fromBits(r>>>t-32,0,this.unsigned)},e.prototype.shr_u=function(t){return this.shiftRightUnsigned(t)},e.prototype.shru=function(t){return this.shiftRightUnsigned(t)},e.prototype.subtract=function(t){return e.isLong(t)||(t=e.fromValue(t)),this.add(t.neg())},e.prototype.sub=function(t){return this.subtract(t)},e.prototype.toInt=function(){return this.unsigned?this.low>>>0:this.low},e.prototype.toNumber=function(){return this.unsigned?(this.high>>>0)*Nu+(this.low>>>0):this.high*Nu+(this.low>>>0)},e.prototype.toBigInt=function(){return BigInt(this.toString())},e.prototype.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},e.prototype.toBytesLE=function(){var t=this.high,r=this.low;return[r&255,r>>>8&255,r>>>16&255,r>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]},e.prototype.toBytesBE=function(){var t=this.high,r=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,r>>>24,r>>>16&255,r>>>8&255,r&255]},e.prototype.toSigned=function(){return this.unsigned?e.fromBits(this.low,this.high,!1):this},e.prototype.toString=function(t){if(t=t||10,t<2||36>>0,m=h.toString(t);if(u=l,u.isZero())return m+f;for(;m.length<6;)m="0"+m;f=""+m+f}},e.prototype.toUnsigned=function(){return this.unsigned?this:e.fromBits(this.low,this.high,!0)},e.prototype.xor=function(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low^t.low,this.high^t.high,this.unsigned)},e.prototype.eqz=function(){return this.isZero()},e.prototype.le=function(t){return this.lessThanOrEqual(t)},e.prototype.toExtendedJSON=function(t){return t&&t.relaxed?this.toNumber():{$numberLong:this.toString()}},e.fromExtendedJSON=function(t,r){var n=e.fromString(t.$numberLong);return r&&r.relaxed?n.toNumber():n},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return'new Long("'.concat(this.toString(),'"').concat(this.unsigned?", true":"",")")},e.TWO_PWR_24=e.fromInt(Ohe),e.MAX_UNSIGNED_VALUE=e.fromBits(-1,-1,!0),e.ZERO=e.fromInt(0),e.UZERO=e.fromInt(0,!0),e.ONE=e.fromInt(1),e.UONE=e.fromInt(1,!0),e.NEG_ONE=e.fromInt(-1),e.MAX_VALUE=e.fromBits(-1,2147483647,!1),e.MIN_VALUE=e.fromBits(0,-2147483648,!1),e}();_m.Long=nN;Object.defineProperty(nN.prototype,"__isLong__",{value:!0});Object.defineProperty(nN.prototype,"_bsontype",{value:"Long"})});var vm=E(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});wm.Decimal128=void 0;var bu=require("buffer"),Cu=Nn(),Ne=Fo(),Ehe=Wn(),The=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,Nhe=/^(\+|-)?(Infinity|inf)$/i,bhe=/^(\+|-)?NaN$/i,Uf=6111,iN=-6176,yU=6176,Ahe=34,sN=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),SU=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),_U=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),Che=/^([-+])?(\d+)?$/,Ihe=31,wU=16383,Bhe=30,Rhe=31;function vU(e){return!isNaN(parseInt(e,10))}s(vU,"isDigit");function xhe(e){var t=Ne.Long.fromNumber(1e9),r=Ne.Long.fromNumber(0);if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3])return{quotient:e,rem:r};for(var n=0;n<=3;n++)r=r.shiftLeft(32),r=r.add(new Ne.Long(e.parts[n],0)),e.parts[n]=r.div(t).low,r=r.modulo(t);return{quotient:e,rem:r}}s(xhe,"divideu128");function Mhe(e,t){if(!e&&!t)return{high:Ne.Long.fromNumber(0),low:Ne.Long.fromNumber(0)};var r=e.shiftRightUnsigned(32),n=new Ne.Long(e.getLowBits(),0),i=t.shiftRightUnsigned(32),a=new Ne.Long(t.getLowBits(),0),u=r.multiply(i),f=r.multiply(a),l=n.multiply(i),h=n.multiply(a);return u=u.add(f.shiftRightUnsigned(32)),f=new Ne.Long(f.getLowBits(),0).add(l).add(h.shiftRightUnsigned(32)),u=u.add(f.shiftRightUnsigned(32)),h=f.shiftLeft(32).add(new Ne.Long(h.getLowBits(),0)),{high:u,low:h}}s(Mhe,"multiply64x2");function Dhe(e,t){var r=e.high>>>0,n=t.high>>>0;if(r>>0,a=t.low>>>0;if(i=7e3)throw new Cu.BSONTypeError(""+t+" not a valid Decimal128 string");var Y=t.match(The),W=t.match(Nhe),ee=t.match(bhe);if(!Y&&!W&&!ee||t.length===0)throw new Cu.BSONTypeError(""+t+" not a valid Decimal128 string");if(Y){var Ee=Y[2],V=Y[4],fe=Y[5],ne=Y[6];V&&ne===void 0&&Au(t,"missing exponent power"),V&&Ee===void 0&&Au(t,"missing exponent base"),V===void 0&&(fe||ne)&&Au(t,"missing e before exponent")}if((t[R]==="+"||t[R]==="-")&&(r=t[R++]==="-"),!vU(t[R])&&t[R]!=="."){if(t[R]==="i"||t[R]==="I")return new e(bu.Buffer.from(r?SU:_U));if(t[R]==="N")return new e(bu.Buffer.from(sN))}for(;vU(t[R])||t[R]===".";){if(t[R]==="."){n&&Au(t,"contains multiple periods"),n=!0,R=R+1;continue}p<34&&(t[R]!=="0"||i)&&(i||(h=u),i=!0,m[g++]=parseInt(t[R],10),p=p+1),i&&(f=f+1),n&&(l=l+1),u=u+1,R=R+1}if(n&&!u)throw new Cu.BSONTypeError(""+t+" not a valid Decimal128 string");if(t[R]==="e"||t[R]==="E"){var J=t.substr(++R).match(Che);if(!J||!J[2])return new e(bu.Buffer.from(sN));N=parseInt(J[0],10),R=R+J[0].length}if(t[R])return new e(bu.Buffer.from(sN));if(w=0,!p)w=0,O=0,m[0]=0,f=1,p=1,a=0;else if(O=p-1,a=f,a!==1)for(;m[h+a-1]===0;)a=a-1;for(N<=l&&l-N>16384?N=iN:N=N-l;N>Uf;){if(O=O+1,O-w>Ahe){var K=m.join("");if(K.match(/^0+$/)){N=Uf;break}Au(t,"overflow")}N=N-1}for(;N=5&&(oe=1,me===5)){for(oe=m[O]%2===1?1:0,A=h+O+2;A=0;ae--)if(++m[ae]>9&&(m[ae]=0,ae===0))if(N>8&255,Ke[R++]=le.low.low>>16&255,Ke[R++]=le.low.low>>24&255,Ke[R++]=le.low.high&255,Ke[R++]=le.low.high>>8&255,Ke[R++]=le.low.high>>16&255,Ke[R++]=le.low.high>>24&255,Ke[R++]=le.high.low&255,Ke[R++]=le.high.low>>8&255,Ke[R++]=le.high.low>>16&255,Ke[R++]=le.high.low>>24&255,Ke[R++]=le.high.high&255,Ke[R++]=le.high.high>>8&255,Ke[R++]=le.high.high>>16&255,Ke[R++]=le.high.high>>24&255,new e(Ke)},e.prototype.toString=function(){for(var t,r=0,n=new Array(36),i=0;i>26&Ihe;if(L>>3===3){if(L===Bhe)return p.join("")+"Infinity";if(L===Rhe)return"NaN";t=A>>15&wU,f=8+(A>>14&1)}else f=A>>14&7,t=A>>17&wU;var I=t-yU;if(l.parts[0]=(A&16383)+((f&15)<<14),l.parts[1]=N,l.parts[2]=O,l.parts[3]=w,l.parts[0]===0&&l.parts[1]===0&&l.parts[2]===0&&l.parts[3]===0)u=!0;else for(m=3;m>=0;m--){var R=0,Y=xhe(l);if(l=Y.quotient,R=Y.rem.low,!!R)for(h=8;h>=0;h--)n[m*9+h]=R%10,R=Math.floor(R/10)}if(u)r=1,n[a]=0;else for(r=36;!n[a];)r=r-1,a=a+1;var W=r-1+I;if(W>=34||W<=-7||I>0){if(r>34)return p.push("".concat(0)),I>0?p.push("E+".concat(I)):I<0&&p.push("E".concat(I)),p.join("");p.push("".concat(n[a++])),r=r-1,r&&p.push(".");for(var i=0;i0?p.push("+".concat(W)):p.push("".concat(W))}else if(I>=0)for(var i=0;i0)for(var i=0;i{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});Om.Double=void 0;var EU=function(){function e(t){if(!(this instanceof e))return new e(t);t instanceof Number&&(t=t.valueOf()),this.value=+t}return s(e,"Double"),e.prototype.valueOf=function(){return this.value},e.prototype.toJSON=function(){return this.value},e.prototype.toString=function(t){return this.value.toString(t)},e.prototype.toExtendedJSON=function(t){return t&&(t.legacy||t.relaxed&&isFinite(this.value))?this.value:Object.is(Math.sign(this.value),-0)?{$numberDouble:"-".concat(this.value.toFixed(1))}:{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}},e.fromExtendedJSON=function(t,r){var n=parseFloat(t.$numberDouble);return r&&r.relaxed?n:new e(n)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.toExtendedJSON();return"new Double(".concat(t.$numberDouble,")")},e}();Om.Double=EU;Object.defineProperty(EU.prototype,"_bsontype",{value:"Double"})});var Nm=E(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.Int32=void 0;var TU=function(){function e(t){if(!(this instanceof e))return new e(t);t instanceof Number&&(t=t.valueOf()),this.value=+t|0}return s(e,"Int32"),e.prototype.valueOf=function(){return this.value},e.prototype.toString=function(t){return this.value.toString(t)},e.prototype.toJSON=function(){return this.value},e.prototype.toExtendedJSON=function(t){return t&&(t.relaxed||t.legacy)?this.value:{$numberInt:this.value.toString()}},e.fromExtendedJSON=function(t,r){return r&&r.relaxed?parseInt(t.$numberInt,10):new e(t.$numberInt)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return"new Int32(".concat(this.valueOf(),")")},e}();Tm.Int32=TU;Object.defineProperty(TU.prototype,"_bsontype",{value:"Int32"})});var Am=E(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});bm.MaxKey=void 0;var NU=function(){function e(){if(!(this instanceof e))return new e}return s(e,"MaxKey"),e.prototype.toExtendedJSON=function(){return{$maxKey:1}},e.fromExtendedJSON=function(){return new e},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return"new MaxKey()"},e}();bm.MaxKey=NU;Object.defineProperty(NU.prototype,"_bsontype",{value:"MaxKey"})});var Im=E(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});Cm.MinKey=void 0;var bU=function(){function e(){if(!(this instanceof e))return new e}return s(e,"MinKey"),e.prototype.toExtendedJSON=function(){return{$minKey:1}},e.fromExtendedJSON=function(){return new e},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return"new MinKey()"},e}();Cm.MinKey=bU;Object.defineProperty(bU.prototype,"_bsontype",{value:"MinKey"})});var Rm=E(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.ObjectId=void 0;var ki=require("buffer"),qhe=Pf(),jf=Nn(),Iu=Wn(),Phe=new RegExp("^[0-9a-fA-F]{24}$"),$o=null,ai=Symbol("id"),ui=function(){function e(t){if(!(this instanceof e))return new e(t);var r;if(typeof t=="object"&&t&&"id"in t){if(typeof t.id!="string"&&!ArrayBuffer.isView(t.id))throw new jf.BSONTypeError("Argument passed in must have an id that is of type string or Buffer");"toHexString"in t&&typeof t.toHexString=="function"?r=ki.Buffer.from(t.toHexString(),"hex"):r=t.id}else r=t;if(r==null||typeof r=="number")this[ai]=e.generate(typeof r=="number"?r:void 0);else if(ArrayBuffer.isView(r)&&r.byteLength===12)this[ai]=r instanceof ki.Buffer?r:(0,qhe.ensureBuffer)(r);else if(typeof r=="string")if(r.length===12){var n=ki.Buffer.from(r);if(n.byteLength===12)this[ai]=n;else throw new jf.BSONTypeError("Argument passed in must be a string of 12 bytes")}else if(r.length===24&&Phe.test(r))this[ai]=ki.Buffer.from(r,"hex");else throw new jf.BSONTypeError("Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer");else throw new jf.BSONTypeError("Argument passed in does not match the accepted types");e.cacheHexString&&(this.__id=this.id.toString("hex"))}return s(e,"ObjectId"),Object.defineProperty(e.prototype,"id",{get:function(){return this[ai]},set:function(t){this[ai]=t,e.cacheHexString&&(this.__id=t.toString("hex"))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"generationTime",{get:function(){return this.id.readInt32BE(0)},set:function(t){this.id.writeUInt32BE(t,0)},enumerable:!1,configurable:!0}),e.prototype.toHexString=function(){if(e.cacheHexString&&this.__id)return this.__id;var t=this.id.toString("hex");return e.cacheHexString&&!this.__id&&(this.__id=t),t},e.getInc=function(){return e.index=(e.index+1)%16777215},e.generate=function(t){typeof t!="number"&&(t=Math.floor(Date.now()/1e3));var r=e.getInc(),n=ki.Buffer.alloc(12);return n.writeUInt32BE(t,0),$o===null&&($o=(0,Iu.randomBytes)(5)),n[4]=$o[0],n[5]=$o[1],n[6]=$o[2],n[7]=$o[3],n[8]=$o[4],n[11]=r&255,n[10]=r>>8&255,n[9]=r>>16&255,n},e.prototype.toString=function(t){return t?this.id.toString(t):this.toHexString()},e.prototype.toJSON=function(){return this.toHexString()},e.prototype.equals=function(t){if(t==null)return!1;if(t instanceof e)return this[ai][11]===t[ai][11]&&this[ai].equals(t[ai]);if(typeof t=="string"&&e.isValid(t)&&t.length===12&&(0,Iu.isUint8Array)(this.id))return t===ki.Buffer.prototype.toString.call(this.id,"latin1");if(typeof t=="string"&&e.isValid(t)&&t.length===24)return t.toLowerCase()===this.toHexString();if(typeof t=="string"&&e.isValid(t)&&t.length===12)return ki.Buffer.from(t).equals(this.id);if(typeof t=="object"&&"toHexString"in t&&typeof t.toHexString=="function"){var r=t.toHexString(),n=this.toHexString().toLowerCase();return typeof r=="string"&&r.toLowerCase()===n}return!1},e.prototype.getTimestamp=function(){var t=new Date,r=this.id.readUInt32BE(0);return t.setTime(Math.floor(r)*1e3),t},e.createPk=function(){return new e},e.createFromTime=function(t){var r=ki.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0]);return r.writeUInt32BE(t,0),new e(r)},e.createFromHexString=function(t){if(typeof t>"u"||t!=null&&t.length!==24)throw new jf.BSONTypeError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");return new e(ki.Buffer.from(t,"hex"))},e.isValid=function(t){if(t==null)return!1;try{return new e(t),!0}catch{return!1}},e.prototype.toExtendedJSON=function(){return this.toHexString?{$oid:this.toHexString()}:{$oid:this.toString("hex")}},e.fromExtendedJSON=function(t){return new e(t.$oid)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return'new ObjectId("'.concat(this.toHexString(),'")')},e.index=Math.floor(Math.random()*16777215),e}();Bm.ObjectId=ui;Object.defineProperty(ui.prototype,"generate",{value:(0,Iu.deprecate)(function(e){return ui.generate(e)},"Please use the static `ObjectId.generate(time)` instead")});Object.defineProperty(ui.prototype,"getInc",{value:(0,Iu.deprecate)(function(){return ui.getInc()},"Please use the static `ObjectId.getInc()` instead")});Object.defineProperty(ui.prototype,"get_inc",{value:(0,Iu.deprecate)(function(){return ui.getInc()},"Please use the static `ObjectId.getInc()` instead")});Object.defineProperty(ui,"get_inc",{value:(0,Iu.deprecate)(function(){return ui.getInc()},"Please use the static `ObjectId.getInc()` instead")});Object.defineProperty(ui.prototype,"_bsontype",{value:"ObjectID"})});var Dm=E(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});Mm.BSONRegExp=void 0;var xm=Nn();function Lhe(e){return e.split("").sort().join("")}s(Lhe,"alphabetize");var AU=function(){function e(t,r){if(!(this instanceof e))return new e(t,r);if(this.pattern=t,this.options=Lhe(r??""),this.pattern.indexOf("\0")!==-1)throw new xm.BSONError("BSON Regex patterns cannot contain null bytes, found: ".concat(JSON.stringify(this.pattern)));if(this.options.indexOf("\0")!==-1)throw new xm.BSONError("BSON Regex options cannot contain null bytes, found: ".concat(JSON.stringify(this.options)));for(var n=0;n{"use strict";Object.defineProperty(qm,"__esModule",{value:!0});qm.BSONSymbol=void 0;var CU=function(){function e(t){if(!(this instanceof e))return new e(t);this.value=t}return s(e,"BSONSymbol"),e.prototype.valueOf=function(){return this.value},e.prototype.toString=function(){return this.value},e.prototype.inspect=function(){return'new BSONSymbol("'.concat(this.value,'")')},e.prototype.toJSON=function(){return this.value},e.prototype.toExtendedJSON=function(){return{$symbol:this.value}},e.fromExtendedJSON=function(t){return new e(t.$symbol)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e}();qm.BSONSymbol=CU;Object.defineProperty(CU.prototype,"_bsontype",{value:"Symbol"})});var Wf=E(Gi=>{"use strict";var Uhe=Gi&&Gi.__extends||function(){var e=s(function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},e(t,r)},"extendStatics");return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}s(n,"__"),t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(Gi,"__esModule",{value:!0});Gi.Timestamp=Gi.LongWithoutOverridesClass=void 0;var Bu=Fo(),jhe=Wn();Gi.LongWithoutOverridesClass=Bu.Long;var Whe=function(e){Uhe(t,e);function t(r,n){var i=this;return i instanceof t?(Bu.Long.isLong(r)?i=e.call(this,r.low,r.high,!0)||this:(0,jhe.isObjectLike)(r)&&typeof r.t<"u"&&typeof r.i<"u"?i=e.call(this,r.i,r.t,!0)||this:i=e.call(this,r,n,!0)||this,Object.defineProperty(i,"_bsontype",{value:"Timestamp",writable:!1,configurable:!1,enumerable:!1}),i):new t(r,n)}return s(t,"Timestamp"),t.prototype.toJSON=function(){return{$timestamp:this.toString()}},t.fromInt=function(r){return new t(Bu.Long.fromInt(r,!0))},t.fromNumber=function(r){return new t(Bu.Long.fromNumber(r,!0))},t.fromBits=function(r,n){return new t(r,n)},t.fromString=function(r,n){return new t(Bu.Long.fromString(r,!0,n))},t.prototype.toExtendedJSON=function(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}},t.fromExtendedJSON=function(r){return new t(r.$timestamp)},t.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},t.prototype.inspect=function(){return"new Timestamp({ t: ".concat(this.getHighBits(),", i: ").concat(this.getLowBits()," })")},t.MAX_VALUE=Bu.Long.MAX_UNSIGNED_VALUE,t}(Gi.LongWithoutOverridesClass);Gi.Timestamp=Whe});var jm=E(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.EJSON=zo.isBSONType=void 0;var oN=Eu(),cN=ym(),Ff=Sm(),BU=vm(),fN=Em(),$f=Nn(),lN=Nm(),Lm=Fo(),RU=Am(),xU=Im(),aN=Rm(),uN=Wn(),Um=Dm(),MU=Pm(),DU=Wf();function qU(e){return(0,uN.isObjectLike)(e)&&Reflect.has(e,"_bsontype")&&typeof e._bsontype=="string"}s(qU,"isBSONType");zo.isBSONType=qU;var PU=2147483647,LU=-2147483648,UU=9223372036854776e3,jU=-9223372036854776e3,Fhe={$oid:aN.ObjectId,$binary:oN.Binary,$uuid:oN.Binary,$symbol:MU.BSONSymbol,$numberInt:lN.Int32,$numberDecimal:BU.Decimal128,$numberDouble:fN.Double,$numberLong:Lm.Long,$minKey:xU.MinKey,$maxKey:RU.MaxKey,$regex:Um.BSONRegExp,$regularExpression:Um.BSONRegExp,$timestamp:DU.Timestamp};function WU(e,t){if(t===void 0&&(t={}),typeof e=="number"){if(t.relaxed||t.legacy)return e;if(Math.floor(e)===e){if(e>=LU&&e<=PU)return new lN.Int32(e);if(e>=jU&&e<=UU)return Lm.Long.fromNumber(e)}return new fN.Double(e)}if(e==null||typeof e!="object")return e;if(e.$undefined)return null;for(var r=Object.keys(e).filter(function(p){return p.startsWith("$")&&e[p]!=null}),n=0;n ")}).join(""),a=n[r],u=" -> "+n.slice(r+1,n.length-1).map(function(M){return"".concat(M," -> ")}).join(""),f=n[n.length-1],l=" ".repeat(i.length+a.length/2),h="-".repeat(u.length+(a.length+f.length)/2-1);throw new $f.BSONTypeError(`Converting circular structure to EJSON: +`+" ".concat(i).concat(a).concat(u).concat(f,` +`)+" ".concat(l,"\\").concat(h,"/"))}t.seenObjects[t.seenObjects.length-1].obj=e}if(Array.isArray(e))return $he(e,t);if(e===void 0)return null;if(e instanceof Date||(0,uN.isDate)(e)){var m=e.getTime(),p=m>-1&&m<2534023188e5;return t.legacy?t.relaxed&&p?{$date:e.getTime()}:{$date:IU(e)}:t.relaxed&&p?{$date:IU(e)}:{$date:{$numberLong:e.getTime().toString()}}}if(typeof e=="number"&&(!t.relaxed||!isFinite(e))){if(Math.floor(e)===e){var g=e>=LU&&e<=PU,w=e>=jU&&e<=UU;if(g)return{$numberInt:e.toString()};if(w)return{$numberLong:e.toString()}}return{$numberDouble:e.toString()}}if(e instanceof RegExp||(0,uN.isRegExp)(e)){var O=e.flags;if(O===void 0){var N=e.toString().match(/[gimuy]*$/);N&&(O=N[0])}var A=new Um.BSONRegExp(e.source,O);return A.toExtendedJSON(t)}return e!=null&&typeof e=="object"?Hhe(e,t):e}s($s,"serializeValue");var zhe={Binary:function(e){return new oN.Binary(e.value(),e.sub_type)},Code:function(e){return new cN.Code(e.code,e.scope)},DBRef:function(e){return new Ff.DBRef(e.collection||e.namespace,e.oid,e.db,e.fields)},Decimal128:function(e){return new BU.Decimal128(e.bytes)},Double:function(e){return new fN.Double(e.value)},Int32:function(e){return new lN.Int32(e.value)},Long:function(e){return Lm.Long.fromBits(e.low!=null?e.low:e.low_,e.low!=null?e.high:e.high_,e.low!=null?e.unsigned:e.unsigned_)},MaxKey:function(){return new RU.MaxKey},MinKey:function(){return new xU.MinKey},ObjectID:function(e){return new aN.ObjectId(e)},ObjectId:function(e){return new aN.ObjectId(e)},BSONRegExp:function(e){return new Um.BSONRegExp(e.pattern,e.options)},Symbol:function(e){return new MU.BSONSymbol(e.value)},Timestamp:function(e){return DU.Timestamp.fromBits(e.low,e.high)}};function Hhe(e,t){if(e==null||typeof e!="object")throw new $f.BSONError("not an object instance");var r=e._bsontype;if(typeof r>"u"){var n={};for(var i in e){t.seenObjects.push({propertyName:i,obj:null});try{var a=$s(e[i],t);i==="__proto__"?Object.defineProperty(n,i,{value:a,writable:!0,enumerable:!0,configurable:!0}):n[i]=a}finally{t.seenObjects.pop()}}return n}else if(qU(e)){var u=e;if(typeof u.toExtendedJSON!="function"){var f=zhe[e._bsontype];if(!f)throw new $f.BSONTypeError("Unrecognized or invalid _bsontype: "+e._bsontype);u=f(u)}return r==="Code"&&u.scope?u=new cN.Code(u.code,$s(u.scope,t)):r==="DBRef"&&u.oid&&(u=new Ff.DBRef($s(u.collection,t),$s(u.oid,t),$s(u.db,t),$s(u.fields,t))),u.toExtendedJSON(t)}else throw new $f.BSONError("_bsontype must be a string, but was: "+typeof r)}s(Hhe,"serializeDocument");var Vhe;(function(e){function t(a,u){var f=Object.assign({},{relaxed:!0,legacy:!1},u);return typeof f.relaxed=="boolean"&&(f.strict=!f.relaxed),typeof f.strict=="boolean"&&(f.relaxed=!f.strict),JSON.parse(a,function(l,h){if(l.indexOf("\0")!==-1)throw new $f.BSONError("BSON Document field names cannot contain null bytes, found: ".concat(JSON.stringify(l)));return WU(h,f)})}s(t,"parse"),e.parse=t;function r(a,u,f,l){f!=null&&typeof f=="object"&&(l=f,f=0),u!=null&&typeof u=="object"&&!Array.isArray(u)&&(l=u,u=void 0,f=0);var h=Object.assign({relaxed:!0,legacy:!1},l,{seenObjects:[{propertyName:"(root)",obj:null}]}),m=$s(a,h);return JSON.stringify(m,u,f)}s(r,"stringify"),e.stringify=r;function n(a,u){return u=u||{},JSON.parse(r(a,u))}s(n,"serialize"),e.serialize=n;function i(a,u){return u=u||{},t(JSON.stringify(a),u)}s(i,"deserialize"),e.deserialize=i})(Vhe=zo.EJSON||(zo.EJSON={}))});var dN=E(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.Map=void 0;var Yhe=ZT(),hN;Ru.Map=hN;var FU=(0,Yhe.getGlobal)();FU.Map?Ru.Map=hN=FU.Map:Ru.Map=hN=function(){function e(t){t===void 0&&(t=[]),this._keys=[],this._values={};for(var r=0;r{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});Fm.calculateObjectSize=void 0;var $e=require("buffer"),khe=Eu(),Wm=vu(),xu=Wn();function zf(e,t,r){var n=5;if(Array.isArray(e))for(var i=0;i=Wm.JS_INT_MIN&&t<=Wm.JS_INT_MAX&&t>=Wm.BSON_INT32_MIN&&t<=Wm.BSON_INT32_MAX?(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(4+1):(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(8+1);case"undefined":return n||!i?(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t._bsontype==="MinKey"||t._bsontype==="MaxKey")return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1;if(t._bsontype==="ObjectId"||t._bsontype==="ObjectID")return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(12+1);if(t instanceof Date||(0,xu.isDate)(t))return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||(0,xu.isAnyArrayBuffer)(t))return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.byteLength;if(t._bsontype==="Long"||t._bsontype==="Double"||t._bsontype==="Timestamp")return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(t._bsontype==="Decimal128")return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(16+1);if(t._bsontype==="Code")return t.scope!=null&&Object.keys(t.scope).length>0?(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+4+4+$e.Buffer.byteLength(t.code.toString(),"utf8")+1+zf(t.scope,r,i):(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+4+$e.Buffer.byteLength(t.code.toString(),"utf8")+1;if(t._bsontype==="Binary"){var a=t;return a.sub_type===khe.Binary.SUBTYPE_BYTE_ARRAY?(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(a.position+1+4+1+4):(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+(a.position+1+4+1)}else{if(t._bsontype==="Symbol")return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+$e.Buffer.byteLength(t.value,"utf8")+4+1+1;if(t._bsontype==="DBRef"){var u=Object.assign({$ref:t.collection,$id:t.oid},t.fields);return t.db!=null&&(u.$db=t.db),(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+zf(u,r,i)}else return t instanceof RegExp||(0,xu.isRegExp)(t)?(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+$e.Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t._bsontype==="BSONRegExp"?(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+$e.Buffer.byteLength(t.pattern,"utf8")+1+$e.Buffer.byteLength(t.options,"utf8")+1:(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+zf(t,r,i)+1}case"function":if(t instanceof RegExp||(0,xu.isRegExp)(t)||String.call(t)==="[object RegExp]")return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+$e.Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(r&&t.scope!=null&&Object.keys(t.scope).length>0)return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+4+4+$e.Buffer.byteLength((0,xu.normalizedFunctionString)(t),"utf8")+1+zf(t.scope,r,i);if(r)return(e!=null?$e.Buffer.byteLength(e,"utf8")+1:0)+1+4+$e.Buffer.byteLength((0,xu.normalizedFunctionString)(t),"utf8")+1}return 0}s($U,"calculateElement")});var HU=E($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});$m.validateUtf8=void 0;var Ghe=128,Khe=192,Xhe=224,Jhe=240,Zhe=248,Qhe=192,ede=224,tde=240,rde=128;function nde(e,t,r){for(var n=0,i=t;i{"use strict";var Mu=Du&&Du.__assign||function(){return Mu=Object.assign||function(e){for(var t,r=1,n=arguments.length;r= 5, is ".concat(i));if(t.allowObjectSmallerThanBufferSize&&e.length= bson size ").concat(i));if(!t.allowObjectSmallerThanBufferSize&&e.length!==i)throw new Ce.BSONError("buffer length ".concat(e.length," must === bson size ").concat(i));if(i+n>e.byteLength)throw new Ce.BSONError("(bson size ".concat(i," + options.index ").concat(n," must be <= buffer length ").concat(e.byteLength,")"));if(e[n+i-1]!==0)throw new Ce.BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return Ym(e,n,t,r)}s(pde,"deserialize");Du.deserialize=pde;var mde=/^\$ref$|^\$id$|^\$db$/;function Ym(e,t,r,n){n===void 0&&(n=!1);var i=r.evalFunctions==null?!1:r.evalFunctions,a=r.cacheFunctions==null?!1:r.cacheFunctions,u=r.fieldsAsRaw==null?null:r.fieldsAsRaw,f=r.raw==null?!1:r.raw,l=typeof r.bsonRegExp=="boolean"?r.bsonRegExp:!1,h=r.promoteBuffers==null?!1:r.promoteBuffers,m=r.promoteLongs==null?!0:r.promoteLongs,p=r.promoteValues==null?!0:r.promoteValues,g=r.validation==null?{utf8:!0}:r.validation,w=!0,O,N=new Set,A=g.utf8;if(typeof A=="boolean")O=A;else{w=!1;var M=Object.keys(A).map(function(Lu){return A[Lu]});if(M.length===0)throw new Ce.BSONError("UTF-8 validation setting cannot be empty");if(typeof M[0]!="boolean")throw new Ce.BSONError("Invalid UTF-8 validation option, must specify boolean values");if(O=M[0],!M.every(function(Lu){return Lu===O}))throw new Ce.BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}if(!w)for(var L=0,I=Object.keys(A);Le.length)throw new Ce.BSONError("corrupt bson message");for(var ee=n?[]:{},Ee=0,V=!1,fe=n?!1:null,ne=new DataView(e.buffer,e.byteOffset,e.byteLength);!V;){var J=e[t++];if(J===0)break;for(var K=t;e[K]!==0&&K=e.byteLength)throw new Ce.BSONError("Bad BSON Document: illegal CString");var ue=n?Ee++:e.toString("utf8",t,K),me=!0;w||N.has(ue)?me=O:me=!O,fe!==!1&&ue[0]==="$"&&(fe=mde.test(ue));var oe=void 0;if(t=K+1,J===rt.BSON_DATA_STRING){var ae=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(ae<=0||ae>e.length-t||e[t+ae-1]!==0)throw new Ce.BSONError("bad string length in bson");oe=Vm(e,t,t+ae-1,me),t=t+ae}else if(J===rt.BSON_DATA_OID){var De=zm.Buffer.alloc(12);e.copy(De,0,t,t+12),oe=new YU.ObjectId(De),t=t+12}else if(J===rt.BSON_DATA_INT&&p===!1)oe=new ode.Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(J===rt.BSON_DATA_INT)oe=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(J===rt.BSON_DATA_NUMBER&&p===!1)oe=new sde.Double(ne.getFloat64(t,!0)),t=t+8;else if(J===rt.BSON_DATA_NUMBER)oe=ne.getFloat64(t,!0),t=t+8;else if(J===rt.BSON_DATA_DATE){var le=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,Ke=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;oe=new Date(new km.Long(le,Ke).toNumber())}else if(J===rt.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new Ce.BSONError("illegal boolean type value");oe=e[t++]===1}else if(J===rt.BSON_DATA_OBJECT){var An=t,Ft=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(Ft<=0||Ft>e.length-t)throw new Ce.BSONError("bad embedded document length in bson");if(f)oe=e.slice(t,t+Ft);else{var lr=r;w||(lr=Mu(Mu({},r),{validation:{utf8:me}})),oe=Ym(e,An,lr,!1)}t=t+Ft}else if(J===rt.BSON_DATA_ARRAY){var An=t,Ft=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,Zt=r,hr=t+Ft;if(u&&u[ue]){Zt={};for(var sn in r)Zt[sn]=r[sn];Zt.raw=!0}if(w||(Zt=Mu(Mu({},Zt),{validation:{utf8:me}})),oe=Ym(e,An,Zt,!0),t=t+Ft,e[t-1]!==0)throw new Ce.BSONError("invalid array terminator byte");if(t!==hr)throw new Ce.BSONError("corrupted array bson")}else if(J===rt.BSON_DATA_UNDEFINED)oe=void 0;else if(J===rt.BSON_DATA_NULL)oe=null;else if(J===rt.BSON_DATA_LONG){var le=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,Ke=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,dr=new km.Long(le,Ke);m&&p===!0?oe=dr.lessThanOrEqual(hde)&&dr.greaterThanOrEqual(dde)?dr.toNumber():dr:oe=dr}else if(J===rt.BSON_DATA_DECIMAL128){var Hs=zm.Buffer.alloc(16);e.copy(Hs,0,t,t+16),t=t+16;var Cn=new ide.Decimal128(Hs);"toObject"in Cn&&typeof Cn.toObject=="function"?oe=Cn.toObject():oe=Cn}else if(J===rt.BSON_DATA_BINARY){var st=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,Fn=st,bt=e[t++];if(st<0)throw new Ce.BSONError("Negative binary type element size found");if(st>e.byteLength)throw new Ce.BSONError("Binary type size larger than document size");if(e.slice!=null){if(bt===Hf.Binary.SUBTYPE_BYTE_ARRAY){if(st=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,st<0)throw new Ce.BSONError("Negative binary type element size found for subtype 0x02");if(st>Fn-4)throw new Ce.BSONError("Binary type with subtype 0x02 contains too long binary size");if(stFn-4)throw new Ce.BSONError("Binary type with subtype 0x02 contains too long binary size");if(st=e.length)throw new Ce.BSONError("Bad BSON Document: illegal CString");var Pu=e.toString("utf8",t,K);for(t=K+1,K=t;e[K]!==0&&K=e.length)throw new Ce.BSONError("Bad BSON Document: illegal CString");var pr=e.toString("utf8",t,K);t=K+1;var Vs=new Array(pr.length);for(K=0;K=e.length)throw new Ce.BSONError("Bad BSON Document: illegal CString");var Pu=e.toString("utf8",t,K);for(t=K+1,K=t;e[K]!==0&&K=e.length)throw new Ce.BSONError("Bad BSON Document: illegal CString");var pr=e.toString("utf8",t,K);t=K+1,oe=new cde.BSONRegExp(Pu,pr)}else if(J===rt.BSON_DATA_SYMBOL){var ae=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(ae<=0||ae>e.length-t||e[t+ae-1]!==0)throw new Ce.BSONError("bad string length in bson");var Xf=Vm(e,t,t+ae-1,me);oe=p?Xf:new fde.BSONSymbol(Xf),t=t+ae}else if(J===rt.BSON_DATA_TIMESTAMP){var le=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,Ke=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;oe=new lde.Timestamp(le,Ke)}else if(J===rt.BSON_DATA_MIN_KEY)oe=new ude.MinKey;else if(J===rt.BSON_DATA_MAX_KEY)oe=new ade.MaxKey;else if(J===rt.BSON_DATA_CODE){var ae=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(ae<=0||ae>e.length-t||e[t+ae-1]!==0)throw new Ce.BSONError("bad string length in bson");var $r=Vm(e,t,t+ae-1,me);i?a?oe=Hm($r,kU,ee):oe=Hm($r):oe=new VU.Code($r),t=t+ae}else if(J===rt.BSON_DATA_CODE_W_SCOPE){var mr=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(mr<4+4+4+1)throw new Ce.BSONError("code_w_scope total size shorter minimum expected length");var ae=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(ae<=0||ae>e.length-t||e[t+ae-1]!==0)throw new Ce.BSONError("bad string length in bson");var $r=Vm(e,t,t+ae-1,me);t=t+ae;var An=t,Ft=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,Ji=Ym(e,An,r,!1);if(t=t+Ft,mr<4+4+Ft+ae)throw new Ce.BSONError("code_w_scope total size is too short, truncating scope");if(mr>4+4+Ft+ae)throw new Ce.BSONError("code_w_scope total size is too long, clips outer document");i?(a?oe=Hm($r,kU,ee):oe=Hm($r),oe.scope=Ji):oe=new VU.Code($r,Ji)}else if(J===rt.BSON_DATA_DBPOINTER){var ae=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(ae<=0||ae>e.length-t||e[t+ae-1]!==0)throw new Ce.BSONError("bad string length in bson");if(g!=null&&g.utf8&&!(0,GU.validateUtf8)(e,t,t+ae-1))throw new Ce.BSONError("Invalid UTF-8 string in BSON document");var Yo=e.toString("utf8",t,t+ae-1);t=t+ae;var Jf=zm.Buffer.alloc(12);e.copy(Jf,0,t,t+12);var De=new YU.ObjectId(Jf);t=t+12,oe=new pN.DBRef(Yo,De)}else throw new Ce.BSONError("Detected unknown BSON type ".concat(J.toString(16),' for fieldname "').concat(ue,'"'));ue==="__proto__"?Object.defineProperty(ee,ue,{value:oe,writable:!0,enumerable:!0,configurable:!0}):ee[ue]=oe}if(W!==t-Y)throw n?new Ce.BSONError("corrupt array bson"):new Ce.BSONError("corrupt object bson");if(!fe)return ee;if((0,pN.isDBRefLike)(ee)){var zn=Object.assign({},ee);return delete zn.$ref,delete zn.$id,delete zn.$db,new pN.DBRef(ee.$ref,ee.$id,ee.$db,zn)}return ee}s(Ym,"deserializeObject");function Hm(e,t,r){return t?(t[e]==null&&(t[e]=new Function(e)),t[e].bind(r)):new Function(e)}s(Hm,"isolateEval");function Vm(e,t,r,n){var i=e.toString("utf8",t,r);if(n){for(var a=0;a{"use strict";Object.defineProperty(Xm,"__esModule",{value:!0});Xm.serializeInto=void 0;var XU=Eu(),Qe=vu(),gde=Pf(),Ki=Nn(),yde=jm(),Sde=Fo(),_de=dN(),Fr=Wn(),Gm=/\x00/,JU=new Set(["$db","$ref","$id","$clusterTime"]);function mN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_STRING;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+a+1,e[n-1]=0;var u=e.write(r,n+4,void 0,"utf8");return e[n+3]=u+1>>24&255,e[n+2]=u+1>>16&255,e[n+1]=u+1>>8&255,e[n]=u+1&255,n=n+4+u,e[n++]=0,n}s(mN,"serializeString");var Yf=new Uint8Array(8),ZU=new DataView(Yf.buffer,Yf.byteOffset,Yf.byteLength);function gN(e,t,r,n,i){if(Number.isInteger(r)&&r>=Qe.BSON_INT32_MIN&&r<=Qe.BSON_INT32_MAX){e[n++]=Qe.BSON_DATA_INT;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+a,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255}else{e[n++]=Qe.BSON_DATA_NUMBER;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+a,e[n++]=0,ZU.setFloat64(0,r,!0),e.set(Yf,n),n=n+8}return n}s(gN,"serializeNumber");function Vf(e,t,r,n,i){e[n++]=Qe.BSON_DATA_NULL;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+a,e[n++]=0,n}s(Vf,"serializeNull");function yN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_BOOLEAN;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+a,e[n++]=0,e[n++]=r?1:0,n}s(yN,"serializeBoolean");function SN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_DATE;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+a,e[n++]=0;var u=Sde.Long.fromNumber(r.getTime()),f=u.getLowBits(),l=u.getHighBits();return e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255,e[n++]=l&255,e[n++]=l>>8&255,e[n++]=l>>16&255,e[n++]=l>>24&255,n}s(SN,"serializeDate");function _N(e,t,r,n,i){e[n++]=Qe.BSON_DATA_REGEXP;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");if(n=n+a,e[n++]=0,r.source&&r.source.match(Gm)!=null)throw Error("value "+r.source+" must not contain null bytes");return n=n+e.write(r.source,n,void 0,"utf8"),e[n++]=0,r.ignoreCase&&(e[n++]=105),r.global&&(e[n++]=115),r.multiline&&(e[n++]=109),e[n++]=0,n}s(_N,"serializeRegExp");function wN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_REGEXP;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");if(n=n+a,e[n++]=0,r.pattern.match(Gm)!=null)throw Error("pattern "+r.pattern+" must not contain null bytes");return n=n+e.write(r.pattern,n,void 0,"utf8"),e[n++]=0,n=n+e.write(r.options.split("").sort().join(""),n,void 0,"utf8"),e[n++]=0,n}s(wN,"serializeBSONRegExp");function vN(e,t,r,n,i){r===null?e[n++]=Qe.BSON_DATA_NULL:r._bsontype==="MinKey"?e[n++]=Qe.BSON_DATA_MIN_KEY:e[n++]=Qe.BSON_DATA_MAX_KEY;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+a,e[n++]=0,n}s(vN,"serializeMinMax");function ON(e,t,r,n,i){e[n++]=Qe.BSON_DATA_OID;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");if(n=n+a,e[n++]=0,typeof r.id=="string")e.write(r.id,n,void 0,"binary");else if((0,Fr.isUint8Array)(r.id))e.set(r.id.subarray(0,12),n);else throw new Ki.BSONTypeError("object ["+JSON.stringify(r)+"] is not a valid ObjectId");return n+12}s(ON,"serializeObjectId");function EN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_BINARY;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+a,e[n++]=0;var u=r.length;return e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=Qe.BSON_BINARY_SUBTYPE_DEFAULT,e.set((0,gde.ensureBuffer)(r),n),n=n+u,n}s(EN,"serializeBuffer");function TN(e,t,r,n,i,a,u,f,l,h){i===void 0&&(i=!1),a===void 0&&(a=0),u===void 0&&(u=!1),f===void 0&&(f=!0),l===void 0&&(l=!1),h===void 0&&(h=[]);for(var m=0;m>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255,n}s(bN,"serializeLong");function AN(e,t,r,n,i){r=r.valueOf(),e[n++]=Qe.BSON_DATA_INT;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+a,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255,n}s(AN,"serializeInt32");function CN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_NUMBER;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+a,e[n++]=0,ZU.setFloat64(0,r.value,!0),e.set(Yf,n),n=n+8,n}s(CN,"serializeDouble");function IN(e,t,r,n,i,a,u){i===void 0&&(i=!1),a===void 0&&(a=0),e[n++]=Qe.BSON_DATA_CODE;var f=u?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+f,e[n++]=0;var l=(0,Fr.normalizedFunctionString)(r),h=e.write(l,n+4,void 0,"utf8")+1;return e[n]=h&255,e[n+1]=h>>8&255,e[n+2]=h>>16&255,e[n+3]=h>>24&255,n=n+4+h-1,e[n++]=0,n}s(IN,"serializeFunction");function BN(e,t,r,n,i,a,u,f,l){if(i===void 0&&(i=!1),a===void 0&&(a=0),u===void 0&&(u=!1),f===void 0&&(f=!0),l===void 0&&(l=!1),r.scope&&typeof r.scope=="object"){e[n++]=Qe.BSON_DATA_CODE_W_SCOPE;var h=l?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+h,e[n++]=0;var m=n,p=typeof r.code=="string"?r.code:r.code.toString();n=n+4;var g=e.write(p,n+4,void 0,"utf8")+1;e[n]=g&255,e[n+1]=g>>8&255,e[n+2]=g>>16&255,e[n+3]=g>>24&255,e[n+4+g-1]=0,n=n+g+4;var w=Km(e,r.scope,i,n,a+1,u,f);n=w-1;var O=w-m;e[m++]=O&255,e[m++]=O>>8&255,e[m++]=O>>16&255,e[m++]=O>>24&255,e[n++]=0}else{e[n++]=Qe.BSON_DATA_CODE;var h=l?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+h,e[n++]=0;var p=r.code.toString(),N=e.write(p,n+4,void 0,"utf8")+1;e[n]=N&255,e[n+1]=N>>8&255,e[n+2]=N>>16&255,e[n+3]=N>>24&255,n=n+4+N-1,e[n++]=0}return n}s(BN,"serializeCode");function RN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_BINARY;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+a,e[n++]=0;var u=r.value(!0),f=r.position;return r.sub_type===XU.Binary.SUBTYPE_BYTE_ARRAY&&(f=f+4),e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255,e[n++]=r.sub_type,r.sub_type===XU.Binary.SUBTYPE_BYTE_ARRAY&&(f=f-4,e[n++]=f&255,e[n++]=f>>8&255,e[n++]=f>>16&255,e[n++]=f>>24&255),e.set(u,n),n=n+r.position,n}s(RN,"serializeBinary");function xN(e,t,r,n,i){e[n++]=Qe.BSON_DATA_SYMBOL;var a=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+a,e[n++]=0;var u=e.write(r.value,n+4,void 0,"utf8")+1;return e[n]=u&255,e[n+1]=u>>8&255,e[n+2]=u>>16&255,e[n+3]=u>>24&255,n=n+4+u-1,e[n++]=0,n}s(xN,"serializeSymbol");function MN(e,t,r,n,i,a,u){e[n++]=Qe.BSON_DATA_OBJECT;var f=u?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+f,e[n++]=0;var l=n,h={$ref:r.collection||r.namespace,$id:r.oid};r.db!=null&&(h.$db=r.db),h=Object.assign(h,r.fields);var m=Km(e,h,!1,n,i+1,a),p=m-l;return e[l++]=p&255,e[l++]=p>>8&255,e[l++]=p>>16&255,e[l++]=p>>24&255,m}s(MN,"serializeDBRef");function Km(e,t,r,n,i,a,u,f){r===void 0&&(r=!1),n===void 0&&(n=0),i===void 0&&(i=0),a===void 0&&(a=!1),u===void 0&&(u=!0),f===void 0&&(f=[]),n=n||0,f=f||[],f.push(t);var l=n+4;if(Array.isArray(t))for(var h=0;h>8&255,e[n++]=A>>16&255,e[n++]=A>>24&255,l}s(Km,"serializeInto");Xm.serializeInto=Km});var Tj=E(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.BSONRegExp=j.MaxKey=j.MinKey=j.Int32=j.Double=j.Timestamp=j.Long=j.UUID=j.ObjectId=j.Binary=j.DBRef=j.BSONSymbol=j.Map=j.Code=j.LongWithoutOverridesClass=j.EJSON=j.BSON_INT64_MIN=j.BSON_INT64_MAX=j.BSON_INT32_MIN=j.BSON_INT32_MAX=j.BSON_DATA_UNDEFINED=j.BSON_DATA_TIMESTAMP=j.BSON_DATA_SYMBOL=j.BSON_DATA_STRING=j.BSON_DATA_REGEXP=j.BSON_DATA_OID=j.BSON_DATA_OBJECT=j.BSON_DATA_NUMBER=j.BSON_DATA_NULL=j.BSON_DATA_MIN_KEY=j.BSON_DATA_MAX_KEY=j.BSON_DATA_LONG=j.BSON_DATA_INT=j.BSON_DATA_DECIMAL128=j.BSON_DATA_DBPOINTER=j.BSON_DATA_DATE=j.BSON_DATA_CODE_W_SCOPE=j.BSON_DATA_CODE=j.BSON_DATA_BOOLEAN=j.BSON_DATA_BINARY=j.BSON_DATA_ARRAY=j.BSON_BINARY_SUBTYPE_COLUMN=j.BSON_BINARY_SUBTYPE_ENCRYPTED=j.BSON_BINARY_SUBTYPE_UUID_NEW=j.BSON_BINARY_SUBTYPE_UUID=j.BSON_BINARY_SUBTYPE_USER_DEFINED=j.BSON_BINARY_SUBTYPE_MD5=j.BSON_BINARY_SUBTYPE_FUNCTION=j.BSON_BINARY_SUBTYPE_DEFAULT=j.BSON_BINARY_SUBTYPE_BYTE_ARRAY=void 0;j.deserializeStream=j.calculateObjectSize=j.deserialize=j.serializeWithBufferAndIndex=j.serialize=j.setInternalBufferSize=j.BSONTypeError=j.BSONError=j.ObjectID=j.Decimal128=void 0;var kf=require("buffer"),Jm=Eu();Object.defineProperty(j,"Binary",{enumerable:!0,get:function(){return Jm.Binary}});Object.defineProperty(j,"UUID",{enumerable:!0,get:function(){return Jm.UUID}});var tj=ym();Object.defineProperty(j,"Code",{enumerable:!0,get:function(){return tj.Code}});var rj=Sm();Object.defineProperty(j,"DBRef",{enumerable:!0,get:function(){return rj.DBRef}});var nj=vm();Object.defineProperty(j,"Decimal128",{enumerable:!0,get:function(){return nj.Decimal128}});var ij=Em();Object.defineProperty(j,"Double",{enumerable:!0,get:function(){return ij.Double}});var sj=Pf(),wde=jm(),oj=Nm();Object.defineProperty(j,"Int32",{enumerable:!0,get:function(){return oj.Int32}});var aj=Fo();Object.defineProperty(j,"Long",{enumerable:!0,get:function(){return aj.Long}});var uj=dN();Object.defineProperty(j,"Map",{enumerable:!0,get:function(){return uj.Map}});var cj=Am();Object.defineProperty(j,"MaxKey",{enumerable:!0,get:function(){return cj.MaxKey}});var fj=Im();Object.defineProperty(j,"MinKey",{enumerable:!0,get:function(){return fj.MinKey}});var Zm=Rm();Object.defineProperty(j,"ObjectId",{enumerable:!0,get:function(){return Zm.ObjectId}});Object.defineProperty(j,"ObjectID",{enumerable:!0,get:function(){return Zm.ObjectId}});var ej=Nn(),vde=zU(),lj=KU(),hj=QU(),dj=Dm();Object.defineProperty(j,"BSONRegExp",{enumerable:!0,get:function(){return dj.BSONRegExp}});var pj=Pm();Object.defineProperty(j,"BSONSymbol",{enumerable:!0,get:function(){return pj.BSONSymbol}});var mj=Wf();Object.defineProperty(j,"Timestamp",{enumerable:!0,get:function(){return mj.Timestamp}});var ze=vu();Object.defineProperty(j,"BSON_BINARY_SUBTYPE_BYTE_ARRAY",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_BYTE_ARRAY}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_DEFAULT",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_DEFAULT}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_FUNCTION",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_FUNCTION}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_MD5",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_MD5}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_USER_DEFINED",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_USER_DEFINED}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_UUID",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_UUID}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_UUID_NEW",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_UUID_NEW}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_ENCRYPTED",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_ENCRYPTED}});Object.defineProperty(j,"BSON_BINARY_SUBTYPE_COLUMN",{enumerable:!0,get:function(){return ze.BSON_BINARY_SUBTYPE_COLUMN}});Object.defineProperty(j,"BSON_DATA_ARRAY",{enumerable:!0,get:function(){return ze.BSON_DATA_ARRAY}});Object.defineProperty(j,"BSON_DATA_BINARY",{enumerable:!0,get:function(){return ze.BSON_DATA_BINARY}});Object.defineProperty(j,"BSON_DATA_BOOLEAN",{enumerable:!0,get:function(){return ze.BSON_DATA_BOOLEAN}});Object.defineProperty(j,"BSON_DATA_CODE",{enumerable:!0,get:function(){return ze.BSON_DATA_CODE}});Object.defineProperty(j,"BSON_DATA_CODE_W_SCOPE",{enumerable:!0,get:function(){return ze.BSON_DATA_CODE_W_SCOPE}});Object.defineProperty(j,"BSON_DATA_DATE",{enumerable:!0,get:function(){return ze.BSON_DATA_DATE}});Object.defineProperty(j,"BSON_DATA_DBPOINTER",{enumerable:!0,get:function(){return ze.BSON_DATA_DBPOINTER}});Object.defineProperty(j,"BSON_DATA_DECIMAL128",{enumerable:!0,get:function(){return ze.BSON_DATA_DECIMAL128}});Object.defineProperty(j,"BSON_DATA_INT",{enumerable:!0,get:function(){return ze.BSON_DATA_INT}});Object.defineProperty(j,"BSON_DATA_LONG",{enumerable:!0,get:function(){return ze.BSON_DATA_LONG}});Object.defineProperty(j,"BSON_DATA_MAX_KEY",{enumerable:!0,get:function(){return ze.BSON_DATA_MAX_KEY}});Object.defineProperty(j,"BSON_DATA_MIN_KEY",{enumerable:!0,get:function(){return ze.BSON_DATA_MIN_KEY}});Object.defineProperty(j,"BSON_DATA_NULL",{enumerable:!0,get:function(){return ze.BSON_DATA_NULL}});Object.defineProperty(j,"BSON_DATA_NUMBER",{enumerable:!0,get:function(){return ze.BSON_DATA_NUMBER}});Object.defineProperty(j,"BSON_DATA_OBJECT",{enumerable:!0,get:function(){return ze.BSON_DATA_OBJECT}});Object.defineProperty(j,"BSON_DATA_OID",{enumerable:!0,get:function(){return ze.BSON_DATA_OID}});Object.defineProperty(j,"BSON_DATA_REGEXP",{enumerable:!0,get:function(){return ze.BSON_DATA_REGEXP}});Object.defineProperty(j,"BSON_DATA_STRING",{enumerable:!0,get:function(){return ze.BSON_DATA_STRING}});Object.defineProperty(j,"BSON_DATA_SYMBOL",{enumerable:!0,get:function(){return ze.BSON_DATA_SYMBOL}});Object.defineProperty(j,"BSON_DATA_TIMESTAMP",{enumerable:!0,get:function(){return ze.BSON_DATA_TIMESTAMP}});Object.defineProperty(j,"BSON_DATA_UNDEFINED",{enumerable:!0,get:function(){return ze.BSON_DATA_UNDEFINED}});Object.defineProperty(j,"BSON_INT32_MAX",{enumerable:!0,get:function(){return ze.BSON_INT32_MAX}});Object.defineProperty(j,"BSON_INT32_MIN",{enumerable:!0,get:function(){return ze.BSON_INT32_MIN}});Object.defineProperty(j,"BSON_INT64_MAX",{enumerable:!0,get:function(){return ze.BSON_INT64_MAX}});Object.defineProperty(j,"BSON_INT64_MIN",{enumerable:!0,get:function(){return ze.BSON_INT64_MIN}});var Ode=jm();Object.defineProperty(j,"EJSON",{enumerable:!0,get:function(){return Ode.EJSON}});var Ede=Wf();Object.defineProperty(j,"LongWithoutOverridesClass",{enumerable:!0,get:function(){return Ede.LongWithoutOverridesClass}});var gj=Nn();Object.defineProperty(j,"BSONError",{enumerable:!0,get:function(){return gj.BSONError}});Object.defineProperty(j,"BSONTypeError",{enumerable:!0,get:function(){return gj.BSONTypeError}});var yj=1024*1024*17,zs=kf.Buffer.alloc(yj);function Sj(e){zs.length{var Nde=require("stream").Transform,Nj=Tj();bj.exports=s(function(t){function r(n,i,a){if(t){var u=Nj.deserialize(n);return u.cursor.firstBatch.forEach(function(f){this.push(Nj.serialize(f))}.bind(this)),a()}return a(null,n)}return s(r,"transform"),new Nde({readableObjectMode:!0,writableObjectMode:!0,transform:r})},"rawTransform")});var Bj=E((nOe,Ij)=>{var Cj=GT(),bde=Aj(),Ade=JT(),Cde=require("util").inherits,Ide=fm()("mongodb-collection-sample:native-sampler");function DN(e,t,r){Cj.call(this,e,t,r),this.running=!1}s(DN,"NativeSampler");Cde(DN,Cj);DN.prototype._read=function(){if(!this.running){this.running=!0;var e={maxTimeMS:this.maxTimeMS,allowDiskUse:!0,promoteValues:this.promoteValues};this.collection.countDocuments(this.query,e,function(t,r){if(t)return this.emit("error",t);if(Ide("sampling %d documents from a collection with %d documents",this.size,r),r>this.size&&r<=this.size*20){var n=new Ade(this.db,this.collectionName,this.opts);return n.on("error",this.emit.bind(this,"error")).on("data",this.push.bind(this)).on("end",this.push.bind(this,null))}this.pipeline=[],Object.keys(this.query).length>0&&this.pipeline.push({$match:this.query}),r>this.size&&this.pipeline.push({$sample:{size:this.size}}),this.fields&&Object.keys(this.fields).length>0&&this.pipeline.push({$project:this.fields}),e.raw=this.raw,e.cursor=this.cursor,e.batchSize=this.size;var i=this.collection.aggregate(this.pipeline,e);i.pipe(bde(this.raw)).on("error",this.emit.bind(this,"error")).on("data",this.push.bind(this)).on("end",this.push.bind(this,null))}.bind(this))}};Ij.exports=DN});var xj=E((sOe,qN)=>{var Bde=wT(),Rde=N2(),xde=fm()("mongodb-collection-sample"),Mde=JT(),Dde=Bj();function Rj(e,t,r,n){e.admin().serverInfo(function(i,a){if(i)return n(i);var u=Rde.gte(a.version,"3.1.6");return xde("has native $sample?",u),u?n(null,new Dde(e,t,r)):n(null,new Mde(e,t,r))})}s(Rj,"getSampler");qN.exports=function(e,t,r){var n=Bde.readable(function(){Rj(e,t,r,function(i,a){if(i)return n.emit("error",i);a.on("data",n.emit.bind(n,"data")),a.on("error",n.emit.bind(n,"error")),a.on("end",n.emit.bind(n,"end"))})});return n};qN.exports.getSampler=Rj});var Dj=E((aOe,Mj)=>{Mj.exports=xj()});var Uj=E((uOe,Lj)=>{var qde=kE().MongoClient,Pde=Dj(),PN,Ho;function Lde(e){return{sshTunnelUsername:e.ssh_user||"ec2-user",sshTunnelHostname:e.ssh_host,sshTunnelPort:Number(e.ssh_port)||22,sshAuthMethod:e.ssh_method==="privateKey"?"IDENTITY_FILE":"",sshTunnelIdentityFile:e.ssh_key_file,sshTunnelPassphrase:e.ssh_key_passphrase,host:e.host,port:Number(e.port)}}s(Lde,"getSshConfig");var Ude=s(async(e,t)=>{let r=Lde(e),{options:n}=await t.openTunnel(r);return{...e,host:n.host,port:n.port.toString()||"22"}},"getSshConnectionSettings");function jde(e){let t=Pj(e.username),r=Pj(e.password);return e.sslType==="TRUST_CUSTOM_CA_SIGNED_CERTIFICATES"&&e.ssh||e.sslType==="UNVALIDATED_SSL"?{url:`mongodb://${t}:${r}@${e.host}:${e.port}/?retryWrites=false`,options:{tls:!0,tlsAllowInvalidHostnames:!0,useUnifiedTopology:!0,sslValidate:!1}}:e.sslType==="TRUST_CUSTOM_CA_SIGNED_CERTIFICATES"?{url:`mongodb://${t}:${r}@${e.host}:${e.port}/?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`,options:{tlsCAFile:e.certAuthority,useUnifiedTopology:!0}}:{url:`mongodb://${t}:${r}@${e.host}:${e.port}/?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`,options:{useNewUrlParser:!0,useUnifiedTopology:!0}}}s(jde,"generateConnectionParams");async function Wde(e,t){try{if(Ho)return qj(Ho);e.ssh&&(e=await Ude(e,t),PN=!0);let r=jde(e);return Ho=await qde.connect(r.url,r.options),qj(Ho)}catch(r){throw{message:r.code===18?"Authentication failed. Please, check connection settings and try again":r.message,stack:r.stack}}}s(Wde,"connect");function qj(e){let t=s(()=>new Promise((g,w)=>{e.db().admin().listDatabases((N,A)=>N?w(N):g(A.databases))}),"getDatabases"),r=s(g=>new Promise((w,O)=>{let N=e.db(g);if(!N)return O(new Error(`Failed connection to database "${g}"`));N.listCollections().toArray((A,M)=>A?O(A):w(M))}),"getCollections"),n=s(()=>new Promise((g,w)=>{e.db().admin().buildInfo((N,A)=>{N?w(N):g(A)})}),"getBuildInfo"),i=s((g,w,O)=>{let N=e.db(g);return!O.sort||Object.keys(O.sort).length===0?Pde(N,w,O):N.collection(w).find(O.query,{sort:O.sort,limit:Number(O.size),maxTimeMS:O.maxTimeMS}).stream()},"getDataStream"),a=s((g,w,{query:O,sort:N,limit:A,maxTimeMS:M})=>new Promise((L,I)=>{let W=[],ee={size:Number(A),query:O,sort:N,maxTimeMS:M||12e4},Ee,V=s(ne=>{if(ne.code===28799&&(ne={message:"MongoDB Error: $sample stage could not find a non-duplicate document after 100 while using a random cursor. Please try again."}),ne.code===11601){let J=new Error("MongoDB Error: "+ne.message+". Please, try to increase query timeout (Options -> Reverse-Engineering) and try again.");J.stack=ne.stack,ne=J}Ee=ne,I(ne)},"streamErrorHandler"),fe=i(g,w,ee);fe.on("error",ne=>{V(ne)}),fe.on("data",ne=>{W.push(ne)}),fe.on("end",()=>{Ee||L(W)})}),"getRandomDocuments"),u=s((g,w)=>new Promise((O,N)=>{e.db(g).collection(w).estimatedDocumentCount((L,I)=>L?N(L):O(I))}),"getCount"),f=s((g,w,O)=>new Promise((N,A)=>{e.db(g).collection(w).findOne(O,(I,R)=>I?A(I):N(R))}),"findOne");return{getDatabases:t,getCollections:r,getBuildInfo:n,getDataStream:i,getCount:u,getRandomDocuments:a,findOne:f,hasPermission:s(async(g,w)=>{try{return await f(g,w),!0}catch(O){if(O.code===13)return!1;throw O}},"hasPermission"),getIndexes:s((g,w)=>new Promise((O,N)=>{e.db(g).collection(w).indexes({full:!0},(L,I)=>L?N(L):O(I))}),"getIndexes"),getCollection:s((g,w)=>{let N=e.db(g).collection(w);return{createIndex(A,M){return N.createIndex(A,M)},insertOne(A){return N.insertOne(A)}}},"getCollection"),createCollection:s(async(g,w)=>{let N=e.db(g);try{return await N.createCollection(w)}catch(A){if(A.code===48)return;throw A}},"createCollection")}}s(qj,"createConnection");async function Fde(e){Ho&&(Ho.close(),Ho=null),PN&&(PN=!1,await e.closeConsumer())}s(Fde,"close");var Pj=s(e=>encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16)}),"encodeURIComponentRFC3986");Lj.exports={connect:Wde,close:Fde}});var jj=E((fOe,$de)=>{$de.exports={name:"DocumentDB",version:"0.1.8",versionDate:"2023-08-03",author:"hackolade",engines:{hackolade:"6.10.3",hackoladePlugin:"1.0.1"},contributes:{target:{applicationTarget:"DocumentDB",title:"DocumentDB",versions:["3.6.0","4.0.0","5.0.0"]},features:{nestedCollections:!1,forwardEngineering:{jsonSchema:{keepParentType:{objectId:{type:"string",pattern:"^[a-fA-F0-9]{24}$"},regex:"string",date:{type:"string",format:"date-time"},timestamp:{type:"string",format:"date-time"},binary:{type:"string",mediaType:"image/png",contentEncoding:"base64"},minKey:"number",maxKey:"number"}}},enableReverseEngineering:!0,enableForwardEngineering:!0,enableReverseEngineeringDetectionSchemaByContent:!1,enableReversingDateTypeAsISODate:!0,supportInferRelationships:!0,enableREQueryAndSortCriteria:!0}},description:"Hackolade plugin for Amazon DocumentDB",scripts:{lint:"eslint . --max-warnings=0",package:"node esbuild.package.js"},dependencies:{async:"^3.2.4",bson:"^1.1.6",lodash:"^4.17.21",mongodb:"^3.7.3","mongodb-collection-sample":"^4.5.1"},devDependencies:{"@hackolade/hck-esbuild-plugins-pack":"^0.0.1",esbuild:"^0.19.4","esbuild-plugin-clean":"^1.0.1",eslint:"^8.51.0","eslint-config-prettier":"^9.0.0","eslint-plugin-prettier":"^5.0.0","lint-staged":"^14.0.1",prettier:"^3.0.3","simple-git-hooks":"^2.9.0"},"lint-staged":{"*.{js,json}":"prettier --write"},"simple-git-hooks":{"pre-commit":"npx lint-staged","pre-push":"npx eslint ."}}});var Fj=E((lOe,Wj)=>{var Xi=require("os"),zde=jj(),Hde=s(()=>zde.version,"getPluginVersion"),Vde=s(e=>`Date: ${new Date} +Application version: ${e} +Plugin version: ${Hde()} + +System information: + Hostname: ${Xi.hostname()} + Platform: ${Xi.platform()} ${Xi.arch()} + Release: ${Xi.release()} + Uptime: ${Gde(Xi.uptime())} + Total RAM: ${(Xi.totalmem()/1073741824).toFixed(2)} GB + CPU Model: ${Xi.cpus()[0].model} + CPU Clock: ${Yde(Xi.cpus())} MHZ + CPU Cores: ${Xi.cpus().length} cores + +`,"getSystemInfo"),Yde=s(e=>e.reduce((t,r)=>Math.max(t,r.speed),0),"maxClock"),kde=s(e=>e<10?"0"+e:e,"prefixZero"),Gde=s(e=>Math.floor(e/3600)+":"+kde(parseInt((e/3600-Math.floor(e/3600))*60)),"toTime"),Kde=s(({title:e,logger:t,hiddenKeys:r})=>({info(n){t.log("info",{message:n},e,r)},progress(n,i="",a=""){t.progress({message:n,containerName:i,entityName:a})},error(n){t.log("error",Xde(n),e)}}),"createLogger"),Xde=s(e=>({message:e.message||e.msg||e.errmsg,code:e.code,stack:e.stack}),"createError"),Jde={getSystemInfo:Vde,createLogger:Kde};Wj.exports=Jde});var Hj=E((dOe,zj)=>{var Zde=require("fs"),{createInterface:Qde}=require("readline"),$j=s((e,t)=>{let r=Zde.createReadStream(e);return Qde({input:r,crlfDelay:1/0}).on("line",n=>{t(n)})},"createNdJsonStream"),epe=s(e=>e<1e3?e%100===0:e%1e3===0,"shouldLogStep"),tpe=s(e=>new Promise((t,r)=>{let n=0;try{$j(e,()=>{n++}).on("close",()=>{t(n)})}catch(i){r(rpe(i))}}),"getCountOfLines"),rpe=s(e=>{let t=new Error(e);return t.type="file",t},"createFileError"),npe=s(async(e,t)=>{let r=await tpe(e),n=0,i=[];return new Promise((a,u)=>{try{$j(e,async f=>{n++,epe(n)&&t.info(`NDJSON_READ_LINES - lines: ${n} / ${r}, progress: ${n/r}`),f&&i.push(f)}).on("close",()=>(t.info(`NDJSON_READ_LINES - lines: ${n} / ${r}, progress: ${n/r}`),a(i)))}catch(f){return u(f)}})},"readNdJsonByLine");zj.exports=npe});var kj=E((mOe,Yj)=>{var Vj=require("vm"),Vo=th(),Gf=Uj(),Qm=Fj(),ipe=Hj(),spe={async applyToInstance(e,t,r){let n=Qm.createLogger({title:"Applying to instance",hiddenKeys:e.hiddenKeys,logger:t});try{t.clear(),n.info(Qm.getSystemInfo(e.appVersion)),n.info(e);let i=await Gf.connect(e),{scriptWithSamples:a,numberOfSamples:u}=await upe(e.script,e.entitiesData,n),f=ope(fpe(a));await ape({mongodbScript:f,logger:n,connection:i,numberOfSamples:u}),Gf.close(),r(null)}catch(i){n.error(i),Gf.close(),r({message:i.message,stack:i.stack})}},async testConnection(e,t,r){let n=Qm.createLogger({title:"Test connection",hiddenKeys:e.hiddenKeys,logger:t});try{t.clear(),n.info(Qm.getSystemInfo(e.appVersion)),n.info(e),await Gf.connect(e),Gf.close(),n.info("Connected successfully"),r()}catch(i){return n.error(i),r({message:i.message,stack:i.stack})}}},ope=s(e=>e.split(` +`).filter(Boolean).map(t=>{let r=/^use\ ([\s\S]+);$/i,n=t.match(r);return n?`useDb("${n[1]}");`:t}).join(` +`),"replaceUseCommand"),ape=s(({mongodbScript:e,logger:t,connection:r,numberOfSamples:n})=>{let i,a=[],u=0,f=0,l=cpe(t);l.info("Start applying instance ...");let h={ISODate:m=>new Date(m),ObjectId:Vo.ObjectId,Binary:Vo.Binary,BinData:(m,p)=>Vo.Binary(p),MinKey:Vo.MinKey,MaxKey:Vo.MaxKey,Code:Vo.Code,Timestamp:Vo.Timestamp,useDb(m){i=m},db:{createCollection(m){let p=s(()=>r.createCollection(i,m).then(()=>{l.info(`Collection ${m} created`)},g=>{let w=`Collection ${m} not created`;return l.error(g,w),g.message=w,Promise.reject(g)}),"command");a.push(p)},getCollection(m){let p=r.getCollection(i,m);return{createIndex(g,w={}){let O=s(()=>p.createIndex(g,w).then(()=>{l.info(`index ${w.name} created`)},N=>{let A=`index ${w.name} not created`;return l.error(N,A),N.message=A,Promise.reject(N)}),"command");a.push(O)},insert(g){let w=s(()=>p.insertOne(g).then(()=>{u++;let O=Math.round(u/n*100);O-f<5||(f=O,l.info(`Inserting Samples: ${O}%`))}).catch(O=>{u++;let N=`sample is not inserted ${u} / ${n} Reason: ${O.message}`;return l.error(O,N),O.message=N,Promise.reject(O)}),"command");a.push(w)}}}}};return Vj.createContext(h),Vj.runInContext(e,h),a.reduce((m,p)=>m.then(()=>p()),Promise.resolve())},"runMongoDbScript"),upe=s(async(e,t,r)=>{let n=Object.keys(t).length;return{scriptWithSamples:await Object.values(t).reduce(async(a,u)=>{if(a=await a,!u.filePath)return Promise.resolve(a);try{let f=u.code||u.name,l=await ipe(u.filePath,r);return n+=l.length,a+l.map(h=>`db.getCollection("${f}").insert(${h});`).join(` + +`)}catch(f){r.error(f,"Error during publishing fake data in bulk")}},Promise.resolve(e+` + +`)),numberOfSamples:n}},"generateScriptForInsertingDataInBulk"),cpe=s(e=>({info(t){e.progress(`${t}`),e.info(t)},error(t,r){e.progress(`[color:red]failed: ${r}`),e.error(t)},warning(t,r){e.progress({message:`[color:orange]warning: ${t}`}),r&&e.error(r)}}),"createProgressLog");function fpe(e){return e.replace(/\{\s*\"\$minKey\": (\d*)\s*\}/gi,"MinKey($1)").replace(/\{\s*\"\$maxKey\": (\d*)\s*\}/gi,"MaxKey($1)")}s(fpe,"convertBson");Yj.exports=spe});var Kj=E((yOe,Gj)=>{"use strict";var Kf=s((e,t,r)=>{if(e.GUID===t)return r;if(e.properties)return Object.keys(e.properties).reduce((n,i)=>n||Kf(e.properties[i],t,[...r,e.properties[i].GUID]),void 0);if(e.items)return Array.isArray(e.items)?e.items.reduce((n,i)=>n||Kf(i,t,[...r,i.GUID]),void 0):Kf(e.items,t,[...r,e.items.GUID])},"getPathById"),lpe=s((e,t)=>{let r=Object.keys(t).find(n=>t[n].GUID===e);return t[r]&&t[r].code?{name:t[r].code,isActivated:t[r].isActivated}:{name:r,isActivated:t[r]&&t[r].isActivated}},"getRootItemMetadataById"),hpe=s((e,t)=>{let r=Kf(t,e,[]);return r?lpe(r[0],t.properties):{name:""}},"findFieldMetadataById"),dpe=s((e,t)=>e.reduce((r,n)=>{for(let i=0;i{var ppe=Kj(),mpe=s(e=>Object.keys(e).length===0,"isObjectEmpty"),Xj=s(e=>Object.fromEntries(Object.entries(e).filter(([t,r])=>r!==void 0)),"filterObject"),gpe=s((...e)=>"createIndex("+e.map(Xj).filter(t=>!mpe(t)).map(ype).join(", ")+");","createIndexStatement"),ype=s(e=>JSON.stringify(e,null,2),"stringify"),Spe=s(e=>({descending:-1,ascending:1,"2DSphere":"2dsphere"})[e]||1,"getIndexType"),_pe=s(e=>{let t=e==null?void 0:e.key;return!Array.isArray(t)||(t=t.filter(r=>r.name&&r.isActivated),t.length===0)?"":gpe(t.reduce((r,n)=>({...r,[n.name]:Spe(n.type)}),{}),Xj({name:e.name,unique:e.unique?e.unique:void 0,sparse:e.sparse?e.sparse:void 0,background:e.background?e.background:void 0,expireAfterSeconds:e.expireAfterSeconds?e.expireAfterSeconds:void 0}))},"createIndex"),wpe=s(e=>{var t,r;return((t=e[0])==null?void 0:t.code)||((r=e[0])==null?void 0:r.name)},"getContainerName"),LN=s(e=>{var t,r;return((t=e[0])==null?void 0:t.code)||((r=e[0])==null?void 0:r.collectionName)},"getCollectionName"),Jj=s(e=>`db.getCollection("${e}")`,"getCollection"),vpe=s((e,t)=>{var n;return(((n=e[1])==null?void 0:n.Indxs)||[]).filter(i=>i.isActivated!==!1).map(Npe(t)).map(_pe).filter(Boolean).map(i=>Jj(LN(e))+"."+i).join(` + +`)},"getIndexes"),Ope=s(e=>`db.createCollection("${LN(e)}");`,"createCollection"),Epe=s(e=>{let t=vpe(e.entityData,e);return[Ope(e.entityData),t].filter(Boolean).join(` + +`)},"getScript"),Tpe=s(e=>{let t=JSON.parse(Cpe(e));return Ape(JSON.stringify({...t},null,2))},"updateSample"),Npe=s(({jsonSchema:e,definitions:t})=>r=>{let n=ppe.getNamesByIds(r.key.map(i=>i.keyId),[e,t.internal,t.model,t.external]);return{...r,key:r.key.map(i=>({...i,...n[i.keyId]||{}}))}},"fillKeys"),Zj=s(({entityData:e,sample:t})=>Jj(LN(e))+`.insert(${Tpe(t)});`,"insertSample"),bpe=s(e=>{let t=Qj(e.containerData),r=e.entities.map(n=>Zj({entityData:e.entityData[n]||[],sample:e.jsonData[n]})).join(` + +`);return[t,r].filter(Boolean).join(` + +`)},"insertSamples");function Ape(e,t){let r,n=e,i="",a="";return r=n.replace(/\"\$__oid_(.*?)\"/gi,function(u,f){return i+'ObjectId("'+f+'")'+a}).replace(/\"\$__date_(.*?)\"/gi,function(u,f){return i+'ISODate("'+f+'")'+a}).replace(/\"(?:CURRENT_)?\$__tmstmp_(.*?)\"/gi,function(u,f){return i+"Timestamp("+f+")"+a}).replace(/\"\$__rgxp_(.*?)\"/gi,function(u,f){return i+f+a}).replace(/\"\$__bindata_(\d*)_(.*?)\"/gi,function(u,f,l){return i+`BinData(${f},"${l}")`+a}).replace(/\"\$__maxKey_(\d*)\"/gi,function(u,f){return i+`new MaxKey(${f})`+a}).replace(/\"\$__minKey_(\d*)\"/gi,function(u,f){return i+`new MinKey(${f})`+a}).replace(/\"\$__jswscope_(.*?})\"/gi,function(u,f){return i+`Code("${f}")`+a}).replace(/\"\$__js_(.*?})\"/gi,function(u,f){return i+`Code("${f}")`+a}),r}s(Ape,"decodedExtendedTypes");function Cpe(e,t){let r,n='"',i='"';return r=e.replace(/ObjectId\(\"(.*?)\"\)/gi,function(a,u){return n+"$__oid_"+u+i}).replace(/ISODate\(\"(.*?)\"\)/gi,function(a,u){return n+"$__date_"+u+i}).replace(/Timestamp\((.*?)\)/gi,function(a,u){return n+"$__tmstmp_"+u+i}).replace(/\"\s*:\s*\/(.*?)\/([^,\s\]\}\n]*)/gi,function(a,u,f){return'": '+n+"$__rgxp_/"+u+"/"+f+i}).replace(/BinData\((\d*),\"(.*?)\"\)/gi,function(a,u,f){return n+`$__bindata_${u}_${f}`+i}).replace(/\"type\": \"JavaScript\(w\/scope\)\",\s*.*?\"sample\": \{\s*\"_bsontype\": \"Code\",\s*\"code\": \"(.*?})\",\s*\"scope\": .*?\s*\}/gi,function(a,u){return a.replace(/\{\s*\"_bsontype\": \"Code\",\s*\"code\": \"(.*?})\",\s*\"scope\": .*?\s*\}/,function(f,l){return n+`$__jswscope_${l}`+i})}).replace(/\{\s*\"_bsontype\": \"Code\",\s*\"code\": \"(.*?})\".*?\s*\}/gi,function(a,u){return n+`$__js_${u}`+i}).replace(/\{\s*\"\$minKey\": (\d*)\s*\}/,function(a,u){return n+`$__minKey_${u}`+i}).replace(/\{\s*\"\$maxKey\": (\d*)\s*\}/,function(a,u){return n+`$__maxKey_${u}`+i}),r}s(Cpe,"encodedExtendedTypes");var Qj=s(e=>{let t=wpe(e);return t?`use ${t};`:""},"useDbStatement");eW.exports={getScript:Epe,insertSample:Zj,insertSamples:bpe,useDbStatement:Qj}});var Ipe=dC(),rW=kj(),qu=tW();module.exports={generateContainerScript(e,t,r){try{let n=Ipe.get(e,"options.additionalOptions",[]).find(l=>l.id==="INCLUDE_SAMPLES")||{},i=e.options.origin!=="ui",u=qu.useDbStatement(e.containerData)+` + +`+e.entities.map(l=>{var p;let h=e.entityData[l],m=qu.getScript({entityData:h,containerData:e.containerData,jsonSchema:JSON.parse(e.jsonSchema[l]),definitions:{internal:JSON.parse(e.internalDefinitions[l]),model:JSON.parse(e.modelDefinitions),external:JSON.parse(e.externalDefinitions)}});return(p=h==null?void 0:h[0])!=null&&p.isActivated?m:`/* +${m} +*/`}).join(` + +`),f=qu.insertSamples(e);return u+=i?` +`+f:"",i||!n.value?r(null,u):r(null,[{title:"MongoDB script",script:u},{title:"Sample data",script:f}])}catch(n){let i={message:n.message,stack:n.stack};t.log("error",i,"DocumentDB forward engineering error"),r(i)}},generateScript(e,t,r,n){try{let i=qu.useDbStatement(e.containerData),a=qu.getScript({containerData:e.containerData,entityData:e.entityData,jsonSchema:JSON.parse(e.jsonSchema),definitions:{model:JSON.parse(e.modelDefinitions),internal:JSON.parse(e.internalDefinitions),external:JSON.parse(e.externalDefinitions)}}),u=qu.insertSample({containerData:e.containerData,entityData:e.entityData,sample:e.jsonData});return r(null,[i,a,u].join(` + +`))}catch(i){let a={message:i.message,stack:i.stack};t.log("error",a,"DocumentDB forward engineering error"),r(a)}},applyToInstance:rW.applyToInstance,testConnection:rW.testConnection}; +/*! Bundled license information: + +lodash/lodash.js: + (** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) +*/ diff --git a/forward_engineering/config.json b/forward_engineering/config.json index 1f89a1f..d0e5e0a 100644 --- a/forward_engineering/config.json +++ b/forward_engineering/config.json @@ -12,15 +12,17 @@ "container": true, "view": false }, - "additionalOptions": [{ - "id": "INCLUDE_SAMPLES", - "value": true, - "name": "Include sample data", - "align": "right", - "level": { - "entity": false + "additionalOptions": [ + { + "id": "INCLUDE_SAMPLES", + "value": true, + "name": "Include sample data", + "align": "right", + "level": { + "entity": false + } } - }], + ], "splitView": { "byAdditionalOptions": ["INCLUDE_SAMPLES"] }, diff --git a/forward_engineering/helpers/applyToInstanceHelper.js b/forward_engineering/helpers/applyToInstanceHelper.js deleted file mode 100644 index 37a90a7..0000000 --- a/forward_engineering/helpers/applyToInstanceHelper.js +++ /dev/null @@ -1,223 +0,0 @@ -const vm = require('vm'); -const bson = require('../../reverse_engineering/node_modules/bson'); -const connectionHelper = require('../../reverse_engineering/helpers/connectionHelper'); -const loggerHelper = require('../../reverse_engineering/helpers/logHelper'); -const readNdJsonByLine = require('./ndJsonHelper'); - -const applyToInstanceHelper = { - async applyToInstance(data, logger, cb) { - const log = loggerHelper.createLogger({ - title: 'Applying to instance', - hiddenKeys: data.hiddenKeys, - logger, - }); - - try { - logger.clear(); - log.info(loggerHelper.getSystemInfo(data.appVersion)); - log.info(data); - - const connection = await connectionHelper.connect(data); - - const {scriptWithSamples, numberOfSamples} = await generateScriptForInsertingDataInBulk(data.script, data.entitiesData, log); - const mongodbScript = replaceUseCommand(convertBson(scriptWithSamples)); - await runMongoDbScript({ - mongodbScript, - logger: log, - connection, - numberOfSamples, - }); - - connectionHelper.close(); - cb(null); - } catch (error) { - log.error(error); - connectionHelper.close(); - - cb({ - message: error.message, - stack: error.stack, - }); - } - }, - - async testConnection(connectionInfo, logger, cb){ - const log = loggerHelper.createLogger({ - title: 'Test connection', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); - - try { - logger.clear(); - log.info(loggerHelper.getSystemInfo(connectionInfo.appVersion)); - log.info(connectionInfo); - - await connectionHelper.connect(connectionInfo); - connectionHelper.close(); - - log.info('Connected successfully'); - - cb(); - } catch (error) { - log.error(error); - - return cb({ - message: error.message, - stack: error.stack, - }); - } - }, -}; - -const replaceUseCommand = (script) => { - return script.split('\n').filter(Boolean).map(line => { - const useStatement = /^use\ ([\s\S]+);$/i; - const result = line.match(useStatement); - - if (!result) { - return line; - } - - return `useDb("${result[1]}");`; - }).join('\n'); -}; - -const runMongoDbScript = ({ mongodbScript, logger: loggerInstance, connection, numberOfSamples }) => { - let currentDb; - let commands = []; - let insertedSamples = 0; - let prevInsertingProgress = 0; - const logger = createProgressLog(loggerInstance); - - logger.info('Start applying instance ...'); - - const context = { - ISODate: (d) => new Date(d), - ObjectId: bson.ObjectId, - Binary: bson.Binary, - BinData: (i, data) => bson.Binary(data), - MinKey: bson.MinKey, - MaxKey: bson.MaxKey, - Code: bson.Code, - Timestamp: bson.Timestamp, - - useDb(dbName) { - currentDb = dbName; - }, - - db: { - createCollection(collectionName) { - const command = () => connection.createCollection(currentDb, collectionName).then(() => { - logger.info(`Collection ${collectionName} created`); - }, (error) => { - const errMessage = `Collection ${collectionName} not created`; - logger.error(error, errMessage); - error.message = errMessage; - - return Promise.reject(error); - }); - - commands.push(command); - }, - getCollection(collectionName) { - const collection = connection.getCollection(currentDb, collectionName); - - return { - createIndex(fields, params = {}) { - const command = () => collection.createIndex(fields, params).then(() => { - logger.info(`index ${params.name} created`); - }, (error) => { - const errMessage = `index ${params.name} not created`; - logger.error(error, errMessage); - error.message = errMessage; - - return Promise.reject(error); - }); - - commands.push(command); - }, - insert(data) { - const command = () => collection.insertOne(data).then(() => { - insertedSamples++; - const insertingProgress = Math.round((insertedSamples / numberOfSamples) * 100); - if (insertingProgress - prevInsertingProgress < 5) { - return; - } - prevInsertingProgress = insertingProgress; - - logger.info(`Inserting Samples: ${insertingProgress}%`); - }).catch(error => { - insertedSamples++; - const errMessage = `sample is not inserted ${insertedSamples} / ${numberOfSamples} Reason: ${error.message}`; - logger.error(error, errMessage); - error.message = errMessage; - - return Promise.reject(error); - }); - - commands.push(command); - } - }; - } - } - }; - - vm.createContext(context); - vm.runInContext(mongodbScript, context); - - return commands.reduce((prev, next) => { - return prev.then(() => next()); - }, Promise.resolve()); -}; - -const generateScriptForInsertingDataInBulk = async (script, entitiesData, logger) => { - let numberOfSamples = Object.keys(entitiesData).length; - const scriptWithSamples = await Object.values(entitiesData).reduce(async (resultScript, entityData) => { - resultScript = await resultScript; - - if (!entityData.filePath) { - return Promise.resolve(resultScript); - } - - try { - const collectionName = entityData.code || entityData.name; - const documents = await readNdJsonByLine(entityData.filePath, logger); - numberOfSamples += documents.length; - - return resultScript + documents - .map(document => `db.getCollection("${collectionName}").insert(${document});`) - .join('\n\n'); - } catch (error) { - logger.error(error, 'Error during publishing fake data in bulk'); - } - }, Promise.resolve(script + '\n\n')); - - return { scriptWithSamples, numberOfSamples }; -}; - -const createProgressLog = logger => ({ - info(message) { - logger.progress(`${message}`); - logger.info(message); - }, - error(error, message) { - logger.progress( `[color:red]failed: ${message}`); - logger.error(error); - }, - warning(message, error) { - logger.progress({ - message: `[color:orange]warning: ${message}`, - }); - if (error) { - logger.error(error); - } - } -}); - -function convertBson(sample) { - return sample.replace(/\{\s*\"\$minKey\": (\d*)\s*\}/gi, 'MinKey($1)') - .replace(/\{\s*\"\$maxKey\": (\d*)\s*\}/gi, 'MaxKey($1)'); -} - -module.exports = applyToInstanceHelper; diff --git a/forward_engineering/helpers/ndJsonHelper.js b/forward_engineering/helpers/ndJsonHelper.js deleted file mode 100644 index c64ed0e..0000000 --- a/forward_engineering/helpers/ndJsonHelper.js +++ /dev/null @@ -1,68 +0,0 @@ -const fs = require('fs'); -const { createInterface } = require('readline'); - -const createNdJsonStream = (ndJsonFilePath, onData) => { - const stream = fs.createReadStream(ndJsonFilePath); - - return createInterface({ input: stream, crlfDelay: Infinity }) - .on('line', data => { - onData(data); - }); -}; - -const shouldLogStep = line => { - if (line < 1000) { - return line % 100 === 0; - } else { - return line % 1000 === 0; - } -}; - -const getCountOfLines = filePath => - new Promise((resolve, reject) => { - let countOfLines = 0; - - try { - createNdJsonStream(filePath, () => { countOfLines++; }) - .on('close', () => { - resolve(countOfLines); - }); - } catch (error) { - reject(createFileError(error)); - } - }); - -const createFileError = error => { - const fileError = new Error(error); - - fileError.type = 'file'; - - return fileError; -}; - -const readNdJsonByLine = async (filePath, log) => { - const maxDocuments = await getCountOfLines(filePath); - let line = 0; - const documents = []; - return new Promise((resolve, reject) => { - try { - createNdJsonStream(filePath, async data => { - line++; - - if (shouldLogStep(line)) { - log.info( `NDJSON_READ_LINES - lines: ${line} / ${maxDocuments}, progress: ${line / maxDocuments}`); - } - if (data) { - documents.push(data); - } - }).on('close', () => { - log.info(`NDJSON_READ_LINES - lines: ${line} / ${maxDocuments}, progress: ${line / maxDocuments}`); - return resolve(documents); - }) - } catch (error) { - return reject(error); - } - }); -}; - -module.exports = readNdJsonByLine; diff --git a/forward_engineering/helpers/schemaHelper.js b/forward_engineering/helpers/schemaHelper.js deleted file mode 100644 index d509ff2..0000000 --- a/forward_engineering/helpers/schemaHelper.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict' - -const getPathById = (schema, id, path) => { - if (schema.GUID === id) { - return path; - } - - if (schema.properties) { - return Object.keys(schema.properties).reduce((newPath, propertyName) => { - if (newPath) { - return newPath; - } else { - return getPathById(schema.properties[propertyName], id, [...path, schema.properties[propertyName].GUID]); - } - }, undefined); - } else if (schema.items) { - if (Array.isArray(schema.items)) { - return schema.items.reduce((newPath, item) => { - if (newPath) { - return newPath; - } else { - return getPathById(item, id, [...path, item.GUID]); - } - }, undefined); - } else { - return getPathById(schema.items, id, [...path, schema.items.GUID]); - } - } -}; - -const getRootItemMetadataById = (id, properties) => { - const propertyName = Object.keys(properties).find(propertyName => (properties[propertyName].GUID === id)); - - if (properties[propertyName] && properties[propertyName].code) { - return { name: properties[propertyName].code, isActivated: properties[propertyName].isActivated }; - } - - return { name: propertyName, isActivated: properties[propertyName] && properties[propertyName].isActivated }; -}; - -const findFieldMetadataById = (id, source) => { - let path = getPathById(source, id, []); - - if (path) { - return getRootItemMetadataById(path[0], source.properties); - } else { - return { name: "" }; - } -}; - -const getNamesByIds = (ids, sources) => { - return ids.reduce((hash, id) => { - for (let i = 0; i < sources.length; i++) { - const { name, isActivated } = findFieldMetadataById(id, sources[i]); - - if (name) { - return Object.assign({}, hash, { [id]: { name, isActivated }}); - } - } - - return hash; - }, {}); -}; - -module.exports = { - getPathById, - getNamesByIds, -}; diff --git a/forward_engineering/helpers/scriptHelper.js b/forward_engineering/helpers/scriptHelper.js deleted file mode 100644 index 0f46847..0000000 --- a/forward_engineering/helpers/scriptHelper.js +++ /dev/null @@ -1,228 +0,0 @@ - -const schemaHelper = require('./schemaHelper'); - -const isObjectEmpty = obj => Object.keys(obj).length === 0; - -const filterObject = obj => Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== undefined)); - -const createIndexStatement = (...args) => { - return 'createIndex(' + args.map(filterObject).filter(arg => !isObjectEmpty(arg)).map(stringify).join(', ') + ');'; -}; - -const stringify = (data) => JSON.stringify(data, null, 2); - -const getIndexType = (indexType) => { - return ({ - 'descending': -1, - 'ascending': 1, - '2DSphere': '2dsphere', - })[indexType] || 1; -}; - -const createIndex = (index) => { - let indexKeys = index?.key; - - if (!Array.isArray(indexKeys)) { - return ''; - } - - indexKeys = indexKeys.filter(index => index.name && index.isActivated); - - if (indexKeys.length === 0) { - return ''; - } - - return createIndexStatement( - indexKeys.reduce((result, indexKey) => ({ - ...result, - [indexKey.name]: getIndexType(indexKey.type), - }), {}), - filterObject({ - name: index.name, - unique: index.unique ? index.unique : undefined, - sparse: index.sparse ? index.sparse : undefined, - background: index.background ? index.background : undefined, - expireAfterSeconds: index.expireAfterSeconds ? index.expireAfterSeconds : undefined, - }) - ); -}; - -const getContainerName = (containerData) => { - return containerData[0]?.code || containerData[0]?.name; -}; - -const getCollectionName = (entityData) => { - return entityData[0]?.code || entityData[0]?.collectionName; -}; - -const getCollection = (name) => { - return `db.getCollection("${name}")`; -}; - -const getIndexes = (entityData, data) => { - const indexes = entityData[1]?.Indxs || []; - - return indexes - .filter(index => index.isActivated !== false) - .map(fillKeys(data)) - .map(createIndex) - .filter(Boolean) - .map(index => getCollection(getCollectionName(entityData)) + '.' + index) - .join('\n\n'); -}; - -const createCollection = (entityData) => { - return `db.createCollection("${getCollectionName(entityData)}");`; -}; - -const getScript = (data) => { - const indexes = getIndexes(data.entityData, data); - const createStatement = createCollection(data.entityData); - - return [createStatement, indexes].filter(Boolean).join('\n\n'); -}; - -const updateSample = (sample) => { - let data = JSON.parse(encodedExtendedTypes(sample)); - - return decodedExtendedTypes(JSON.stringify({ - ...data, - }, null, 2)); -}; - -const fillKeys = ({ jsonSchema, definitions }) => (index) => { - const hashTable = schemaHelper.getNamesByIds( - index.key.map(key => key.keyId), - [ - jsonSchema, - definitions.internal, - definitions.model, - definitions.external, - ] - ); - - return { - ...index, - key: index.key.map(key => { - return { - ...key, - ...(hashTable[key.keyId] || {}) - }; - }), - }; -}; - -const insertSample = ({ entityData, sample }) => { - return getCollection(getCollectionName(entityData)) + `.insert(${updateSample(sample)});`; -}; - -const insertSamples = (data) => { - const useDb = useDbStatement(data.containerData); - const samples = data.entities.map(entityId => insertSample({ - entityData: (data.entityData[entityId] || []), - sample: data.jsonData[entityId], - })).join('\n\n'); - - return [useDb, samples].filter(Boolean).join('\n\n'); -}; - - -function decodedExtendedTypes(data, returnInStr) { - let decodedData; - let strData = data; - let lineBeginning = ''; - let lineEnding = ''; - - decodedData = strData - .replace(/\"\$__oid_(.*?)\"/gi, function (a, b) { - return lineBeginning + 'ObjectId("' + b + '")' + lineEnding; - }) - .replace(/\"\$__date_(.*?)\"/gi, function (a, b) { - return lineBeginning + 'ISODate("' + b + '")' + lineEnding; - }) - .replace(/\"(?:CURRENT_)?\$__tmstmp_(.*?)\"/gi, function (a, b) { - return lineBeginning + 'Timestamp(' + b + ')' + lineEnding; - }) - .replace(/\"\$__rgxp_(.*?)\"/gi, function (a, b) { - return lineBeginning + b + lineEnding; - }) - .replace(/\"\$__bindata_(\d*)_(.*?)\"/gi, function (a, b, c) { - return lineBeginning + `BinData(${b},"${c}")` + lineEnding; - }) - .replace(/\"\$__maxKey_(\d*)\"/gi, function (a, b) { - return lineBeginning + `new MaxKey(${b})` + lineEnding; - }) - .replace(/\"\$__minKey_(\d*)\"/gi, function (a, b) { - return lineBeginning + `new MinKey(${b})` + lineEnding; - }) - .replace(/\"\$__jswscope_(.*?})\"/gi, function (a, b) { - return lineBeginning + `Code("${b}")` + lineEnding; - }) - .replace(/\"\$__js_(.*?})\"/gi, function (a, b) { - return lineBeginning + `Code("${b}")` + lineEnding; - }); - - return decodedData; -}; - -function encodedExtendedTypes(data, returnInStr) { - let encodedData; - let lineBeginning = '"'; - let lineEnding = '"'; - - encodedData = data - .replace(/ObjectId\(\"(.*?)\"\)/gi, function (a, b) { - return lineBeginning + '$__oid_' + b + lineEnding; - }) - .replace(/ISODate\(\"(.*?)\"\)/gi, function (a, b) { - return lineBeginning + '$__date_' + b + lineEnding; - }) - .replace(/Timestamp\((.*?)\)/gi, function (a, b) { - return lineBeginning + '$__tmstmp_' + b + lineEnding; - }) - .replace(/\"\s*:\s*\/(.*?)\/([^,\s\]\}\n]*)/gi, function (a, b, c) { - return '": ' + lineBeginning + '$__rgxp_/' + b + '/' + c + lineEnding; - }) - .replace(/BinData\((\d*),\"(.*?)\"\)/gi, function (a, b, c) { - return lineBeginning + `$__bindata_${b}_${c}` + lineEnding; - }) - .replace( - /\"type\": \"JavaScript\(w\/scope\)\",\s*.*?\"sample\": \{\s*\"_bsontype\": \"Code\",\s*\"code\": \"(.*?})\",\s*\"scope\": .*?\s*\}/gi, - function (a, b) { - return a.replace( - /\{\s*\"_bsontype\": \"Code\",\s*\"code\": \"(.*?})\",\s*\"scope\": .*?\s*\}/, - function (a, b) { - return lineBeginning + `$__jswscope_${b}` + lineEnding; - }, - ); - }, - ) - .replace( - /\{\s*\"_bsontype\": \"Code\",\s*\"code\": \"(.*?})\".*?\s*\}/gi, - function (a, b) { - return lineBeginning + `$__js_${b}` + lineEnding; - }, - ) - .replace(/\{\s*\"\$minKey\": (\d*)\s*\}/, function (a, b) { - return lineBeginning + `$__minKey_${b}` + lineEnding; - }) - .replace(/\{\s*\"\$maxKey\": (\d*)\s*\}/, function (a, b) { - return lineBeginning + `$__maxKey_${b}` + lineEnding; - }); - - return encodedData; -}; - -const useDbStatement = (containerData) => { - const name = getContainerName(containerData); - const useDb = name ? `use ${name};` : ''; - - return useDb; -}; - -module.exports = { - getScript, - insertSample, - insertSamples, - useDbStatement, -}; diff --git a/jsonSchemaProperties.json b/jsonSchemaProperties.json index 0086051..4deb252 100644 --- a/jsonSchemaProperties.json +++ b/jsonSchemaProperties.json @@ -1,4 +1,4 @@ { "unneededFieldProps": ["collectionName", "name", "users", "indexes", "collectionUsers", "additionalProperties"], "removeIfPropsNegative": ["partitionKey", "sortKey"] -} \ No newline at end of file +} diff --git a/localization/en.json b/localization/en.json index dd43073..7664b80 100644 --- a/localization/en.json +++ b/localization/en.json @@ -134,9 +134,9 @@ "MONGODB_SCRIPT_WARNING_MESSAGE": "This view is not associated to a collection (viewOn property).", "TYPE": {}, "MODAL_WINDOW___SELECTION_DOCUMENT_KIND_REVERSE_ENGINEERING_TITLE": "Select collection field", - "MODAL_WINDOW___SELECTION_DOCUMENT_KIND_REVERSE_ENGINEERING": "No collection separation", + "MODAL_WINDOW___SELECTION_DOCUMENT_KIND_REVERSE_ENGINEERING": "No collection separation", "CONTEXT_MENU___CONVERT_TO_PATTERN_FIELD": "Convert to Pattern Field", "CONTEXT_MENU___CONVERT_PATTERN_TO_REGULAR_FIELD": "Convert to Regular Field", "CENTRAL_PANE___FE_SCRIPT": "MongoDB script", "MAIN_MENU___FORWARD_DB_BUCKETS": "MongoDB script" -} \ No newline at end of file +} diff --git a/package.json b/package.json index 7d751c1..02b9a54 100644 --- a/package.json +++ b/package.json @@ -1,56 +1,87 @@ { - "name": "DocumentDB", - "version": "0.1.7", - "versionDate": "2023-08-03", - "author": "hackolade", - "engines": { - "hackolade": "6.10.3", - "hackoladePlugin": "1.0.1" - }, - "contributes": { - "target": { - "applicationTarget": "DocumentDB", - "title": "DocumentDB", - "versions": [ - "3.6.0", - "4.0.0" - ] - }, - "features": { - "nestedCollections": false, - "forwardEngineering": { - "jsonSchema": { - "keepParentType": { - "objectId": { - "type": "string", - "pattern": "^[a-fA-F0-9]{24}$" - }, - "regex": "string", - "date": { - "type": "string", - "format": "date-time" - }, - "timestamp": { - "type": "string", - "format": "date-time" - }, - "binary": { - "type": "string", - "mediaType": "image/png", - "contentEncoding": "base64" - }, - "minKey": "number", - "maxKey": "number" - } - } - }, - "enableReverseEngineering": true, - "enableForwardEngineering": true, - "enableReverseEngineeringDetectionSchemaByContent": false, - "enableReversingDateTypeAsISODate": true, - "supportInferRelationships": true, - "enableREQueryAndSortCriteria": true - } - }, - "description": "Hackolade plugin for Amazon DocumentDB" -} + "name": "DocumentDB", + "version": "0.1.8", + "versionDate": "2023-08-03", + "author": "hackolade", + "engines": { + "hackolade": "6.10.3", + "hackoladePlugin": "1.0.1" + }, + "contributes": { + "target": { + "applicationTarget": "DocumentDB", + "title": "DocumentDB", + "versions": [ + "3.6.0", + "4.0.0", + "5.0.0" + ] + }, + "features": { + "nestedCollections": false, + "forwardEngineering": { + "jsonSchema": { + "keepParentType": { + "objectId": { + "type": "string", + "pattern": "^[a-fA-F0-9]{24}$" + }, + "regex": "string", + "date": { + "type": "string", + "format": "date-time" + }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "binary": { + "type": "string", + "mediaType": "image/png", + "contentEncoding": "base64" + }, + "minKey": "number", + "maxKey": "number" + } + } + }, + "enableReverseEngineering": true, + "enableForwardEngineering": true, + "enableReverseEngineeringDetectionSchemaByContent": false, + "enableReversingDateTypeAsISODate": true, + "supportInferRelationships": true, + "enableREQueryAndSortCriteria": true + } + }, + "description": "Hackolade plugin for Amazon DocumentDB", + "scripts": { + "lint": "eslint . --max-warnings=0", + "package": "node esbuild.package.js" + }, + "dependencies": { + "async": "^3.2.4", + "bson": "^1.1.6", + "lodash": "^4.17.21", + "mongodb": "^3.7.3", + "mongodb-collection-sample": "^4.5.1" + }, + "devDependencies": { + "@hackolade/hck-esbuild-plugins-pack": "^0.0.1", + "esbuild": "^0.19.4", + "esbuild-plugin-clean": "^1.0.1", + "eslint": "^8.51.0", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-prettier": "^5.0.0", + "lint-staged": "^14.0.1", + "prettier": "^3.0.3", + "simple-git-hooks": "^2.9.0" + }, + "lint-staged": { + "*.{js,json}": "prettier --write" + }, + "simple-git-hooks": { + "pre-commit": "npx lint-staged", + "pre-push": "npx eslint ." + }, + "release": true +} \ No newline at end of file diff --git a/properties_pane/defaultData.json b/properties_pane/defaultData.json index 1010fff..63d1f33 100644 --- a/properties_pane/defaultData.json +++ b/properties_pane/defaultData.json @@ -1,12 +1,12 @@ /* -* Copyright © 2016-2017 by IntegrIT S.A. dba Hackolade. All rights reserved. -* -* The copyright to the computer software herein is the property of IntegrIT S.A. -* The software may be used and/or copied only with the written permission of -* IntegrIT S.A. or in accordance with the terms and conditions stipulated in -* the agreement/contract under which the software has been supplied. -* -*/ + * Copyright © 2016-2017 by IntegrIT S.A. dba Hackolade. All rights reserved. + * + * The copyright to the computer software herein is the property of IntegrIT S.A. + * The software may be used and/or copied only with the written permission of + * IntegrIT S.A. or in accordance with the terms and conditions stipulated in + * the agreement/contract under which the software has been supplied. + * + */ { "model": { "modelName": "New model", @@ -38,4 +38,4 @@ "viewOn": "", "pipeline": "" } -} \ No newline at end of file +} diff --git a/properties_pane/entity_level/entityLevelConfig.json b/properties_pane/entity_level/entityLevelConfig.json index 102b598..21ae901 100644 --- a/properties_pane/entity_level/entityLevelConfig.json +++ b/properties_pane/entity_level/entityLevelConfig.json @@ -150,83 +150,77 @@ making sure that you maintain a proper JSON format. }, { "lowerTab": "Indexes", - "structure": [{ - "propertyName": "Index", - "propertyType": "group", - "propertyKeyword": "Indxs", - "propertyTooltip": "Click + to add an index", - "erdIndexAbbr": "I", - "structure": [ - { - "propertyName": "Name", - "propertyKeyword": "name", - "propertyTooltip": "", - "propertyType": "text" - }, - { - "propertyName": "Activated", - "propertyKeyword": "isActivated", - "propertyTooltip": "Deactivated item will be not included in forward-engineering script", - "propertyType": "checkbox", - "defaultValue": true - }, - { - "propertyName": "Keys", - "propertyKeyword": "key", - "propertyType": "fieldList", - "template": "orderedList", - "attributeList": [ - "ascending", - "descending", - "2DSphere" - ] - }, - { - "propertyName": "Unique", - "propertyKeyword": "unique", - "propertyType": "checkbox" - }, - { - "propertyName": "Sparse", - "propertyKeyword": "sparse", - "propertyType": "checkbox" - }, - { - "propertyName": "Background indexing", - "propertyKeyword": "background", - "propertyType": "checkbox" - }, - { - "propertyName": "Expire after (seconds)", - "propertyKeyword": "expireAfterSeconds", - "propertyType": "numeric", - "valueType": "number", - "allowNegative": false - }, - { - "propertyName": "2D Sphere", - "propertyKeyword": "2dsphere", - "propertyType": "block", - "propertyTooltip": "", - "dependency": { - "key": "key.*.type", - "value": "2DSphere" + "structure": [ + { + "propertyName": "Index", + "propertyType": "group", + "propertyKeyword": "Indxs", + "propertyTooltip": "Click + to add an index", + "erdIndexAbbr": "I", + "structure": [ + { + "propertyName": "Name", + "propertyKeyword": "name", + "propertyTooltip": "", + "propertyType": "text" }, - "structure": [ - { - "propertyName": "Index version", - "propertyKeyword": "2dsphereIndexVersion", - "propertyTooltip": "Select from list of options", - "propertyType": "select", - "options": [ - "default", - "Version 2", - "Version 1" - ] - } - ] - } - ] - }] + { + "propertyName": "Activated", + "propertyKeyword": "isActivated", + "propertyTooltip": "Deactivated item will be not included in forward-engineering script", + "propertyType": "checkbox", + "defaultValue": true + }, + { + "propertyName": "Keys", + "propertyKeyword": "key", + "propertyType": "fieldList", + "template": "orderedList", + "attributeList": ["ascending", "descending", "2DSphere"] + }, + { + "propertyName": "Unique", + "propertyKeyword": "unique", + "propertyType": "checkbox" + }, + { + "propertyName": "Sparse", + "propertyKeyword": "sparse", + "propertyType": "checkbox" + }, + { + "propertyName": "Background indexing", + "propertyKeyword": "background", + "propertyType": "checkbox" + }, + { + "propertyName": "Expire after (seconds)", + "propertyKeyword": "expireAfterSeconds", + "propertyType": "numeric", + "valueType": "number", + "allowNegative": false + }, + { + "propertyName": "2D Sphere", + "propertyKeyword": "2dsphere", + "propertyType": "block", + "propertyTooltip": "", + "dependency": { + "key": "key.*.type", + "value": "2DSphere" + }, + "structure": [ + { + "propertyName": "Index version", + "propertyKeyword": "2dsphereIndexVersion", + "propertyTooltip": "Select from list of options", + "propertyType": "select", + "options": ["default", "Version 2", "Version 1"] + } + ] + } + ] + } + ] } -] \ No newline at end of file +] diff --git a/properties_pane/field_level/fieldLevelConfig.json b/properties_pane/field_level/fieldLevelConfig.json index 67f40bf..fbee2a2 100644 --- a/properties_pane/field_level/fieldLevelConfig.json +++ b/properties_pane/field_level/fieldLevelConfig.json @@ -197,12 +197,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "mode", "propertyTooltip": "Select from list of options", "propertyType": "select", - "options": [ - "", - "int32", - "int64", - "double" - ] + "options": ["", "int32", "int64", "double"] }, "minimum", "exclusiveMinimum", @@ -459,4 +454,4 @@ making sure that you maintain a proper JSON format. "comments" ] } -} \ No newline at end of file +} diff --git a/properties_pane/model_level/modelLevelConfig.json b/properties_pane/model_level/modelLevelConfig.json index 161ce94..35395a8 100644 --- a/properties_pane/model_level/modelLevelConfig.json +++ b/properties_pane/model_level/modelLevelConfig.json @@ -123,9 +123,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "dbVendor", "propertyTooltip": "db vendor", "propertyType": "select", - "options": [ - "DocumentDB" - ], + "options": ["DocumentDB"], "disabledOption": true }, { @@ -133,10 +131,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "dbVersion", "propertyTooltip": "Database version", "propertyType": "select", - "options": [ - "3.6.0", - "4.0.0" - ] + "options": ["3.6.0", "4.0.0", "5.0.0"] }, { "propertyName": "Region", @@ -144,22 +139,22 @@ making sure that you maintain a proper JSON format. "propertyTooltip": "Select from list of options", "propertyType": "select", "options": [ - {"name": "US East (N. Virginia)", "value": "us-east-1"}, - {"name": "US East (Ohio)", "value": "us-east-2"}, - {"name": "AWS GovCloud (US)", "value": "us-gov-west-1"}, - {"name": "US West (Oregon)", "value": "us-west-2"}, - {"name": "Canada (Central)", "value": "ca-central-1"}, - {"name": "South America (São Paulo)", "value": "sa-east-1"}, - {"name": "Europe (Frankfurt)", "value": "eu-central-1"}, - {"name": "Europe (Ireland)", "value": "eu-west-1"}, - {"name": "Europe (London)", "value": "eu-west-2"}, - {"name": "Europe (Paris)", "value": "eu-west-3"}, - {"name": "China (Ningxia)", "value": "cn-northwest-1"}, - {"name": "Asia Pacific (Singapore)", "value": "ap-southeast-1"}, - {"name": "Asia Pacific (Sydney)", "value": "ap-southeast-2"}, - {"name": "Asia Pacific (Tokyo)", "value": "ap-northeast-1"}, - {"name": "Asia Pacific (Seoul)", "value": "ap-northeast-2"}, - {"name": "Asia Pacific (Mumbai)", "value": "ap-south-1"} + { "name": "US East (N. Virginia)", "value": "us-east-1" }, + { "name": "US East (Ohio)", "value": "us-east-2" }, + { "name": "AWS GovCloud (US)", "value": "us-gov-west-1" }, + { "name": "US West (Oregon)", "value": "us-west-2" }, + { "name": "Canada (Central)", "value": "ca-central-1" }, + { "name": "South America (São Paulo)", "value": "sa-east-1" }, + { "name": "Europe (Frankfurt)", "value": "eu-central-1" }, + { "name": "Europe (Ireland)", "value": "eu-west-1" }, + { "name": "Europe (London)", "value": "eu-west-2" }, + { "name": "Europe (Paris)", "value": "eu-west-3" }, + { "name": "China (Ningxia)", "value": "cn-northwest-1" }, + { "name": "Asia Pacific (Singapore)", "value": "ap-southeast-1" }, + { "name": "Asia Pacific (Sydney)", "value": "ap-southeast-2" }, + { "name": "Asia Pacific (Tokyo)", "value": "ap-northeast-1" }, + { "name": "Asia Pacific (Seoul)", "value": "ap-northeast-2" }, + { "name": "Asia Pacific (Mumbai)", "value": "ap-south-1" } ] }, { @@ -180,10 +175,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "dbInstanceRole", "propertyType": "select", "defaultValue": "Reader", - "options": [ - "Primary", - "Replica" - ] + "options": ["Primary", "Replica"] } ] }, @@ -296,15 +288,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "startDay", "propertyTooltip": "Select from list of options", "propertyType": "select", - "options": [ - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday" - ], + "options": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], "dependency": { "key": "maintenance", "value": true @@ -483,4 +467,4 @@ making sure that you maintain a proper JSON format. } ] } -] \ No newline at end of file +] diff --git a/properties_pane/samples.json b/properties_pane/samples.json index 3620742..63c9314 100644 --- a/properties_pane/samples.json +++ b/properties_pane/samples.json @@ -32,4 +32,4 @@ "value": "double" } } -] \ No newline at end of file +] diff --git a/properties_pane/view_level/viewLevelConfig.json b/properties_pane/view_level/viewLevelConfig.json index f35cb1a..57278e2 100644 --- a/properties_pane/view_level/viewLevelConfig.json +++ b/properties_pane/view_level/viewLevelConfig.json @@ -128,4 +128,4 @@ making sure that you maintain a proper JSON format. } ] } -] \ No newline at end of file +] diff --git a/reverse_engineering/api.js b/reverse_engineering/api.js index 3073d9b..2fb4c9a 100644 --- a/reverse_engineering/api.js +++ b/reverse_engineering/api.js @@ -1,483 +1,61 @@ -'use strict'; - -const connectionHelper = require('./helpers/connectionHelper'); -const { createLogger, getSystemInfo } = require('./helpers/logHelper'); -const bson = require('bson'); -const awsHelper = require('./helpers/awsHelper'); - -module.exports = { - disconnect: function (connectionInfo, logger, cb) { - connectionHelper.close(); - cb(); - }, - - async testConnection(connectionInfo, logger, cb) { - const log = createLogger({ - title: 'Test connection', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); - - try { - logger.clear(); - log.info(getSystemInfo(connectionInfo.appVersion)); - log.info(connectionInfo); - - await connectionHelper.connect(connectionInfo); - - log.info('Connected successfully'); - - cb(); - } catch (error) { - log.error(error); - - return cb({ - message: error.message, - stack: error.stack, - }); - } - }, - - async getDbCollectionsNames(connectionInfo, logger, cb, app) { - const log = createLogger({ - title: 'Retrieving databases and collections information', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); - - try { - const _ = app.require('lodash'); - const async = app.require('async'); - const awsSdk = app.require('aws-sdk'); - - awsHelper( - { - ...connectionInfo, - ...parseHost(connectionInfo.host, log), - }, - awsSdk, - ); - - logger.clear(); - log.info(getSystemInfo(connectionInfo.appVersion)); - log.info(connectionInfo); - - const includeSystemCollection = connectionInfo.includeSystemCollection; - const connection = await connectionHelper.connect(connectionInfo); - - const databases = await connection.getDatabases(); - - const result = await async.mapSeries(databases, async database => { - const collections = await connection.getCollections(database.name); - let dbCollections = collections.map(collection => collection.name); - - log.info({ - message: 'Found collections', - collections: dbCollections, - }); - - dbCollections = await async.filter(dbCollections, async collectionName => { - return connection.hasPermission(database.name, collectionName); - }); - - log.info({ - message: 'Collections that user has access to', - collections: dbCollections, - }); - - if (!includeSystemCollection) { - dbCollections = filterSystemCollections(dbCollections); - } - - log.info({ - message: 'Collections to process', - collections: dbCollections, - }); - - return { - dbName: database.name, - dbCollections, - isEmpty: dbCollections.length === 0, - }; - }); - - log.info('Names retrieved successfully'); - - cb(null, result); - } catch (error) { - log.error(error); - cb({ message: error.message, stack: error.stack }); - } - }, - - async getDbCollectionsData(data, logger, cb, app) { - const log = createLogger({ - title: 'Retrieving data for inferring schema', - hiddenKeys: data.hiddenKeys, - logger, - }); - - try { - const async = app.require('async'); - const _ = app.require('lodash'); - const { recordSamplingSettings, fieldInference, includeEmptyCollection, collectionData } = data; - const query = safeParse(data.queryCriteria); - const sort = safeParse(data.sortCriteria); - const maxTimeMS = Number(data.queryRequestTimeout) || 120000; - const awsConnection = awsHelper(); - - log.info({ - title: 'Parameters', - sampling: getSamplingInfo(recordSamplingSettings, fieldInference), - data, - }); - - const connection = await connectionHelper.connect(); - const dbInfo = await connection.getBuildInfo(); - let modelInfo = { - version: dbInfo.version, - }; - log.progress('Start reverse-engineering'); - - try { - log.info('Getting cluster information'); - log.progress('Getting cluster information ...'); - - const cluster = await awsConnection.getCluster(); - if (!cluster) { - throw new Error("Cluster doesn't exist in the chosen region."); - } - const tags = await awsConnection.tags(cluster['DBClusterArn']); - const clusterData = getClusterData(cluster); - modelInfo = { - ...modelInfo, - 'source-region': awsConnection.getRegion(), - ...clusterData, - tags: tags['TagList']?.map(tag => ({ - tagName: tag['Key'], - tagValue: tag['Value'], - })), - }; - } catch (e) { - log.progress('[color:red]Error of getting cluster information'); - log.info( - 'Cannot get information about the cluster from AWS. Please, check AWS credentials in the connection settings.', - ); - log.error(e); - } - - const result = await async.reduce(collectionData.dataBaseNames, [], async (result, dbName) => { - return await async.reduce(collectionData.collections[dbName], result, async (result, collectionName) => { - log.info({ message: 'Calculate count of documents', dbName, collectionName }); - log.progress('Calculate count of documents', dbName, collectionName); - - const count = await connection.getCount(dbName, collectionName); - - if (!includeEmptyCollection && count === 0) { - return result; - } - - const limit = getSampleDocSize(count, recordSamplingSettings); - - log.info({ - message: 'Getting documents for sampling', - dbName, - collectionName, - countOfDocuments: count, - documentsToSample: limit, - }); - log.progress('Getting documents for sampling', dbName, collectionName); - - const documents = await connection.getRandomDocuments(dbName, collectionName, { - maxTimeMS, - limit, - query, - sort, - }); - let standardDoc = {}; - - if (fieldInference.active === 'field') { - log.info({ message: 'Getting a document for inferring', dbName, collectionName }); - log.progress('Getting a document for inferring', dbName, collectionName); - - standardDoc = await connection.findOne(dbName, collectionName, query); - } - - log.info({ message: 'Getting indexes', dbName, collectionName }); - log.progress('Getting indexes', dbName, collectionName); - - const indexes = await connection.getIndexes(dbName, collectionName); - - const packageData = { - dbName, - collectionName, - documents: documents, - relationshipDocuments: filterPotentialForeignKeys(documents), - primaryKey: '_id', - standardDoc, - validation: { - jsonSchema: getJsonSchema(documents[0]), - }, - entityLevel: { - Indxs: getIndexes(indexes), - }, - }; - - log.info({ message: 'Collection processed', dbName, collectionName }); - log.progress('Collection processed', dbName, collectionName); - - return result.concat(packageData); - }); - }); - - cb(null, result, modelInfo, []); - } catch (error) { - log.error(error); - cb({ message: error.message, stack: error.stack }); - } - }, -}; - -const safeParse = data => { - try { - return JSON.parse(data); - } catch (e) { - return {}; - } -}; - -const filterPotentialForeignKeys = documents => { - const isObject = item => item && typeof item === 'object'; - const isEmpty = item => { - if (!item) { - return true; - } - - if (Array.isArray(item)) { - return item.length === 0; - } - - if (isObject(item)) { - return Object.keys(item).length === 0; - } - - return false; - }; - - const iterateProps = document => { - return Object.keys(document).reduce((obj, prop) => { - if (document?.[prop]?._bsontype === 'ObjectID') { - return { ...obj, [prop]: document[prop] }; - } else if (document?.[prop]?._bsontype === 'DBRef') { - return { ...obj }; - } - - if (isObject(document[prop]) || Array.isArray(document[prop])) { - const innerData = iterateProps(document[prop]); - if (isEmpty(innerData)) { - return { ...obj }; - } - return { ...obj, [prop]: innerData }; - } - - return { ...obj }; - }, {}); - }; - - return documents.map(document => iterateProps(document)).filter(item => !isEmpty(item)); -}; - -function getSamplingInfo(recordSamplingSettings, fieldInference) { - let samplingInfo = {}; - let value = recordSamplingSettings[recordSamplingSettings.active].value; - let unit = recordSamplingSettings.active === 'relative' ? '%' : ' records max'; - samplingInfo.recordSampling = `${recordSamplingSettings.active} ${value}${unit}`; - samplingInfo.fieldInference = fieldInference.active === 'field' ? 'keep field order' : 'alphabetical order'; - return samplingInfo; +"use strict";var gP=Object.defineProperty;var o=(e,t)=>gP(e,"name",{value:t,configurable:!0});var w=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var e_=w((Tc,QE)=>{(function(e,t){typeof Tc=="object"&&typeof QE<"u"?t(Tc):typeof define=="function"&&define.amd?define(["exports"],t):t(e.async={})})(Tc,function(e){"use strict";function t(y,...p){return(...g)=>y(...p,...g)}o(t,"apply");function r(y){return function(...p){var g=p.pop();return y.call(this,p,g)}}o(r,"initialParams");var n=typeof queueMicrotask=="function"&&queueMicrotask,i=typeof setImmediate=="function"&&setImmediate,s=typeof process=="object"&&typeof process.nextTick=="function";function a(y){setTimeout(y,0)}o(a,"fallback");function u(y){return(p,...g)=>y(()=>p(...g))}o(u,"wrap");var c;n?c=queueMicrotask:i?c=setImmediate:s?c=process.nextTick:c=a;var f=u(c);function h(y){return m(y)?function(...p){let g=p.pop(),v=y.apply(this,p);return l(v,g)}:r(function(p,g){var v;try{v=y.apply(this,p)}catch(C){return g(C)}if(v&&typeof v.then=="function")return l(v,g);g(null,v)})}o(h,"asyncify");function l(y,p){return y.then(g=>{d(p,null,g)},g=>{d(p,g&&g.message?g:new Error(g))})}o(l,"handlePromise");function d(y,p,g){try{y(p,g)}catch(v){f(C=>{throw C},v)}}o(d,"invokeCallback");function m(y){return y[Symbol.toStringTag]==="AsyncFunction"}o(m,"isAsync");function S(y){return y[Symbol.toStringTag]==="AsyncGenerator"}o(S,"isAsyncGenerator");function E(y){return typeof y[Symbol.asyncIterator]=="function"}o(E,"isAsyncIterable");function O(y){if(typeof y!="function")throw new Error("expected a function");return m(y)?h(y):y}o(O,"wrapAsync");function T(y,p=y.length){if(!p)throw new Error("arity is undefined");function g(...v){return typeof v[p-1]=="function"?y.apply(this,v):new Promise((C,A)=>{v[p-1]=(M,...x)=>{if(M)return A(M);C(x.length>1?x:x[0])},y.apply(this,v)})}return o(g,"awaitable"),g}o(T,"awaitify");function R(y){return o(function(g,...v){return T(function(A){var M=this;return y(g,(x,L)=>{O(x).apply(M,v.concat(L))},A)})},"applyEach")}o(R,"applyEach");function _(y,p,g,v){p=p||[];var C=[],A=0,M=O(g);return y(p,(x,L,Z)=>{var _e=A++;M(x,(xe,be)=>{C[_e]=be,Z(xe)})},x=>{v(x,C)})}o(_,"_asyncMap");function N(y){return y&&typeof y.length=="number"&&y.length>=0&&y.length%1===0}o(N,"isArrayLike");let P={};function q(y){function p(...g){if(y!==null){var v=y;y=null,v.apply(this,g)}}return o(p,"wrapper"),Object.assign(p,y),p}o(q,"once");function H(y){return y[Symbol.iterator]&&y[Symbol.iterator]()}o(H,"getIterator");function ue(y){var p=-1,g=y.length;return o(function(){return++p=p||M||C||(M=!0,y.next().then(({value:be,done:dr})=>{if(!(A||C)){if(M=!1,dr){C=!0,x<=0&&v(null);return}x++,g(be,L,_e),L++,Z()}}).catch(xe))}o(Z,"replenish");function _e(be,dr){if(x-=1,!A){if(be)return xe(be);if(be===!1){C=!0,A=!0;return}if(dr===P||C&&x<=0)return C=!0,v(null);Z()}}o(_e,"iterateeCallback");function xe(be){A||(M=!1,C=!0,v(be))}o(xe,"handleError"),Z()}o(z,"asyncEachOfLimit");var Y=o(y=>(p,g,v)=>{if(v=q(v),y<=0)throw new RangeError("concurrency limit cannot be less than 1");if(!p)return v(null);if(S(p))return z(p,y,g,v);if(E(p))return z(p[Symbol.asyncIterator](),y,g,v);var C=K(p),A=!1,M=!1,x=0,L=!1;function Z(xe,be){if(!M)if(x-=1,xe)A=!0,v(xe);else if(xe===!1)A=!0,M=!0;else{if(be===P||A&&x<=0)return A=!0,v(null);L||_e()}}o(Z,"iterateeCallback");function _e(){for(L=!0;x1?C:C[0])}return o(g,"callback"),g[nr]=new Promise((v,C)=>{y=v,p=C}),g}o(Ue,"promiseCallback");function Br(y,p,g){typeof p!="number"&&(g=p,p=null),g=q(g||Ue());var v=Object.keys(y).length;if(!v)return g(null);p||(p=v);var C={},A=0,M=!1,x=!1,L=Object.create(null),Z=[],_e=[],xe={};Object.keys(y).forEach(J=>{var ie=y[J];if(!Array.isArray(ie)){be(J,[ie]),_e.push(J);return}var Ce=ie.slice(0,ie.length-1),Xe=Ce.length;if(Xe===0){be(J,ie),_e.push(J);return}xe[J]=Xe,Ce.forEach(pt=>{if(!y[pt])throw new Error("async.auto task `"+J+"` has a non-existent dependency `"+pt+"` in "+Ce.join(", "));Os(pt,()=>{Xe--,Xe===0&&be(J,ie)})})}),qe(),dr();function be(J,ie){Z.push(()=>oa(J,ie))}o(be,"enqueueTask");function dr(){if(!M){if(Z.length===0&&A===0)return g(null,C);for(;Z.length&&ACe()),dr()}o(bi,"taskComplete");function oa(J,ie){if(!x){var Ce=W((pt,...pr)=>{if(A--,pt===!1){M=!0;return}if(pr.length<2&&([pr]=pr),pt){var vs={};if(Object.keys(C).forEach(Ci=>{vs[Ci]=C[Ci]}),vs[J]=pr,x=!0,L=Object.create(null),M)return;g(pt,vs)}else C[J]=pr,bi(J)});A++;var Xe=O(ie[ie.length-1]);ie.length>1?Xe(C,Ce):Xe(Ce)}}o(oa,"runTask");function qe(){for(var J,ie=0;_e.length;)J=_e.pop(),ie++,ne(J).forEach(Ce=>{--xe[Ce]===0&&_e.push(Ce)});if(ie!==v)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}o(qe,"checkForDeadlocks");function ne(J){var ie=[];return Object.keys(y).forEach(Ce=>{let Xe=y[Ce];Array.isArray(Xe)&&Xe.indexOf(J)>=0&&ie.push(Ce)}),ie}return o(ne,"getDependents"),g[nr]}o(Br,"auto");var Rr=/^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/,gs=/^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/,Xo=/,/,_i=/(=.+)?(\s*)$/;function Ss(y){let p="",g=0,v=y.indexOf("*/");for(;gC.replace(_i,"").trim())}o(ec,"parseParams");function Wr(y,p){var g={};return Object.keys(y).forEach(v=>{var C=y[v],A,M=m(C),x=!M&&C.length===1||M&&C.length===0;if(Array.isArray(C))A=[...C],C=A.pop(),g[v]=A.concat(A.length>0?L:C);else if(x)g[v]=C;else{if(A=ec(C),C.length===0&&!M&&A.length===0)throw new Error("autoInject task functions require explicit parameters.");M||A.pop(),g[v]=A.concat(L)}function L(Z,_e){var xe=A.map(be=>Z[be]);xe.push(_e),O(C)(...xe)}o(L,"newTask")}),Br(g,p)}o(Wr,"autoInject");let Xd=class Xd{constructor(){this.head=this.tail=null,this.length=0}removeLink(p){return p.prev?p.prev.next=p.next:this.head=p.next,p.next?p.next.prev=p.prev:this.tail=p.prev,p.prev=p.next=null,this.length-=1,p}empty(){for(;this.head;)this.shift();return this}insertAfter(p,g){g.prev=p,g.next=p.next,p.next?p.next.prev=g:this.tail=g,p.next=g,this.length+=1}insertBefore(p,g){g.prev=p.prev,g.next=p,p.prev?p.prev.next=g:this.head=g,p.prev=g,this.length+=1}unshift(p){this.head?this.insertBefore(this.head,p):Jo(this,p)}push(p){this.tail?this.insertAfter(this.tail,p):Jo(this,p)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var p=this.head;p;)yield p.data,p=p.next}remove(p){for(var g=this.head;g;){var{next:v}=g;p(g)&&this.removeLink(g),g=v}return this}};o(Xd,"DLL");let Ti=Xd;function Jo(y,p){y.length=1,y.head=y.tail=p}o(Jo,"setInitial");function Zo(y,p,g){if(p==null)p=1;else if(p===0)throw new RangeError("Concurrency must not be zero");var v=O(y),C=0,A=[];let M={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function x(ne,J){M[ne].push(J)}o(x,"on");function L(ne,J){let ie=o((...Ce)=>{Z(ne,ie),J(...Ce)},"handleAndRemove");M[ne].push(ie)}o(L,"once");function Z(ne,J){if(!ne)return Object.keys(M).forEach(ie=>M[ie]=[]);if(!J)return M[ne]=[];M[ne]=M[ne].filter(ie=>ie!==J)}o(Z,"off");function _e(ne,...J){M[ne].forEach(ie=>ie(...J))}o(_e,"trigger");var xe=!1;function be(ne,J,ie,Ce){if(Ce!=null&&typeof Ce!="function")throw new Error("task callback must be a function");qe.started=!0;var Xe,pt;function pr(Ci,...aa){if(Ci)return ie?pt(Ci):Xe();if(aa.length<=1)return Xe(aa[0]);Xe(aa)}o(pr,"promiseCallback");var vs=qe._createTaskItem(ne,ie?pr:Ce||pr);if(J?qe._tasks.unshift(vs):qe._tasks.push(vs),xe||(xe=!0,f(()=>{xe=!1,qe.process()})),ie||!Ce)return new Promise((Ci,aa)=>{Xe=Ci,pt=aa})}o(be,"_insert");function dr(ne){return function(J,...ie){C-=1;for(var Ce=0,Xe=ne.length;Ce0&&A.splice(pr,1),pt.callback(J,...ie),J!=null&&_e("error",J,pt.data)}C<=qe.concurrency-qe.buffer&&_e("unsaturated"),qe.idle()&&_e("drain"),qe.process()}}o(dr,"_createCB");function Os(ne){return ne.length===0&&qe.idle()?(f(()=>_e("drain")),!0):!1}o(Os,"_maybeDrain");let bi=o(ne=>J=>{if(!J)return new Promise((ie,Ce)=>{L(ne,(Xe,pt)=>{if(Xe)return Ce(Xe);ie(pt)})});Z(ne),x(ne,J)},"eventMethod");var oa=!1,qe={_tasks:new Ti,_createTaskItem(ne,J){return{data:ne,callback:J}},*[Symbol.iterator](){yield*qe._tasks[Symbol.iterator]()},concurrency:p,payload:g,buffer:p/4,started:!1,paused:!1,push(ne,J){return Array.isArray(ne)?Os(ne)?void 0:ne.map(ie=>be(ie,!1,!1,J)):be(ne,!1,!1,J)},pushAsync(ne,J){return Array.isArray(ne)?Os(ne)?void 0:ne.map(ie=>be(ie,!1,!0,J)):be(ne,!1,!0,J)},kill(){Z(),qe._tasks.empty()},unshift(ne,J){return Array.isArray(ne)?Os(ne)?void 0:ne.map(ie=>be(ie,!0,!1,J)):be(ne,!0,!1,J)},unshiftAsync(ne,J){return Array.isArray(ne)?Os(ne)?void 0:ne.map(ie=>be(ie,!0,!0,J)):be(ne,!0,!0,J)},remove(ne){qe._tasks.remove(ne)},process(){if(!oa){for(oa=!0;!qe.paused&&C{C(p,A,(L,Z)=>{p=Z,x(L)})},A=>v(A,p))}o(ea,"reduce");var Wn=T(ea,4);function $d(...y){var p=y.map(O);return function(...g){var v=this,C=g[g.length-1];return typeof C=="function"?g.pop():C=Ue(),Wn(p,g,(A,M,x)=>{M.apply(v,A.concat((L,...Z)=>{x(L,Z)}))},(A,M)=>C(A,...M)),C[nr]}}o($d,"seq");function gE(...y){return $d(...y.reverse())}o(gE,"compose");function qD(y,p,g,v){return _(Y(p),y,g,v)}o(qD,"mapLimit");var ta=T(qD,4);function DD(y,p,g,v){var C=O(g);return ta(y,p,(A,M)=>{C(A,(x,...L)=>x?M(x):M(x,L))},(A,M)=>{for(var x=[],L=0;L{var M=!1,x;let L=O(C);g(v,(Z,_e,xe)=>{L(Z,(be,dr)=>{if(be||be===!1)return xe(be);if(y(dr)&&!x)return M=!0,x=p(!0,Z),xe(null,P);xe()})},Z=>{if(Z)return A(Z);A(null,M?x:p(!1))})}}o(nn,"_createTester");function jD(y,p,g){return nn(v=>v,(v,C)=>C)(de,y,p,g)}o(jD,"detect");var nc=T(jD,3);function UD(y,p,g,v){return nn(C=>C,(C,A)=>A)(Y(p),y,g,v)}o(UD,"detectLimit");var ic=T(UD,4);function WD(y,p,g){return nn(v=>v,(v,C)=>C)(Y(1),y,p,g)}o(WD,"detectSeries");var sc=T(WD,3);function wE(y){return(p,...g)=>O(p)(...g,(v,...C)=>{typeof console=="object"&&(v?console.error&&console.error(v):console[y]&&C.forEach(A=>console[y](A)))})}o(wE,"consoleFunc");var OE=wE("dir");function FD(y,p,g){g=W(g);var v=O(y),C=O(p),A;function M(L,...Z){if(L)return g(L);L!==!1&&(A=Z,C(...Z,x))}o(M,"next");function x(L,Z){if(L)return g(L);if(L!==!1){if(!Z)return g(null,...A);v(M)}}return o(x,"check"),x(null,!0)}o(FD,"doWhilst");var ra=T(FD,3);function vE(y,p,g){let v=O(p);return ra(y,(...C)=>{let A=C.pop();v(...C,(M,x)=>A(M,!x))},g)}o(vE,"doUntil");function EE(y){return(p,g,v)=>y(p,v)}o(EE,"_withoutIndex");function $D(y,p,g){return de(y,EE(O(p)),g)}o($D,"eachLimit");var oc=T($D,3);function zD(y,p,g,v){return Y(p)(y,EE(O(g)),v)}o(zD,"eachLimit$1");var na=T(zD,4);function VD(y,p,g){return na(y,1,p,g)}o(VD,"eachSeries");var ia=T(VD,3);function zd(y){return m(y)?y:function(...p){var g=p.pop(),v=!0;p.push((...C)=>{v?f(()=>g(...C)):g(...C)}),y.apply(this,p),v=!1}}o(zd,"ensureAsync");function HD(y,p,g){return nn(v=>!v,v=>!v)(de,y,p,g)}o(HD,"every");var ac=T(HD,3);function kD(y,p,g,v){return nn(C=>!C,C=>!C)(Y(p),y,g,v)}o(kD,"everyLimit");var uc=T(kD,4);function YD(y,p,g){return nn(v=>!v,v=>!v)(Ye,y,p,g)}o(YD,"everySeries");var cc=T(YD,3);function GD(y,p,g,v){var C=new Array(p.length);y(p,(A,M,x)=>{g(A,(L,Z)=>{C[M]=!!Z,x(L)})},A=>{if(A)return v(A);for(var M=[],x=0;x{g(A,(L,Z)=>{if(L)return x(L);Z&&C.push({index:M,value:A}),x(L)})},A=>{if(A)return v(A);v(null,C.sort((M,x)=>M.index-x.index).map(M=>M.value))})}o(KD,"filterGeneric");function fc(y,p,g,v){var C=N(p)?GD:KD;return C(y,p,O(g),v)}o(fc,"_filter");function XD(y,p,g){return fc(de,y,p,g)}o(XD,"filter");var lc=T(XD,3);function JD(y,p,g,v){return fc(Y(p),y,g,v)}o(JD,"filterLimit");var hc=T(JD,4);function ZD(y,p,g){return fc(Ye,y,p,g)}o(ZD,"filterSeries");var dc=T(ZD,3);function QD(y,p){var g=W(p),v=O(zd(y));function C(A){if(A)return g(A);A!==!1&&v(C)}return o(C,"next"),C()}o(QD,"forever");var _E=T(QD,2);function eP(y,p,g,v){var C=O(g);return ta(y,p,(A,M)=>{C(A,(x,L)=>x?M(x):M(x,{key:L,val:A}))},(A,M)=>{for(var x={},{hasOwnProperty:L}=Object.prototype,Z=0;Z{A(M,x,(Z,_e)=>{if(Z)return L(Z);C[x]=_e,L(Z)})},M=>v(M,C))}o(tP,"mapValuesLimit");var mc=T(tP,4);function CE(y,p,g){return mc(y,1/0,p,g)}o(CE,"mapValues");function AE(y,p,g){return mc(y,1,p,g)}o(AE,"mapValuesSeries");function IE(y,p=g=>g){var g=Object.create(null),v=Object.create(null),C=O(y),A=r((M,x)=>{var L=p(...M);L in g?f(()=>x(null,...g[L])):L in v?v[L].push(x):(v[L]=[x],C(...M,(Z,..._e)=>{Z||(g[L]=_e);var xe=v[L];delete v[L];for(var be=0,dr=xe.length;be{var v=N(p)?[]:{};y(p,(C,A,M)=>{O(C)((x,...L)=>{L.length<2&&([L]=L),v[A]=L,M(x)})},C=>g(C,v))},3);function RE(y,p){return Vd(de,y,p)}o(RE,"parallel$1");function ME(y,p,g){return Vd(Y(p),y,g)}o(ME,"parallelLimit");function Hd(y,p){var g=O(y);return Zo((v,C)=>{g(v[0],C)},p,1)}o(Hd,"queue$1");let Jd=class Jd{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(p){let g;for(;p>0&&Yd(this.heap[p],this.heap[g=xE(p)]);){let v=this.heap[p];this.heap[p]=this.heap[g],this.heap[g]=v,p=g}}percDown(p){let g;for(;(g=rP(p))=0;v--)this.percDown(v);return this}};o(Jd,"Heap");let kd=Jd;function rP(y){return(y<<1)+1}o(rP,"leftChi");function xE(y){return(y+1>>1)-1}o(xE,"parent");function Yd(y,p){return y.priority!==p.priority?y.priority({data:M,priority:x,callback:L});function A(M,x){return Array.isArray(M)?M.map(L=>({data:L,priority:x})):{data:M,priority:x}}return o(A,"createDataItems"),g.push=function(M,x=0,L){return v(A(M,x),L)},g.pushAsync=function(M,x=0,L){return C(A(M,x),L)},delete g.unshift,delete g.unshiftAsync,g}o(qE,"priorityQueue");function nP(y,p){if(p=q(p),!Array.isArray(y))return p(new TypeError("First argument to race must be an array of functions"));if(!y.length)return p();for(var g=0,v=y.length;g{let x={};if(A&&(x.error=A),M.length>0){var L=M;M.length<=1&&([L]=M),x.value=L}C(null,x)}),p.apply(this,v)},"reflectOn"))}o(Sc,"reflect");function PE(y){var p;return Array.isArray(y)?p=y.map(Sc):(p={},Object.keys(y).forEach(g=>{p[g]=Sc.call(this,y[g])})),p}o(PE,"reflectAll");function Gd(y,p,g,v){let C=O(g);return fc(y,p,(A,M)=>{C(A,(x,L)=>{M(x,!L)})},v)}o(Gd,"reject");function iP(y,p,g){return Gd(de,y,p,g)}o(iP,"reject$1");var LE=T(iP,3);function sP(y,p,g,v){return Gd(Y(p),y,g,v)}o(sP,"rejectLimit");var jE=T(sP,4);function oP(y,p,g){return Gd(Ye,y,p,g)}o(oP,"rejectSeries");var UE=T(oP,3);function WE(y){return function(){return y}}o(WE,"constant$1");let Kd=5,FE=0;function wc(y,p,g){var v={times:Kd,intervalFunc:WE(FE)};if(arguments.length<3&&typeof y=="function"?(g=p||Ue(),p=y):(aP(v,y),g=g||Ue()),typeof p!="function")throw new Error("Invalid arguments for async.retry");var C=O(p),A=1;function M(){C((x,...L)=>{x!==!1&&(x&&A++{(C.lengthv)(de,y,p,g)}o(uP,"some");var Oc=T(uP,3);function cP(y,p,g,v){return nn(Boolean,C=>C)(Y(p),y,g,v)}o(cP,"someLimit");var vc=T(cP,4);function fP(y,p,g){return nn(Boolean,v=>v)(Ye,y,p,g)}o(fP,"someSeries");var Ec=T(fP,3);function lP(y,p,g){var v=O(p);return ft(y,(A,M)=>{v(A,(x,L)=>{if(x)return M(x);M(x,{value:A,criteria:L})})},(A,M)=>{if(A)return g(A);g(null,M.sort(C).map(x=>x.value))});function C(A,M){var x=A.criteria,L=M.criteria;return xL?1:0}}o(lP,"sortBy");var VE=T(lP,3);function HE(y,p,g){var v=O(y);return r((C,A)=>{var M=!1,x;function L(){var Z=y.name||"anonymous",_e=new Error('Callback function "'+Z+'" timed out.');_e.code="ETIMEDOUT",g&&(_e.info=g),M=!0,A(_e)}o(L,"timeoutCallback"),C.push((...Z)=>{M||(A(...Z),clearTimeout(x))}),x=setTimeout(L,p),v(...C)})}o(HE,"timeout");function hP(y){for(var p=Array(y);y--;)p[y]=y;return p}o(hP,"range");function _c(y,p,g,v){var C=O(g);return ta(hP(y),p,C,v)}o(_c,"timesLimit");function kE(y,p,g){return _c(y,1/0,p,g)}o(kE,"times");function YE(y,p,g){return _c(y,1,p,g)}o(YE,"timesSeries");function GE(y,p,g,v){arguments.length<=3&&typeof p=="function"&&(v=g,g=p,p=Array.isArray(y)?[]:{}),v=q(v||Ue());var C=O(g);return de(y,(A,M,x)=>{C(p,A,M,x)},A=>v(A,p)),v[nr]}o(GE,"transform");function dP(y,p){var g=null,v;return ia(y,(C,A)=>{O(C)((M,...x)=>{if(M===!1)return A(M);x.length<2?[v]=x:v=x,g=M,A(M?null:{})})},()=>p(g,v))}o(dP,"tryEach");var KE=T(dP);function XE(y){return(...p)=>(y.unmemoized||y)(...p)}o(XE,"unmemoize");function pP(y,p,g){g=W(g);var v=O(p),C=O(y),A=[];function M(L,...Z){if(L)return g(L);A=Z,L!==!1&&C(x)}o(M,"next");function x(L,Z){if(L)return g(L);if(L!==!1){if(!Z)return g(null,...A);v(M)}}return o(x,"check"),C(x)}o(pP,"whilst");var sa=T(pP,3);function JE(y,p,g){let v=O(y);return sa(C=>v((A,M)=>C(A,!M)),p,g)}o(JE,"until");function mP(y,p){if(p=q(p),!Array.isArray(y))return p(new Error("First argument to waterfall must be an array of functions"));if(!y.length)return p();var g=0;function v(A){var M=O(y[g++]);M(...A,W(C))}o(v,"nextTask");function C(A,...M){if(A!==!1){if(A||g===y.length)return p(A,...M);v(M)}}o(C,"next"),v([])}o(mP,"waterfall");var ZE=T(mP),yP={apply:t,applyEach:Ir,applyEachSeries:Un,asyncify:h,auto:Br,autoInject:Wr,cargo:Qo,cargoQueue:Ni,compose:gE,concat:tc,concatLimit:ws,concatSeries:rc,constant:SE,detect:nc,detectLimit:ic,detectSeries:sc,dir:OE,doUntil:vE,doWhilst:ra,each:oc,eachLimit:na,eachOf:de,eachOfLimit:ee,eachOfSeries:Ye,eachSeries:ia,ensureAsync:zd,every:ac,everyLimit:uc,everySeries:cc,filter:lc,filterLimit:hc,filterSeries:dc,forever:_E,groupBy:TE,groupByLimit:pc,groupBySeries:NE,log:bE,map:ft,mapLimit:ta,mapSeries:rr,mapValues:CE,mapValuesLimit:mc,mapValuesSeries:AE,memoize:IE,nextTick:BE,parallel:RE,parallelLimit:ME,priorityQueue:qE,queue:Hd,race:DE,reduce:Wn,reduceRight:gc,reflect:Sc,reflectAll:PE,reject:LE,rejectLimit:jE,rejectSeries:UE,retry:wc,retryable:$E,seq:$d,series:zE,setImmediate:f,some:Oc,someLimit:vc,someSeries:Ec,sortBy:VE,timeout:HE,times:kE,timesLimit:_c,timesSeries:YE,transform:GE,tryEach:KE,unmemoize:XE,until:JE,waterfall:ZE,whilst:sa,all:ac,allLimit:uc,allSeries:cc,any:Oc,anyLimit:vc,anySeries:Ec,find:nc,findLimit:ic,findSeries:sc,flatMap:tc,flatMapLimit:ws,flatMapSeries:rc,forEach:oc,forEachSeries:ia,forEachLimit:na,forEachOf:de,forEachOfSeries:Ye,forEachOfLimit:ee,inject:Wn,foldl:Wn,foldr:gc,select:lc,selectLimit:hc,selectSeries:dc,wrapSync:h,during:sa,doDuring:ra};e.default=yP,e.apply=t,e.applyEach=Ir,e.applyEachSeries=Un,e.asyncify=h,e.auto=Br,e.autoInject=Wr,e.cargo=Qo,e.cargoQueue=Ni,e.compose=gE,e.concat=tc,e.concatLimit=ws,e.concatSeries=rc,e.constant=SE,e.detect=nc,e.detectLimit=ic,e.detectSeries=sc,e.dir=OE,e.doUntil=vE,e.doWhilst=ra,e.each=oc,e.eachLimit=na,e.eachOf=de,e.eachOfLimit=ee,e.eachOfSeries=Ye,e.eachSeries=ia,e.ensureAsync=zd,e.every=ac,e.everyLimit=uc,e.everySeries=cc,e.filter=lc,e.filterLimit=hc,e.filterSeries=dc,e.forever=_E,e.groupBy=TE,e.groupByLimit=pc,e.groupBySeries=NE,e.log=bE,e.map=ft,e.mapLimit=ta,e.mapSeries=rr,e.mapValues=CE,e.mapValuesLimit=mc,e.mapValuesSeries=AE,e.memoize=IE,e.nextTick=BE,e.parallel=RE,e.parallelLimit=ME,e.priorityQueue=qE,e.queue=Hd,e.race=DE,e.reduce=Wn,e.reduceRight=gc,e.reflect=Sc,e.reflectAll=PE,e.reject=LE,e.rejectLimit=jE,e.rejectSeries=UE,e.retry=wc,e.retryable=$E,e.seq=$d,e.series=zE,e.setImmediate=f,e.some=Oc,e.someLimit=vc,e.someSeries=Ec,e.sortBy=VE,e.timeout=HE,e.times=kE,e.timesLimit=_c,e.timesSeries=YE,e.transform=GE,e.tryEach=KE,e.unmemoize=XE,e.until=JE,e.waterfall=ZE,e.whilst=sa,e.all=ac,e.allLimit=uc,e.allSeries=cc,e.any=Oc,e.anyLimit=vc,e.anySeries=Ec,e.find=nc,e.findLimit=ic,e.findSeries=sc,e.flatMap=tc,e.flatMapLimit=ws,e.flatMapSeries=rc,e.forEach=oc,e.forEachSeries=ia,e.forEachLimit=na,e.forEachOf=de,e.forEachOfSeries=Ye,e.forEachOfLimit=ee,e.inject=Wn,e.foldl=Wn,e.foldr=gc,e.select=lc,e.selectLimit=hc,e.selectSeries=dc,e.wrapSync=h,e.during=sa,e.doDuring=ra,Object.defineProperty(e,"__esModule",{value:!0})})});var Nc=w((kte,ua)=>{"use strict";typeof global.Map<"u"?(ua.exports=global.Map,ua.exports.Map=global.Map):(ir=o(function(e){this._keys=[],this._values={};for(var t=0;t{function I(e,t){if(!(this instanceof I))return new I(e,t);this._bsontype="Long",this.low_=e|0,this.high_=t|0}o(I,"Long");I.prototype.toInt=function(){return this.low_};I.prototype.toNumber=function(){return this.high_*I.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};I.prototype.toBigInt=function(){return BigInt(this.toString())};I.prototype.toJSON=function(){return this.toString()};I.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:I.TWO_PWR_32_DBL_+this.low_};I.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(I.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=this.high_!==0?this.high_:this.low_,t=31;t>0&&!(e&1<0};I.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};I.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.subtract(e).isNegative()?-1:1};I.prototype.negate=function(){return this.equals(I.MIN_VALUE)?I.MIN_VALUE:this.not().add(I.ONE)};I.prototype.add=function(e){var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,s=e.high_>>>16,a=e.high_&65535,u=e.low_>>>16,c=e.low_&65535,f=0,h=0,l=0,d=0;return d+=i+c,l+=d>>>16,d&=65535,l+=n+u,h+=l>>>16,l&=65535,h+=r+a,f+=h>>>16,h&=65535,f+=t+s,f&=65535,I.fromBits(l<<16|d,f<<16|h)};I.prototype.subtract=function(e){return this.add(e.negate())};I.prototype.multiply=function(e){if(this.isZero())return I.ZERO;if(e.isZero())return I.ZERO;if(this.equals(I.MIN_VALUE))return e.isOdd()?I.MIN_VALUE:I.ZERO;if(e.equals(I.MIN_VALUE))return this.isOdd()?I.MIN_VALUE:I.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(I.TWO_PWR_24_)&&e.lessThan(I.TWO_PWR_24_))return I.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,s=e.high_>>>16,a=e.high_&65535,u=e.low_>>>16,c=e.low_&65535,f=0,h=0,l=0,d=0;return d+=i*c,l+=d>>>16,d&=65535,l+=n*c,h+=l>>>16,l&=65535,l+=i*u,h+=l>>>16,l&=65535,h+=r*c,f+=h>>>16,h&=65535,h+=n*u,f+=h>>>16,h&=65535,h+=i*a,f+=h>>>16,h&=65535,f+=t*c+r*u+n*a+i*s,f&=65535,I.fromBits(l<<16|d,f<<16|h)};I.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return I.ZERO;if(this.equals(I.MIN_VALUE)){if(e.equals(I.ONE)||e.equals(I.NEG_ONE))return I.MIN_VALUE;if(e.equals(I.MIN_VALUE))return I.ONE;var t=this.shiftRight(1),r=t.div(e).shiftLeft(1);if(r.equals(I.ZERO))return e.isNegative()?I.ONE:I.NEG_ONE;var n=this.subtract(e.multiply(r)),i=r.add(n.div(e));return i}else if(e.equals(I.MIN_VALUE))return I.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var s=I.ZERO;for(n=this;n.greaterThanOrEqual(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),u=a<=48?1:Math.pow(2,a-48),c=I.fromNumber(r),f=c.multiply(e);f.isNegative()||f.greaterThan(n);)r-=u,c=I.fromNumber(r),f=c.multiply(e);c.isZero()&&(c=I.ONE),s=s.add(c),n=n.subtract(f)}return s};I.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};I.prototype.not=function(){return I.fromBits(~this.low_,~this.high_)};I.prototype.and=function(e){return I.fromBits(this.low_&e.low_,this.high_&e.high_)};I.prototype.or=function(e){return I.fromBits(this.low_|e.low_,this.high_|e.high_)};I.prototype.xor=function(e){return I.fromBits(this.low_^e.low_,this.high_^e.high_)};I.prototype.shiftLeft=function(e){if(e&=63,e===0)return this;var t=this.low_;if(e<32){var r=this.high_;return I.fromBits(t<>>32-e)}else return I.fromBits(0,t<>>e|t<<32-e,t>>e)}else return I.fromBits(t>>e-32,t>=0?0:-1)};I.prototype.shiftRightUnsigned=function(e){if(e&=63,e===0)return this;var t=this.high_;if(e<32){var r=this.low_;return I.fromBits(r>>>e|t<<32-e,t>>>e)}else return e===32?I.fromBits(t,0):I.fromBits(t>>>e-32,0)};I.fromInt=function(e){if(-128<=e&&e<128){var t=I.INT_CACHE_[e];if(t)return t}var r=new I(e|0,e<0?-1:0);return-128<=e&&e<128&&(I.INT_CACHE_[e]=r),r};I.fromNumber=function(e){return isNaN(e)||!isFinite(e)?I.ZERO:e<=-I.TWO_PWR_63_DBL_?I.MIN_VALUE:e+1>=I.TWO_PWR_63_DBL_?I.MAX_VALUE:e<0?I.fromNumber(-e).negate():new I(e%I.TWO_PWR_32_DBL_|0,e/I.TWO_PWR_32_DBL_|0)};I.fromBigInt=function(e){return I.fromString(e.toString(10),10)};I.fromBits=function(e,t){return new I(e,t)};I.fromString=function(e,t){if(e.length===0)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var n=I.fromNumber(Math.pow(r,8)),i=I.ZERO,s=0;s{function Es(e){if(!(this instanceof Es))return new Es(e);this._bsontype="Double",this.value=e}o(Es,"Double");Es.prototype.valueOf=function(){return this.value};Es.prototype.toJSON=function(){return this.value};Qd.exports=Es;Qd.exports.Double=Es});var fa=w((Zte,ep)=>{function B(e,t){if(!(this instanceof B))return new B(e,t);this._bsontype="Timestamp",this.low_=e|0,this.high_=t|0}o(B,"Timestamp");B.prototype.toInt=function(){return this.low_};B.prototype.toNumber=function(){return this.high_*B.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};B.prototype.toJSON=function(){return this.toString()};B.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:B.TWO_PWR_32_DBL_+this.low_};B.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(B.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=this.high_!==0?this.high_:this.low_,t=31;t>0&&!(e&1<0};B.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};B.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.subtract(e).isNegative()?-1:1};B.prototype.negate=function(){return this.equals(B.MIN_VALUE)?B.MIN_VALUE:this.not().add(B.ONE)};B.prototype.add=function(e){var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,s=e.high_>>>16,a=e.high_&65535,u=e.low_>>>16,c=e.low_&65535,f=0,h=0,l=0,d=0;return d+=i+c,l+=d>>>16,d&=65535,l+=n+u,h+=l>>>16,l&=65535,h+=r+a,f+=h>>>16,h&=65535,f+=t+s,f&=65535,B.fromBits(l<<16|d,f<<16|h)};B.prototype.subtract=function(e){return this.add(e.negate())};B.prototype.multiply=function(e){if(this.isZero())return B.ZERO;if(e.isZero())return B.ZERO;if(this.equals(B.MIN_VALUE))return e.isOdd()?B.MIN_VALUE:B.ZERO;if(e.equals(B.MIN_VALUE))return this.isOdd()?B.MIN_VALUE:B.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(B.TWO_PWR_24_)&&e.lessThan(B.TWO_PWR_24_))return B.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=this.high_&65535,n=this.low_>>>16,i=this.low_&65535,s=e.high_>>>16,a=e.high_&65535,u=e.low_>>>16,c=e.low_&65535,f=0,h=0,l=0,d=0;return d+=i*c,l+=d>>>16,d&=65535,l+=n*c,h+=l>>>16,l&=65535,l+=i*u,h+=l>>>16,l&=65535,h+=r*c,f+=h>>>16,h&=65535,h+=n*u,f+=h>>>16,h&=65535,h+=i*a,f+=h>>>16,h&=65535,f+=t*c+r*u+n*a+i*s,f&=65535,B.fromBits(l<<16|d,f<<16|h)};B.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return B.ZERO;if(this.equals(B.MIN_VALUE)){if(e.equals(B.ONE)||e.equals(B.NEG_ONE))return B.MIN_VALUE;if(e.equals(B.MIN_VALUE))return B.ONE;var t=this.shiftRight(1),r=t.div(e).shiftLeft(1);if(r.equals(B.ZERO))return e.isNegative()?B.ONE:B.NEG_ONE;var n=this.subtract(e.multiply(r)),i=r.add(n.div(e));return i}else if(e.equals(B.MIN_VALUE))return B.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var s=B.ZERO;for(n=this;n.greaterThanOrEqual(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),u=a<=48?1:Math.pow(2,a-48),c=B.fromNumber(r),f=c.multiply(e);f.isNegative()||f.greaterThan(n);)r-=u,c=B.fromNumber(r),f=c.multiply(e);c.isZero()&&(c=B.ONE),s=s.add(c),n=n.subtract(f)}return s};B.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};B.prototype.not=function(){return B.fromBits(~this.low_,~this.high_)};B.prototype.and=function(e){return B.fromBits(this.low_&e.low_,this.high_&e.high_)};B.prototype.or=function(e){return B.fromBits(this.low_|e.low_,this.high_|e.high_)};B.prototype.xor=function(e){return B.fromBits(this.low_^e.low_,this.high_^e.high_)};B.prototype.shiftLeft=function(e){if(e&=63,e===0)return this;var t=this.low_;if(e<32){var r=this.high_;return B.fromBits(t<>>32-e)}else return B.fromBits(0,t<>>e|t<<32-e,t>>e)}else return B.fromBits(t>>e-32,t>=0?0:-1)};B.prototype.shiftRightUnsigned=function(e){if(e&=63,e===0)return this;var t=this.high_;if(e<32){var r=this.low_;return B.fromBits(r>>>e|t<<32-e,t>>>e)}else return e===32?B.fromBits(t,0):B.fromBits(t>>>e-32,0)};B.fromInt=function(e){if(-128<=e&&e<128){var t=B.INT_CACHE_[e];if(t)return t}var r=new B(e|0,e<0?-1:0);return-128<=e&&e<128&&(B.INT_CACHE_[e]=r),r};B.fromNumber=function(e){return isNaN(e)||!isFinite(e)?B.ZERO:e<=-B.TWO_PWR_63_DBL_?B.MIN_VALUE:e+1>=B.TWO_PWR_63_DBL_?B.MAX_VALUE:e<0?B.fromNumber(-e).negate():new B(e%B.TWO_PWR_32_DBL_|0,e/B.TWO_PWR_32_DBL_|0)};B.fromBits=function(e,t){return new B(e,t)};B.fromString=function(e,t){if(e.length===0)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var n=B.fromNumber(Math.pow(r,8)),i=B.ZERO,s=0;s{"use strict";function SP(e){return e.toString().replace(/function *\(/,"function (")}o(SP,"normalizedFunctionString");function t_(e,t){return new Buffer(e,t)}o(t_,"newBuffer");function wP(){return Buffer.alloc.apply(Buffer,arguments)}o(wP,"allocBuffer");function OP(){return Buffer.from.apply(Buffer,arguments)}o(OP,"toBuffer");r_.exports={normalizedFunctionString:SP,allocBuffer:typeof Buffer.alloc=="function"?wP:t_,toBuffer:typeof Buffer.from=="function"?OP:t_}});var da=w((rre,Ac)=>{var i_="inspect",Cc=Fn(),tp=parseInt(Math.random()*16777215,10),n_=new RegExp("^[0-9a-fA-F]{24}$");try{Buffer&&Buffer.from&&(bc=!0,i_=require("util").inspect.custom||"inspect")}catch{bc=!1}var bc,Ae=o(function e(t){if(t instanceof e)return t;if(!(this instanceof e))return new e(t);if(this._bsontype="ObjectID",t==null||typeof t=="number"){this.id=this.generate(t),e.cacheHexString&&(this.__id=this.toString("hex"));return}var r=e.isValid(t);if(!r&&t!=null)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(r&&typeof t=="string"&&t.length===24&&bc)return new e(Cc.toBuffer(t,"hex"));if(r&&typeof t=="string"&&t.length===24)return e.createFromHexString(t);if(t!=null&&t.length===12)this.id=t;else{if(t!=null&&typeof t.toHexString=="function")return t;throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}e.cacheHexString&&(this.__id=this.toString("hex"))},"ObjectID"),s_=[];for(kt=0;kt<256;kt++)s_[kt]=(kt<=15?"0":"")+kt.toString(16);var kt;Ae.prototype.toHexString=function(){if(Ae.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length)throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]");if(this.id instanceof ha)return e=vP(this.id),Ae.cacheHexString&&(this.__id=e),e;for(var t=0;t"u"||process.pid===1?Math.floor(Math.random()*1e5):process.pid)%65535,r=this.get_inc(),n=Cc.allocBuffer(12);return n[3]=e&255,n[2]=e>>8&255,n[1]=e>>16&255,n[0]=e>>24&255,n[6]=tp&255,n[5]=tp>>8&255,n[4]=tp>>16&255,n[8]=t&255,n[7]=t>>8&255,n[11]=r&255,n[10]=r>>8&255,n[9]=r>>16&255,n};Ae.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString(typeof e=="string"?e:"hex"):this.toHexString()};Ae.prototype[i_]=Ae.prototype.toString;Ae.prototype.toJSON=function(){return this.toHexString()};Ae.prototype.equals=o(function(t){return t instanceof Ae?this.toString()===t.toString():typeof t=="string"&&Ae.isValid(t)&&t.length===12&&this.id instanceof ha?t===this.id.toString("binary"):typeof t=="string"&&Ae.isValid(t)&&t.length===24?t.toLowerCase()===this.toHexString():typeof t=="string"&&Ae.isValid(t)&&t.length===12?t===this.id:t!=null&&(t instanceof Ae||t.toHexString)?t.toHexString()===this.toHexString():!1},"equals");Ae.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(Math.floor(t)*1e3),e};Ae.index=~~(Math.random()*16777215);Ae.createPk=o(function(){return new Ae},"createPk");Ae.createFromTime=o(function(t){var r=Cc.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return r[3]=t&255,r[2]=t>>8&255,r[1]=t>>16&255,r[0]=t>>24&255,new Ae(r)},"createFromTime");var la=[];kt=0;for(;kt<10;)la[48+kt]=kt++;for(;kt<16;)la[65-10+kt]=la[97-10+kt]=kt++;var ha=Buffer,vP=o(function(e){return e.toString("hex")},"convertToHex");Ae.createFromHexString=o(function(t){if(typeof t>"u"||t!=null&&t.length!==24)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(bc)return new Ae(Cc.toBuffer(t,"hex"));for(var r=new ha(12),n=0,i=0;i<24;)r[n++]=la[t.charCodeAt(i++)]<<4|la[t.charCodeAt(i++)];return new Ae(r)},"createFromHexString");Ae.isValid=o(function(t){return t==null?!1:typeof t=="number"?!0:typeof t=="string"?t.length===12||t.length===24&&n_.test(t):t instanceof Ae||t instanceof ha?!0:typeof t.toHexString=="function"&&(t.id instanceof ha||typeof t.id=="string")?t.id.length===12||t.id.length===24&&n_.test(t.id):!1},"isValid");Object.defineProperty(Ae.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=e&255,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}});Ac.exports=Ae;Ac.exports.ObjectID=Ae;Ac.exports.ObjectId=Ae});var pa=w((ire,rp)=>{function Ic(e,t){if(!(this instanceof Ic))return new Ic;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r{var EP=Buffer&&require("util").inspect.custom||"inspect";function $n(e){if(!(this instanceof $n))return new $n(e);this._bsontype="Symbol",this.value=e}o($n,"Symbol");$n.prototype.valueOf=function(){return this.value};$n.prototype.toString=function(){return this.value};$n.prototype[EP]=function(){return this.value};$n.prototype.toJSON=function(){return this.value};np.exports=$n;np.exports.Symbol=$n});var Bc=w((ure,ip)=>{var _s=o(function(e){if(!(this instanceof _s))return new _s(e);this._bsontype="Int32",this.value=e},"Int32");_s.prototype.valueOf=function(){return this.value};_s.prototype.toJSON=function(){return this.value};ip.exports=_s;ip.exports.Int32=_s});var ya=w((fre,op)=>{var sp=o(function e(t,r){if(!(this instanceof e))return new e(t,r);this._bsontype="Code",this.code=t,this.scope=r},"Code");sp.prototype.toJSON=function(){return{scope:this.scope,code:this.code}};op.exports=sp;op.exports.Code=sp});var Sa=w((hre,up)=>{"use strict";var ge=Ai(),_P=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,TP=/^(\+|-)?(Infinity|inf)$/i,NP=/^(\+|-)?NaN$/i,ga=6111,Rc=-6176,ap=6176,bP=34,Mc=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),xc=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),qc=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),CP=/^([-+])?(\d+)?$/,sn=Fn(),o_=o(function(e){return!isNaN(parseInt(e,10))},"isDigit"),AP=o(function(e){var t=ge.fromNumber(1e9),r=ge.fromNumber(0),n=0;if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3])return{quotient:e,rem:r};for(n=0;n<=3;n++)r=r.shiftLeft(32),r=r.add(new ge(e.parts[n],0)),e.parts[n]=r.div(t).low_,r=r.modulo(t);return{quotient:e,rem:r}},"divideu128"),IP=o(function(e,t){if(!e&&!t)return{high:ge.fromNumber(0),low:ge.fromNumber(0)};var r=e.shiftRightUnsigned(32),n=new ge(e.getLowBits(),0),i=t.shiftRightUnsigned(32),s=new ge(t.getLowBits(),0),a=r.multiply(i),u=r.multiply(s),c=n.multiply(i),f=n.multiply(s);return a=a.add(u.shiftRightUnsigned(32)),u=new ge(u.getLowBits(),0).add(c).add(f.shiftRightUnsigned(32)),a=a.add(u.shiftRightUnsigned(32)),f=u.shiftLeft(32).add(new ge(f.getLowBits(),0)),{high:a,low:f}},"multiply64x2"),BP=o(function(e,t){var r=e.high_>>>0,n=t.high_>>>0;if(r>>0,s=t.low_>>>0;if(i=7e3)throw new Error(""+e+" not a valid Decimal128 string");var N=e.match(_P),P=e.match(TP),q=e.match(NP);if(!N&&!P&&!q||e.length===0)throw new Error(""+e+" not a valid Decimal128 string");if(N&&N[4]&&N[2]===void 0)throw new Error(""+e+" not a valid Decimal128 string");if((e[_]==="+"||e[_]==="-")&&(t=e[_++]==="-"),!o_(e[_])&&e[_]!=="."){if(e[_]==="i"||e[_]==="I")return new Yt(sn.toBuffer(t?xc:qc));if(e[_]==="N")return new Yt(sn.toBuffer(Mc))}for(;o_(e[_])||e[_]===".";){if(e[_]==="."){if(r)return new Yt(sn.toBuffer(Mc));r=!0,_=_+1;continue}h<34&&(e[_]!=="0"||n)&&(n||(c=s),n=!0,f[l++]=parseInt(e[_],10),h=h+1),n&&(a=a+1),r&&(u=u+1),s=s+1,_=_+1}if(r&&!s)throw new Error(""+e+" not a valid Decimal128 string");if(e[_]==="e"||e[_]==="E"){var H=e.substr(++_).match(CP);if(!H||!H[2])return new Yt(sn.toBuffer(Mc));S=parseInt(H[0],10),_=_+H[0].length}if(e[_])return new Yt(sn.toBuffer(Mc));if(d=0,!h)d=0,m=0,f[0]=0,a=1,h=1,i=0;else if(m=h-1,i=a,S!==0&&i!==1)for(;e[c+i-1]==="0";)i=i-1;for(S<=u&&u-S>16384?S=Rc:S=S-u;S>ga;){if(m=m+1,m-d>bP){var ue=f.join("");if(ue.match(/^0+$/)){S=ga;break}else return new Yt(sn.toBuffer(t?xc:qc))}S=S-1}for(;S=5&&(K=1,te===5)){for(K=f[m]%2===1,E=c+m+2;E=0&&++f[W]>9;W--)if(f[W]=0,W===0)if(S>8&255,fe[_++]=Y.low.low_>>16&255,fe[_++]=Y.low.low_>>24&255,fe[_++]=Y.low.high_&255,fe[_++]=Y.low.high_>>8&255,fe[_++]=Y.low.high_>>16&255,fe[_++]=Y.low.high_>>24&255,fe[_++]=Y.high.low_&255,fe[_++]=Y.high.low_>>8&255,fe[_++]=Y.high.low_>>16&255,fe[_++]=Y.high.low_>>24&255,fe[_++]=Y.high.high_&255,fe[_++]=Y.high.high_>>8&255,fe[_++]=Y.high.high_>>16&255,fe[_++]=Y.high.high_>>24&255,new Yt(fe)};var RP=31,a_=16383,MP=30,xP=31;ap=6176;Yt.prototype.toString=function(){for(var e,t,r,n,i,s,a=0,u=new Array(36),c=0;c>26&RP,i>>3===3){if(i===MP)return T.join("")+"Infinity";if(i===xP)return"NaN";s=e>>15&a_,m=8+(e>>14&1)}else m=e>>14&7,s=e>>17&a_;if(h=s-ap,S.parts[0]=(e&16383)+((m&15)<<14),S.parts[1]=t,S.parts[2]=r,S.parts[3]=n,S.parts[0]===0&&S.parts[1]===0&&S.parts[2]===0&&S.parts[3]===0)d=!0;else for(O=3;O>=0;O--){var N=0,P=AP(S);if(S=P.quotient,N=P.rem.low_,!!N)for(E=8;E>=0;E--)u[O*9+E]=N%10,N=Math.floor(N/10)}if(d)a=1,u[f]=0;else for(a=36,c=0;!u[f];)c++,a=a-1,f=f+1;if(l=a-1+h,l>=34||l<=-7||h>0){for(T.push(u[f++]),a=a-1,a&&T.push("."),c=0;c0?T.push("+"+l):T.push(l)}else if(h>=0)for(c=0;c0)for(c=0;c{function Dc(){if(!(this instanceof Dc))return new Dc;this._bsontype="MinKey"}o(Dc,"MinKey");cp.exports=Dc;cp.exports.MinKey=Dc});var Oa=w((yre,fp)=>{function Pc(){if(!(this instanceof Pc))return new Pc;this._bsontype="MaxKey"}o(Pc,"MaxKey");fp.exports=Pc;fp.exports.MaxKey=Pc});var Ea=w((Sre,lp)=>{function va(e,t,r){if(!(this instanceof va))return new va(e,t,r);this._bsontype="DBRef",this.namespace=e,this.oid=t,this.db=r}o(va,"DBRef");va.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:this.db==null?"":this.db}};lp.exports=va;lp.exports.DBRef=va});var Ts=w((Ore,hp)=>{typeof global<"u"&&(gt=require("buffer").Buffer);var gt,Lc=Fn();function Ge(e,t){if(!(this instanceof Ge))return new Ge(e,t);if(e!=null&&typeof e!="string"&&!gt.isBuffer(e)&&!(e instanceof Uint8Array)&&!Array.isArray(e))throw new Error("only String, Buffer, Uint8Array or Array accepted");if(this._bsontype="Binary",e instanceof Number?(this.sub_type=e,this.position=0):(this.sub_type=t??qP,this.position=0),e!=null&&!(e instanceof Number)){if(typeof e=="string")if(typeof gt<"u")this.buffer=Lc.toBuffer(e);else if(typeof Uint8Array<"u"||Object.prototype.toString.call(e)==="[object Array]")this.buffer=DP(e);else throw new Error("only String, Buffer, Uint8Array or Array accepted");else this.buffer=e;this.position=e.length}else typeof gt<"u"?this.buffer=Lc.allocBuffer(Ge.BUFFER_SIZE):typeof Uint8Array<"u"?this.buffer=new Uint8Array(new ArrayBuffer(Ge.BUFFER_SIZE)):this.buffer=new Array(Ge.BUFFER_SIZE),this.position=0}o(Ge,"Binary");Ge.prototype.put=o(function(t){if(t.length!=null&&typeof t!="number"&&t.length!==1)throw new Error("only accepts single character String, Uint8Array or Array");if(typeof t!="number"&&t<0||t>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var r=null;if(typeof t=="string"?r=t.charCodeAt(0):t.length!=null?r=t[0]:r=t,this.buffer.length>this.position)this.buffer[this.position++]=r;else if(typeof gt<"u"&>.isBuffer(this.buffer)){var n=Lc.allocBuffer(Ge.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=r}else{n=null,Object.prototype.toString.call(this.buffer)==="[object Uint8Array]"?n=new Uint8Array(new ArrayBuffer(Ge.BUFFER_SIZE+this.buffer.length)):n=new Array(Ge.BUFFER_SIZE+this.buffer.length);for(var i=0;ithis.position?r+t.length:this.position;else if(typeof gt<"u"&&typeof t=="string"&>.isBuffer(this.buffer))this.buffer.write(t,r,"binary"),this.position=r+t.length>this.position?r+t.length:this.position;else if(Object.prototype.toString.call(t)==="[object Uint8Array]"||Object.prototype.toString.call(t)==="[object Array]"&&typeof t!="string"){for(i=0;ithis.position?r:this.position}else if(typeof t=="string"){for(i=0;ithis.position?r:this.position}},"write");Ge.prototype.read=o(function(t,r){if(r=r&&r>0?r:this.position,this.buffer.slice)return this.buffer.slice(t,t+r);for(var n=typeof Uint8Array<"u"?new Uint8Array(new ArrayBuffer(r)):new Array(r),i=0;i{"use strict";var Long=Ai().Long,Double=ca().Double,Timestamp=fa().Timestamp,ObjectID=da().ObjectID,Symbol=ma().Symbol,Code=ya().Code,MinKey=wa().MinKey,MaxKey=Oa().MaxKey,Decimal128=Sa(),Int32=Bc(),DBRef=Ea().DBRef,BSONRegExp=pa().BSONRegExp,Binary=Ts().Binary,utils=Fn(),deserialize=o(function(e,t,r){t=t??{};var n=t&&t.index?t.index:0,i=e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24;if(i<5||e.lengthe.length)throw new Error("corrupt bson message");if(e[n+i-1]!==0)throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,n,t,r)},"deserialize"),deserializeObject=o(function(e,t,r,n){var i=r.evalFunctions==null?!1:r.evalFunctions,s=r.cacheFunctions==null?!1:r.cacheFunctions,a=r.cacheFunctionsCrc32==null?!1:r.cacheFunctionsCrc32;if(!a)var u=null;var c=r.fieldsAsRaw==null?null:r.fieldsAsRaw,f=r.raw==null?!1:r.raw,h=typeof r.bsonRegExp=="boolean"?r.bsonRegExp:!1,l=r.promoteBuffers==null?!1:r.promoteBuffers,d=r.promoteLongs==null?!0:r.promoteLongs,m=r.promoteValues==null?!0:r.promoteValues,S=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var E=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(E<5||E>e.length)throw new Error("corrupt bson message");for(var O=n?[]:{},T=0,R=!1;!R;){var _=e[t++];if(_===0)break;for(var N=t;e[N]!==0&&N=e.length)throw new Error("Bad BSON Document: illegal CString");var P=n?T++:e.toString("utf8",t,N);if(t=N+1,_===BSON.BSON_DATA_STRING){var q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(q<=0||q>e.length-t||e[t+q-1]!==0)throw new Error("bad string length in bson");O[P]=e.toString("utf8",t,t+q-1),t=t+q}else if(_===BSON.BSON_DATA_OID){var H=utils.allocBuffer(12);e.copy(H,0,t,t+12),O[P]=new ObjectID(H),t=t+12}else if(_===BSON.BSON_DATA_INT&&m===!1)O[P]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(_===BSON.BSON_DATA_INT)O[P]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(_===BSON.BSON_DATA_NUMBER&&m===!1)O[P]=new Double(e.readDoubleLE(t)),t=t+8;else if(_===BSON.BSON_DATA_NUMBER)O[P]=e.readDoubleLE(t),t=t+8;else if(_===BSON.BSON_DATA_DATE){var ue=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,j=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;O[P]=new Date(new Long(ue,j).toNumber())}else if(_===BSON.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new Error("illegal boolean type value");O[P]=e[t++]===1}else if(_===BSON.BSON_DATA_OBJECT){var te=t,K=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(K<=0||K>e.length-t)throw new Error("bad embedded document length in bson");f?O[P]=e.slice(t,t+K):O[P]=deserializeObject(e,te,r,!1),t=t+K}else if(_===BSON.BSON_DATA_ARRAY){te=t,K=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var W=r,z=t+K;if(c&&c[P]){W={};for(var Y in r)W[Y]=r[Y];W.raw=!0}if(O[P]=deserializeObject(e,te,W,!0),t=t+K,e[t-1]!==0)throw new Error("invalid array terminator byte");if(t!==z)throw new Error("corrupted array bson")}else if(_===BSON.BSON_DATA_UNDEFINED)O[P]=void 0;else if(_===BSON.BSON_DATA_NULL)O[P]=null;else if(_===BSON.BSON_DATA_LONG){ue=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,j=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var fe=new Long(ue,j);d&&m===!0?O[P]=fe.lessThanOrEqual(JS_INT_MAX_LONG)&&fe.greaterThanOrEqual(JS_INT_MIN_LONG)?fe.toNumber():fe:O[P]=fe}else if(_===BSON.BSON_DATA_DECIMAL128){var ee=utils.allocBuffer(16);e.copy(ee,0,t,t+16),t=t+16;var Q=new Decimal128(ee);O[P]=Q.toObject?Q.toObject():Q}else if(_===BSON.BSON_DATA_BINARY){var Ne=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,he=Ne,de=e[t++];if(Ne<0)throw new Error("Negative binary type element size found");if(Ne>e.length)throw new Error("Binary type size larger than document size");if(e.slice!=null){if(de===Binary.SUBTYPE_BYTE_ARRAY){if(Ne=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,Ne<0)throw new Error("Negative binary type element size found for subtype 0x02");if(Ne>he-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(Nehe-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(Ne=e.length)throw new Error("Bad BSON Document: illegal CString");var ft=e.toString("utf8",t,N);for(t=N+1,N=t;e[N]!==0&&N=e.length)throw new Error("Bad BSON Document: illegal CString");var Ir=e.toString("utf8",t,N);t=N+1;var tr=new Array(Ir.length);for(N=0;N=e.length)throw new Error("Bad BSON Document: illegal CString");for(ft=e.toString("utf8",t,N),t=N+1,N=t;e[N]!==0&&N=e.length)throw new Error("Bad BSON Document: illegal CString");Ir=e.toString("utf8",t,N),t=N+1,O[P]=new BSONRegExp(ft,Ir)}else if(_===BSON.BSON_DATA_SYMBOL){if(q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,q<=0||q>e.length-t||e[t+q-1]!==0)throw new Error("bad string length in bson");O[P]=new Symbol(e.toString("utf8",t,t+q-1)),t=t+q}else if(_===BSON.BSON_DATA_TIMESTAMP)ue=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,j=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,O[P]=new Timestamp(ue,j);else if(_===BSON.BSON_DATA_MIN_KEY)O[P]=new MinKey;else if(_===BSON.BSON_DATA_MAX_KEY)O[P]=new MaxKey;else if(_===BSON.BSON_DATA_CODE){if(q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,q<=0||q>e.length-t||e[t+q-1]!==0)throw new Error("bad string length in bson");var Ye=e.toString("utf8",t,t+q-1);if(i)if(s){var jn=a?u(Ye):Ye;O[P]=isolateEvalWithHash(functionCache,jn,Ye,O)}else O[P]=isolateEval(Ye);else O[P]=new Code(Ye);t=t+q}else if(_===BSON.BSON_DATA_CODE_W_SCOPE){var rr=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(rr<4+4+4+1)throw new Error("code_w_scope total size shorter minimum expected length");if(q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,q<=0||q>e.length-t||e[t+q-1]!==0)throw new Error("bad string length in bson");Ye=e.toString("utf8",t,t+q-1),t=t+q,te=t,K=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var Un=deserializeObject(e,te,r,!1);if(t=t+K,rr<4+4+K+q)throw new Error("code_w_scope total size is to short, truncating scope");if(rr>4+4+K+q)throw new Error("code_w_scope total size is to long, clips outer document");i?(s?(jn=a?u(Ye):Ye,O[P]=isolateEvalWithHash(functionCache,jn,Ye,O)):O[P]=isolateEval(Ye),O[P].scope=Un):O[P]=new Code(Ye,Un)}else if(_===BSON.BSON_DATA_DBPOINTER){if(q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,q<=0||q>e.length-t||e[t+q-1]!==0)throw new Error("bad string length in bson");var nr=e.toString("utf8",t,t+q-1);t=t+q;var Ue=utils.allocBuffer(12);e.copy(Ue,0,t,t+12),H=new ObjectID(Ue),t=t+12;var Br=nr.split("."),Rr=Br.shift(),gs=Br.join(".");O[P]=new DBRef(gs,H,Rr)}else throw new Error("Detected unknown BSON type "+_.toString(16)+' for fieldname "'+P+'", are you using the latest BSON parser')}if(E!==t-S)throw n?new Error("corrupt array bson"):new Error("corrupt object bson");return O.$id!=null&&(O=new DBRef(O.$ref,O.$id,O.$db)),O},"deserializeObject"),isolateEvalWithHash=o(function(functionCache,hash,functionString,object){var value=null;return functionCache[hash]==null&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},"isolateEvalWithHash"),isolateEval=o(function(functionString){var value=null;return eval("value = "+functionString),value},"isolateEval"),BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1;BSON.BSON_DATA_STRING=2;BSON.BSON_DATA_OBJECT=3;BSON.BSON_DATA_ARRAY=4;BSON.BSON_DATA_BINARY=5;BSON.BSON_DATA_UNDEFINED=6;BSON.BSON_DATA_OID=7;BSON.BSON_DATA_BOOLEAN=8;BSON.BSON_DATA_DATE=9;BSON.BSON_DATA_NULL=10;BSON.BSON_DATA_REGEXP=11;BSON.BSON_DATA_DBPOINTER=12;BSON.BSON_DATA_CODE=13;BSON.BSON_DATA_SYMBOL=14;BSON.BSON_DATA_CODE_W_SCOPE=15;BSON.BSON_DATA_INT=16;BSON.BSON_DATA_TIMESTAMP=17;BSON.BSON_DATA_LONG=18;BSON.BSON_DATA_DECIMAL128=19;BSON.BSON_DATA_MIN_KEY=255;BSON.BSON_DATA_MAX_KEY=127;BSON.BSON_BINARY_SUBTYPE_DEFAULT=0;BSON.BSON_BINARY_SUBTYPE_FUNCTION=1;BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;BSON.BSON_BINARY_SUBTYPE_UUID=3;BSON.BSON_BINARY_SUBTYPE_MD5=4;BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128;BSON.BSON_INT32_MAX=2147483647;BSON.BSON_INT32_MIN=-2147483648;BSON.BSON_INT64_MAX=Math.pow(2,63)-1;BSON.BSON_INT64_MIN=-Math.pow(2,63);BSON.JS_INT_MAX=9007199254740992;BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize});var c_=w(dp=>{var LP=o(function(e,t,r,n,i){var s,a,u=r==="big",c=i*8-n-1,f=(1<>1,l=-7,d=u?0:i-1,m=u?1:-1,S=e[t+d];for(d+=m,s=S&(1<<-l)-1,S>>=-l,l+=c;l>0;s=s*256+e[t+d],d+=m,l-=8);for(a=s&(1<<-l)-1,s>>=-l,l+=n;l>0;a=a*256+e[t+d],d+=m,l-=8);if(s===0)s=1-h;else{if(s===f)return a?NaN:(S?-1:1)*(1/0);a=a+Math.pow(2,n),s=s-h}return(S?-1:1)*a*Math.pow(2,s-n)},"readIEEE754"),jP=o(function(e,t,r,n,i,s){var a,u,c,f=n==="big",h=s*8-i-1,l=(1<>1,m=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,S=f?s-1:0,E=f?-1:1,O=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(u=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+d>=1?t+=m/c:t+=m*Math.pow(2,1-d),t*c>=2&&(a++,c/=2),a+d>=l?(u=0,a=l):a+d>=1?(u=(t*c-1)*Math.pow(2,i),a=a+d):(u=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+S]=u&255,S+=E,u/=256,i-=8);for(a=a<0;e[r+S]=a&255,S+=E,a/=256,h-=8);e[r+S-E]|=O*128},"writeIEEE754");dp.readIEEE754=LP;dp.writeIEEE754=jP});var p_=w((Nre,d_)=>{"use strict";var Dp=c_().writeIEEE754,h_=Ai().Long,UP=Nc(),f_=Ts().Binary,WP=Fn().normalizedFunctionString,jc=/\x00/,l_=["$db","$ref","$id","$clusterTime"],pp=o(function(t){return typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"},"isDate"),mp=o(function(t){return Object.prototype.toString.call(t)==="[object RegExp]"},"isRegExp"),yp=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_STRING;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+s+1,e[n-1]=0;var a=e.write(r,n+4,"utf8");return e[n+3]=a+1>>24&255,e[n+2]=a+1>>16&255,e[n+1]=a+1>>8&255,e[n]=a+1&255,n=n+4+a,e[n++]=0,n},"serializeString"),gp=o(function(e,t,r,n,i){if(Math.floor(r)===r&&r>=G.JS_INT_MIN&&r<=G.JS_INT_MAX)if(r>=G.BSON_INT32_MIN&&r<=G.BSON_INT32_MAX){e[n++]=G.BSON_DATA_INT;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+s,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255}else if(r>=G.JS_INT_MIN&&r<=G.JS_INT_MAX)e[n++]=G.BSON_DATA_NUMBER,s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+s,e[n++]=0,Dp(e,r,n,"little",52,8),n=n+8;else{e[n++]=G.BSON_DATA_LONG,s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+s,e[n++]=0;var a=h_.fromNumber(r),u=a.getLowBits(),c=a.getHighBits();e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=c&255,e[n++]=c>>8&255,e[n++]=c>>16&255,e[n++]=c>>24&255}else e[n++]=G.BSON_DATA_NUMBER,s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+s,e[n++]=0,Dp(e,r,n,"little",52,8),n=n+8;return n},"serializeNumber"),_a=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_NULL;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+s,e[n++]=0,n},"serializeNull"),Sp=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_BOOLEAN;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+s,e[n++]=0,e[n++]=r?1:0,n},"serializeBoolean"),wp=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_DATE;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+s,e[n++]=0;var a=h_.fromNumber(r.getTime()),u=a.getLowBits(),c=a.getHighBits();return e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=c&255,e[n++]=c>>8&255,e[n++]=c>>16&255,e[n++]=c>>24&255,n},"serializeDate"),Op=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_REGEXP;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");if(n=n+s,e[n++]=0,r.source&&r.source.match(jc)!=null)throw Error("value "+r.source+" must not contain null bytes");return n=n+e.write(r.source,n,"utf8"),e[n++]=0,r.global&&(e[n++]=115),r.ignoreCase&&(e[n++]=105),r.multiline&&(e[n++]=109),e[n++]=0,n},"serializeRegExp"),vp=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_REGEXP;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");if(n=n+s,e[n++]=0,r.pattern.match(jc)!=null)throw Error("pattern "+r.pattern+" must not contain null bytes");return n=n+e.write(r.pattern,n,"utf8"),e[n++]=0,n=n+e.write(r.options.split("").sort().join(""),n,"utf8"),e[n++]=0,n},"serializeBSONRegExp"),Ep=o(function(e,t,r,n,i){r===null?e[n++]=G.BSON_DATA_NULL:r._bsontype==="MinKey"?e[n++]=G.BSON_DATA_MIN_KEY:e[n++]=G.BSON_DATA_MAX_KEY;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+s,e[n++]=0,n},"serializeMinMax"),_p=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_OID;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");if(n=n+s,e[n++]=0,typeof r.id=="string")e.write(r.id,n,"binary");else if(r.id&&r.id.copy)r.id.copy(e,n,0,12);else throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId");return n+12},"serializeObjectId"),Tp=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_BINARY;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+s,e[n++]=0;var a=r.length;return e[n++]=a&255,e[n++]=a>>8&255,e[n++]=a>>16&255,e[n++]=a>>24&255,e[n++]=G.BSON_BINARY_SUBTYPE_DEFAULT,r.copy(e,n,0,a),n=n+a,n},"serializeBuffer"),Np=o(function(e,t,r,n,i,s,a,u,c,f){for(var h=0;h>8&255,e[n++]=a>>16&255,e[n++]=a>>24&255,e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,n},"serializeLong"),Ap=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_INT;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+s,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255,n},"serializeInt32"),Ip=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_NUMBER;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");return n=n+s,e[n++]=0,Dp(e,r,n,"little",52,8),n=n+8,n},"serializeDouble"),Bp=o(function(e,t,r,n,i,s,a){e[n++]=G.BSON_DATA_CODE;var u=a?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+u,e[n++]=0;var c=WP(r),f=e.write(c,n+4,"utf8")+1;return e[n]=f&255,e[n+1]=f>>8&255,e[n+2]=f>>16&255,e[n+3]=f>>24&255,n=n+4+f-1,e[n++]=0,n},"serializeFunction"),Rp=o(function(e,t,r,n,i,s,a,u,c){if(r.scope&&typeof r.scope=="object"){e[n++]=G.BSON_DATA_CODE_W_SCOPE;var f=c?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+f,e[n++]=0;var h=n,l=typeof r.code=="string"?r.code:r.code.toString();n=n+4;var d=e.write(l,n+4,"utf8")+1;e[n]=d&255,e[n+1]=d>>8&255,e[n+2]=d>>16&255,e[n+3]=d>>24&255,e[n+4+d-1]=0,n=n+d+4;var m=Ta(e,r.scope,i,n,s+1,a,u);n=m-1;var S=m-h;e[h++]=S&255,e[h++]=S>>8&255,e[h++]=S>>16&255,e[h++]=S>>24&255,e[n++]=0}else{e[n++]=G.BSON_DATA_CODE,f=c?e.write(t,n,"ascii"):e.write(t,n,"utf8"),n=n+f,e[n++]=0,l=r.code.toString();var E=e.write(l,n+4,"utf8")+1;e[n]=E&255,e[n+1]=E>>8&255,e[n+2]=E>>16&255,e[n+3]=E>>24&255,n=n+4+E-1,e[n++]=0}return n},"serializeCode"),Mp=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_BINARY;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+s,e[n++]=0;var a=r.value(!0),u=r.position;return r.sub_type===f_.SUBTYPE_BYTE_ARRAY&&(u=u+4),e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=r.sub_type,r.sub_type===f_.SUBTYPE_BYTE_ARRAY&&(u=u-4,e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255),a.copy(e,n,0,r.position),n=n+r.position,n},"serializeBinary"),xp=o(function(e,t,r,n,i){e[n++]=G.BSON_DATA_SYMBOL;var s=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+s,e[n++]=0;var a=e.write(r.value,n+4,"utf8")+1;return e[n]=a&255,e[n+1]=a>>8&255,e[n+2]=a>>16&255,e[n+3]=a>>24&255,n=n+4+a-1,e[n++]=0,n},"serializeSymbol"),qp=o(function(e,t,r,n,i,s,a){e[n++]=G.BSON_DATA_OBJECT;var u=a?e.write(t,n,"ascii"):e.write(t,n,"utf8");n=n+u,e[n++]=0;var c=n,f;r.db!=null?f=Ta(e,{$ref:r.namespace,$id:r.oid,$db:r.db},!1,n,i+1,s):f=Ta(e,{$ref:r.namespace,$id:r.oid},!1,n,i+1,s);var h=f-c;return e[c++]=h&255,e[c++]=h>>8&255,e[c++]=h>>16&255,e[c++]=h>>24&255,f},"serializeDBRef"),Ta=o(function(t,r,n,i,s,a,u,c){i=i||0,c=c||[],c.push(r);var f=i+4;if(Array.isArray(r))for(var h=0;h>8&255,t[i++]=T>>16&255,t[i++]=T>>24&255,f},"serializeInto"),G={};G.BSON_DATA_NUMBER=1;G.BSON_DATA_STRING=2;G.BSON_DATA_OBJECT=3;G.BSON_DATA_ARRAY=4;G.BSON_DATA_BINARY=5;G.BSON_DATA_UNDEFINED=6;G.BSON_DATA_OID=7;G.BSON_DATA_BOOLEAN=8;G.BSON_DATA_DATE=9;G.BSON_DATA_NULL=10;G.BSON_DATA_REGEXP=11;G.BSON_DATA_CODE=13;G.BSON_DATA_SYMBOL=14;G.BSON_DATA_CODE_W_SCOPE=15;G.BSON_DATA_INT=16;G.BSON_DATA_TIMESTAMP=17;G.BSON_DATA_LONG=18;G.BSON_DATA_DECIMAL128=19;G.BSON_DATA_MIN_KEY=255;G.BSON_DATA_MAX_KEY=127;G.BSON_BINARY_SUBTYPE_DEFAULT=0;G.BSON_BINARY_SUBTYPE_FUNCTION=1;G.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;G.BSON_BINARY_SUBTYPE_UUID=3;G.BSON_BINARY_SUBTYPE_MD5=4;G.BSON_BINARY_SUBTYPE_USER_DEFINED=128;G.BSON_INT32_MAX=2147483647;G.BSON_INT32_MIN=-2147483648;G.BSON_INT64_MAX=Math.pow(2,63)-1;G.BSON_INT64_MIN=-Math.pow(2,63);G.JS_INT_MAX=9007199254740992;G.JS_INT_MIN=-9007199254740992;d_.exports=Ta});var w_=w((Cre,S_)=>{"use strict";var FP=Ai().Long,$P=ca().Double,zP=fa().Timestamp,VP=da().ObjectID,HP=ma().Symbol,kP=pa().BSONRegExp,YP=ya().Code,GP=Sa(),KP=wa().MinKey,XP=Oa().MaxKey,JP=Ea().DBRef,m_=Ts().Binary,y_=Fn().normalizedFunctionString,ZP=o(function(t){return typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"},"isDate"),Na=o(function(t,r,n){var i=5;if(Array.isArray(t))for(var s=0;s=zn.JS_INT_MIN&&t<=zn.JS_INT_MAX&&t>=zn.BSON_INT32_MIN&&t<=zn.BSON_INT32_MAX?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(4+1):(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1);case"undefined":return n||!i?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t instanceof KP||t instanceof XP||t._bsontype==="MinKey"||t._bsontype==="MaxKey")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof VP||t._bsontype==="ObjectID"||t._bsontype==="ObjectId")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(12+1);if(t instanceof Date||ZP(t))return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(typeof Buffer<"u"&&Buffer.isBuffer(t))return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.length;if(t instanceof FP||t instanceof $P||t instanceof zP||t._bsontype==="Long"||t._bsontype==="Double"||t._bsontype==="Timestamp")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(t instanceof GP||t._bsontype==="Decimal128")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(16+1);if(t instanceof YP||t._bsontype==="Code")return t.scope!=null&&Object.keys(t.scope).length>0?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+Na(t.scope,r,i):(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof m_||t._bsontype==="Binary")return t.sub_type===m_.SUBTYPE_BYTE_ARRAY?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof HP||t._bsontype==="Symbol")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof JP||t._bsontype==="DBRef"){var s={$ref:t.namespace,$id:t.oid};return t.db!=null&&(s.$db=t.db),(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Na(s,r,i)}else return t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof kP||t._bsontype==="BSONRegExp"?(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Na(t,r,i)+1;case"function":if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"||String.call(t)==="[object RegExp]")return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(r&&t.scope!=null&&Object.keys(t.scope).length>0)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(y_(t),"utf8")+1+Na(t.scope,r,i);if(r)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(y_(t),"utf8")+1}return 0}o(g_,"calculateElement");var zn={};zn.BSON_INT32_MAX=2147483647;zn.BSON_INT32_MIN=-2147483648;zn.JS_INT_MAX=9007199254740992;zn.JS_INT_MIN=-9007199254740992;S_.exports=Na});var E_=w((Ire,St)=>{"use strict";var QP=Nc(),eL=Ai(),tL=ca(),rL=fa(),nL=da(),iL=pa(),sL=ma(),oL=Bc(),aL=ya(),uL=Sa(),cL=wa(),fL=Oa(),lL=Ea(),hL=Ts(),dL=u_(),O_=p_(),pL=w_(),Pp=Fn(),v_=1024*1024*17,Uc=Pp.allocBuffer(v_),ve=o(function(){},"BSON");ve.prototype.serialize=o(function(t,r){r=r||{};var n=typeof r.checkKeys=="boolean"?r.checkKeys:!1,i=typeof r.serializeFunctions=="boolean"?r.serializeFunctions:!1,s=typeof r.ignoreUndefined=="boolean"?r.ignoreUndefined:!0,a=typeof r.minInternalBufferSize=="number"?r.minInternalBufferSize:v_;Uc.length{var tt=E_(),mL=Ts(),yL=ya(),gL=Ea(),SL=Sa(),wL=ca(),OL=Bc(),vL=Ai(),EL=Nc(),_L=Oa(),TL=wa(),__=da(),NL=pa(),bL=ma(),CL=fa();tt.BSON_INT32_MAX=2147483647;tt.BSON_INT32_MIN=-2147483648;tt.BSON_INT64_MAX=Math.pow(2,63)-1;tt.BSON_INT64_MIN=-Math.pow(2,63);tt.JS_INT_MAX=9007199254740992;tt.JS_INT_MIN=-9007199254740992;tt.Binary=mL;tt.Code=yL;tt.DBRef=gL;tt.Decimal128=SL;tt.Double=wL;tt.Int32=OL;tt.Long=vL;tt.Map=EL;tt.MaxKey=_L;tt.MinKey=TL;tt.ObjectId=__;tt.ObjectID=__;tt.BSONRegExp=NL;tt.Symbol=bL;tt.Timestamp=CL;T_.exports=tt});var N_=w((exports,module)=>{"use strict";var Module=require("module"),xrequire=eval("require"),createRequireFromPath=Module.createRequire||Module.createRequireFromPath||((e,t)=>{let r=new Module(e);r.filename=e,r.paths=Module._nodeModulePaths(t);function n(a){return xrequire(i(a))}o(n,"_require");function i(a,u){return Module._resolveFilename(a,r,!1,u)}o(i,"resolve"),n.resolve=i;function s(a){return Module._resolveLookupPaths(a,r,!0)}return o(s,"paths"),i.paths=s,n.main=process.mainModule,n.extensions=Module._extensions,n.cache=Module._cache,n});module.exports=createRequireFromPath});var C_=w((xre,b_)=>{"use strict";var Lp=require("path"),AL=require("fs"),IL=N_(),BL=new Map;function Ns(e,t){let r=o((n,i)=>{let s=Ns.cache&&Ns.cache.get(n);if(!s){let a;try{a=AL.statSync(n)}catch(u){throw new Error(`require-at: stat '${n}' failed: ${u.message}`)}if(!a||!a.isDirectory()){if(i)throw new Error(`require-at: not a directory: '${e}'`);return r(Lp.dirname(n),!0)}s=IL(Lp.join(n,"._require-at_"),n),Ns.cache&&Ns.cache.set(n,s)}return t?s(t):s},"makeIt");return r(Lp.resolve(e),!1)}o(Ns,"requireAt");Ns.cache=BL;b_.exports=Ns});var A_=w((exports,module)=>{"use strict";var __assign=exports&&exports.__assign||function(){return __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{"use strict";var Mr=A_();xr.exports=function(){return Mr.makeOptionalRequire.apply(Mr,arguments)};xr.exports.tryRequire=Mr.tryRequire;xr.exports.tryResolve=Mr.tryResolve;xr.exports.try=Mr.tryRequire;xr.exports.resolve=Mr.tryResolve;xr.exports.makeOptionalRequire=Mr.makeOptionalRequire;xr.exports.optionalRequire=Mr.optionalRequire;xr.exports.optionalRequireCwd=Mr.optionalRequireCwd;xr.exports.optionalRequireTop=Mr.optionalRequireTop;var I_;Object.defineProperty(xr.exports,"log",{set(e){I_=e,Mr.setDefaultLog(e)},get(){return I_}})});var B_=w((Lre,RL)=>{RL.exports={name:"mongodb",version:"3.7.4",description:"The official MongoDB driver for Node.js",main:"index.js",files:["index.js","lib"],repository:{type:"git",url:"git@github.com:mongodb/node-mongodb-native.git"},keywords:["mongodb","driver","official"],author:{name:"The MongoDB NodeJS Team",email:"dbx-node@mongodb.com"},peerDependenciesMeta:{kerberos:{optional:!0},"mongodb-client-encryption":{optional:!0},"mongodb-extjson":{optional:!0},snappy:{optional:!0},"bson-ext":{optional:!0},aws4:{optional:!0}},dependencies:{bl:"^2.2.1",bson:"^1.1.4",denque:"^1.4.1","optional-require":"^1.1.8","safe-buffer":"^5.1.2"},devDependencies:{"@types/chai":"^4.2.16","@types/mocha":"^8.2.2","@types/node":"^14.14.37","array-includes":"^3.1.3",chai:"^4.1.1","chai-subset":"^1.6.0",chalk:"^2.4.2",co:"4.6.0",eslint:"^7.10.0","eslint-config-prettier":"^6.11.0","eslint-plugin-es":"^3.0.1","eslint-plugin-prettier":"^3.1.3",jsdoc:"^3.5.5","lodash.camelcase":"^4.3.0",mocha:"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1",nyc:"^15.1.0","object.entries":"^1.1.3",prettier:"^1.19.1",semver:"^5.5.0",sinon:"^4.3.0","sinon-chai":"^3.2.0",snappy:"^6.3.4","spec-xunit-file":"0.0.1-3","standard-version":"^9.2.0",tslib:"^2.2.0",typescript:"^4.2.4","util.promisify":"^1.0.1","worker-farm":"^1.5.0",wtfnode:"^0.8.0",yargs:"^14.2.0"},license:"Apache-2.0",engines:{node:">=4"},bugs:{url:"https://jira.mongodb.org/projects/NODE/issues/"},scripts:{"build:evergreen":"node .evergreen/generate_evergreen_tasks.js","build:unified":"tsc -p test/functional/unified-spec-runner/tsconfig.unified.json","check:atlas":"mocha --opts '{}' ./test/manual/atlas_connectivity.test.js","check:bench":"node test/benchmarks/driverBench/","check:coverage":"nyc npm run check:test","check:kerberos":"mocha --opts '{}' -t 60000 test/manual/kerberos.test.js","check:ldap":"mocha --opts '{}' test/manual/ldap.test.js","check:lint":"eslint -v && eslint lib test","check:test":"mocha --recursive test/functional test/unit","check:tls":"mocha --opts '{}' test/manual/tls_support.test.js",format:"npm run check:lint -- --fix",release:"standard-version -i HISTORY.md",test:"npm run check:lint && mocha --recursive test/functional test/unit"},homepage:"https://github.com/mongodb/node-mongodb-native",optionalDependencies:{saslprep:"^1.0.0"}}});var re=w((jre,x_)=>{"use strict";var jp=require("os"),ML=require("crypto"),R_=Fc()(require),xL=o(()=>{let e=ML.randomBytes(16);return e[6]=e[6]&15|64,e[8]=e[8]&63|128,e},"uuidV4");function qL(e,t,r){r.forEach(n=>e.on(n,i=>t.emit(n,i)))}o(qL,"relayEvents");function DL(){let e;try{e=R_("kerberos")}catch(t){throw t.code==="MODULE_NOT_FOUND"?new Error("The `kerberos` module was not found. Please install it and try again."):t}return e}o(DL,"retrieveKerberos");var bs=o(function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")},"noEJSONError");function PL(){let e=R_("mongodb-extjson");return e||(e={parse:bs,deserialize:bs,serialize:bs,stringify:bs,setBSONModule:bs,BSON:bs}),e}o(PL,"retrieveEJSON");function M_(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if(typeof e.lastIsMaster=="function"){let t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}o(M_,"maxWireVersion");function LL(e,t){return t&&t.collation&&M_(e)<5}o(LL,"collationNotSupported");function jL(e){return e&&typeof e.then=="function"}o(jL,"isPromiseLike");function UL(e,t,r){e=e||[];let n=0,i=0;for(n=0;nr===t[n])}o($L,"arrayStrictEqual");function zL(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>t[i]===e[i])}o(zL,"tagsStrictEqual");function VL(e,t){return e===t?!0:!(e==null&&t!=null||e!=null&&t==null||e.constructor.name!==t.constructor.name||e.message!==t.message)}o(VL,"errorStrictEqual");function HL(e){return o(function(r,n){let i=e[r.s.state];if(i&&i.indexOf(n)<0)throw new TypeError(`illegal state transition from [${r.s.state}] => [${n}], allowed: [${i}]`);r.emit("stateChanged",r.s.state,n),r.s.state=n},"stateTransition")}o(HL,"makeStateMachine");function kL(e){e=e||{};let t={driver:{name:"nodejs",version:B_().version},os:{type:jp.type(),name:process.platform,architecture:process.arch,version:jp.release()},platform:`'Node.js ${process.version}, ${jp.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){let r=Buffer.from(e.appname);t.application={name:r.length>128?r.slice(0,128).toString("utf8"):e.appname}}return t}o(kL,"makeClientMetadata");var YL=o(()=>{},"noop");x_.exports={uuidV4:xL,relayEvents:qL,collationNotSupported:LL,retrieveEJSON:PL,retrieveKerberos:DL,maxWireVersion:M_,isPromiseLike:jL,eachAsync:UL,eachAsyncSeries:WL,isUnifiedTopology:FL,arrayStrictEqual:$L,tagsStrictEqual:zL,errorStrictEqual:VL,makeStateMachine:HL,makeClientMetadata:kL,noop:YL}});var Ii=w((Wre,q_)=>{"use strict";var GL=Object.freeze({HostUnreachable:6,HostNotFound:7,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotMaster:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotMasterNoSlaveOk:13435,NotMasterOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernFailed:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,DuplicateKey:11e3,CannotCreateIndex:67,IndexOptionsConflict:85,IndexKeySpecsConflict:86,InvalidIndexSpecificationOption:197});q_.exports=Object.freeze({MONGODB_ERROR_CODES:GL})});var V=w((Fre,L_)=>{"use strict";var Re=Ii().MONGODB_ERROR_CODES,on=Symbol("errorLabels"),Hc=class Hc extends Error{constructor(t){if(t instanceof Error)super(t.message),this.stack=t.stack;else{if(typeof t=="string")super(t);else{super(t.message||t.errmsg||t.$err||"n/a"),t.errorLabels&&(this[on]=new Set(t.errorLabels));for(var r in t)r==="errorLabels"||r==="errmsg"||(this[r]=t[r])}Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(t){return new Hc(t)}hasErrorLabel(t){return this[on]==null?!1:this[on].has(t)}addErrorLabel(t){this[on]==null&&(this[on]=new Set),this[on].add(t)}get errorLabels(){return this[on]?Array.from(this[on]):[]}};o(Hc,"MongoError");var Bi=Hc,D_=Symbol("beforeHandshake");function KL(e){return e[D_]===!0}o(KL,"isNetworkErrorBeforeHandshake");var $p=class $p extends Bi{constructor(t,r){super(t),this.name="MongoNetworkError",r&&typeof r.beforeHandshake=="boolean"&&(this[D_]=r.beforeHandshake)}};o($p,"MongoNetworkError");var ba=$p,zp=class zp extends ba{constructor(t,r){super(t,r),this.name="MongoNetworkTimeoutError"}};o(zp,"MongoNetworkTimeoutError");var Wp=zp,Vp=class Vp extends Bi{constructor(t){super(t),this.name="MongoParseError"}};o(Vp,"MongoParseError");var $c=Vp,Hp=class Hp extends Bi{constructor(t,r){r&&r.error?super(r.error.message||r.error):super(t),this.name="MongoTimeoutError",r&&(this.reason=r)}};o(Hp,"MongoTimeoutError");var zc=Hp,kp=class kp extends zc{constructor(t,r){super(t,r),this.name="MongoServerSelectionError"}};o(kp,"MongoServerSelectionError");var Fp=kp;function XL(e){let t=Object.assign({},e);return t.ok===0&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}o(XL,"makeWriteConcernResultObject");var Yp=class Yp extends Bi{constructor(t,r){super(t),this.name="MongoWriteConcernError",r&&Array.isArray(r.errorLabels)&&(this[on]=new Set(r.errorLabels)),r!=null&&(this.result=XL(r))}};o(Yp,"MongoWriteConcernError");var Vc=Yp,JL=new Set([Re.HostUnreachable,Re.HostNotFound,Re.NetworkTimeout,Re.ShutdownInProgress,Re.PrimarySteppedDown,Re.SocketException,Re.NotMaster,Re.InterruptedAtShutdown,Re.InterruptedDueToReplStateChange,Re.NotMasterNoSlaveOk,Re.NotMasterOrSecondary]),Up=new Set([Re.InterruptedAtShutdown,Re.InterruptedDueToReplStateChange,Re.NotMaster,Re.NotMasterNoSlaveOk,Re.NotMasterOrSecondary,Re.PrimarySteppedDown,Re.ShutdownInProgress,Re.HostNotFound,Re.HostUnreachable,Re.NetworkTimeout,Re.SocketException,Re.ExceededTimeLimit]);function ZL(e){return e.hasErrorLabel("RetryableWriteError")}o(ZL,"isRetryableEndTransactionError");function QL(e){return e instanceof Vc?Up.has(e.code)||Up.has(e.result.code):Up.has(e.code)}o(QL,"isRetryableWriteError");function e2(e){return JL.has(e.code)||e instanceof ba||e.message.match(/not master/)||e.message.match(/node is recovering/)}o(e2,"isRetryableError");var t2=new Set([Re.ShutdownInProgress,Re.PrimarySteppedDown,Re.InterruptedAtShutdown,Re.InterruptedDueToReplStateChange,Re.NotMasterOrSecondary]),r2=new Set([Re.NotMaster,Re.NotMasterNoSlaveOk,Re.LegacyNotPrimary]),n2=new Set([Re.InterruptedAtShutdown,Re.ShutdownInProgress]);function P_(e){return typeof e.code=="number"?t2.has(e.code):/not master or secondary/.test(e.message)||/node is recovering/.test(e.message)}o(P_,"isRecoveringError");function i2(e){return typeof e.code=="number"?r2.has(e.code):P_(e)?!1:/not master/.test(e.message)}o(i2,"isNotMasterError");function s2(e){return e.code&&n2.has(e.code)}o(s2,"isNodeShuttingDownError");function o2(e){return e instanceof $c||e==null?!0:P_(e)||i2(e)}o(o2,"isSDAMUnrecoverableError");L_.exports={MongoError:Bi,MongoNetworkError:ba,MongoNetworkTimeoutError:Wp,MongoParseError:$c,MongoTimeoutError:zc,MongoServerSelectionError:Fp,MongoWriteConcernError:Vc,isRetryableError:e2,isSDAMUnrecoverableError:o2,isNodeShuttingDownError:s2,isRetryableWriteError:QL,isNetworkErrorBeforeHandshake:KL,isRetryableEndTransactionError:ZL}});var an=w((zre,j_)=>{"use strict";var a2=new Set(["w","wtimeout","j","journal","fsync"]),Gp,Cs=class Cs{constructor(t,r,n,i){t!=null&&(this.w=t),r!=null&&(this.wtimeout=r),n!=null&&(this.j=n),i!=null&&(this.fsync=i)}static fromOptions(t){if(!(t==null||t.writeConcern==null&&t.w==null&&t.wtimeout==null&&t.j==null&&t.journal==null&&t.fsync==null))return t.writeConcern?typeof t.writeConcern=="string"?new Cs(t.writeConcern):Object.keys(t.writeConcern).some(r=>a2.has(r))?new Cs(t.writeConcern.w,t.writeConcern.wtimeout,t.writeConcern.j||t.writeConcern.journal,t.writeConcern.fsync):void 0:(Gp||(Gp=b()),Gp.emitWarningOnce("Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead."),new Cs(t.w,t.wtimeout,t.j||t.journal,t.fsync))}};o(Cs,"WriteConcern");var Kp=Cs;j_.exports=Kp});var Xp=w(U_=>{"use strict";function u2(){let e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}o(u2,"asyncIterator");U_.asyncIterator=u2});var b=w((Yc,k_)=>{"use strict";var Vn=V().MongoError,c2=an(),f2=o(function(e){var t={};for(var r in e)t[r]=e[r];return t},"shallowClone"),l2=o(function(e,t,r){Object.defineProperty(e,t,{enumerable:!0,get:function(){return r}})},"getSingleProperty"),h2=Yc.formatSortValue=function(e){var t=(""+e).toLowerCase();switch(t){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},d2=Yc.formattedOrderClause=function(e){var t=new Map;if(e==null)return null;if(Array.isArray(e)){if(e.length===0)return null;for(var r=0;r{if(e==null)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(r))throw new TypeError("This method requires an array of arguments to apply");n=n||{};let i=e.s.promiseLibrary,s=r[r.length-1],a,u,c;if(!n.skipSessions&&e.hasSessionSupport()){if(u=r[r.length-2],u==null||u.session==null){c=Symbol(),a=e.startSession({owner:c});let h=r.length-2;r[h]=Object.assign({},r[h],{session:a})}else if(u.session&&u.session.hasEnded)throw new Vn("Use of expired sessions is not permitted")}let f=o((h,l)=>o(function(m,S){if(a&&a.owner===c&&!n.returnsCursor)a.endSession(()=>{if(delete u.session,m)return l(m);h(S)});else{if(m)return l(m);h(S)}},"executeCallback"),"makeExecuteCallback");if(typeof s=="function"){s=r.pop();let h=f(l=>s(null,l),l=>s(l,null));r.push(h);try{return t.apply(null,r)}catch(l){throw h(l),l}}if(r[r.length-1]!=null)throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new i(function(h,l){let d=f(h,l);r[r.length-1]=d;try{return t.apply(null,r)}catch(m){d(m)}})},"executeLegacyOperation");function b2(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e}o(b2,"applyRetryableWrites");function C2(e,t,r){r=r||{};let n=t.db,i=t.collection;if(r.session&&r.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;let s=c2.fromOptions(r);return s?Object.assign(e,{writeConcern:s}):i&&i.writeConcern?Object.assign(e,{writeConcern:Object.assign({},i.writeConcern)}):n&&n.writeConcern?Object.assign(e,{writeConcern:Object.assign({},n.writeConcern)}):e}o(C2,"applyWriteConcern");function A2(e){return e&&typeof e.then=="function"}o(A2,"isPromiseLike");function I2(e,t,r){let n=t.s&&t.s.topology||t.topology;if(!n)throw new TypeError('parameter "target" is missing a topology');let i=n.capabilities();if(r.collation&&typeof r.collation=="object")if(i&&i.commandsTakeCollation)e.collation=r.collation;else throw new Vn("Current topology does not support collation")}o(I2,"decorateWithCollation");function B2(e,t,r){if(r&&r.session&&r.session.inTransaction())return;let n=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(n,t.s.readConcern),Object.keys(n).length>0&&Object.assign(e,{readConcern:n})}o(B2,"decorateWithReadConcern");function R2(e,t){return e.explain?e:{explain:e,verbosity:t.verbosity}}o(R2,"decorateWithExplain");var $_=+process.version.split(".")[0].substring(1),M2=o(e=>$_<=6?process.emitWarning(e,"DeprecationWarning",As):process.emitWarning(e,{type:"DeprecationWarning",code:As}),"emitProcessWarning"),x2=o(e=>console.error(e),"emitConsoleWarning"),z_=process.emitWarning?M2:x2;function q2(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}o(q2,"defaultMsgHandler");function D2(e,t){if(process.noDeprecation===!0)return t;let r=e.msgHandler?e.msgHandler:q2,n=new Set;function i(){let s=arguments[e.optionsIndex];return!kc(s)||Object.keys(s).length===0?t.apply(this,arguments):(e.deprecatedOptions.forEach(a=>{if(Object.prototype.hasOwnProperty.call(s,a)&&!n.has(a)){n.add(a);let u=r(e.name,a);if(z_(u),this&&this.getLogger){let c=this.getLogger();c&&c.warn(u)}}}),t.apply(this,arguments))}return o(i,"deprecated"),Object.setPrototypeOf(i,t),t.prototype&&(i.prototype=t.prototype),i}o(D2,"deprecateOptions");var Jp={};try{Xp(),Jp.ASYNC_ITERATOR=!0}catch{Jp.ASYNC_ITERATOR=!1}var Ca=class Ca{constructor(t,r){this.db=t,this.collection=r}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(t){return new Ca(this.db,t)}static fromString(t){if(!t)throw new Error(`Cannot parse namespace from "${t}"`);let r=t.indexOf(".");return new Ca(t.substring(0,r),t.substring(r+1))}};o(Ca,"MongoDBNamespace");var Zp=Ca;function*P2(e){let t=e||0;for(;;){let r=t;t+=1,yield r}}o(P2,"makeCounter");function L2(e,t,r){let n=e&&e.s&&e.s.promiseLibrary||Promise,i;return typeof t!="function"&&(i=new n((s,a)=>{t=o((u,c)=>{if(u)return a(u);s(c)},"callback")})),r(function(s,a){if(s!=null){try{t(s)}catch(u){return process.nextTick(()=>{throw u})}return}t(s,a)}),i}o(L2,"maybePromise");function em(){let e=process.hrtime();return Math.floor(e[0]*1e3+e[1]/1e6)}o(em,"now");function j2(e){if(typeof e!="number")throw TypeError("numeric value required to calculate duration");let t=em()-e;return t<0?0:t}o(j2,"calculateDurationInMs");function U2(e,t){let r,n,i,s=!1;t=t||{};let a=t.interval||1e3,u=t.minInterval||500,c=typeof t.immediate=="boolean"?t.immediate:!1,f=typeof t.clock=="function"?t.clock:em;function h(){let S=f(),E=S-i,O=S-n,T=a-O;i=S,!(Eu&&d(u),T<0&&m())}o(h,"wake");function l(){s=!0,r&&(clearTimeout(r),r=null),n=0,i=0}o(l,"stop");function d(S){s||(clearTimeout(r),r=setTimeout(m,S||a))}o(d,"reschedule");function m(){i=0,n=f(),e(S=>{if(S)throw S;d(a)})}return o(m,"executeAndReschedule"),c?m():(n=f(),d()),{wake:h,stop:l}}o(U2,"makeInterruptableAsyncInterval");function V_(e){return Array.isArray(e)?e.reduce((t,r)=>t||V_(r),null):Object.keys(typeof e.toBSON!="function"?e:e.toBSON()).map(t=>t[0]).indexOf("$")>=0}o(V_,"hasAtomicOperators");var As="MONGODB DRIVER";function H_(e){return process.emitWarning?$_<=6?process.emitWarning(e,void 0,As):process.emitWarning(e,{code:As}):console.error(`[${As}] Warning:`,e)}o(H_,"emitWarning");var F_=new Set;function W2(e){if(!F_.has(e))return F_.add(e),H_(e)}o(W2,"emitWarningOnce");function F2(e,t){e=Array.isArray(e)?new Set(e):e,t=Array.isArray(t)?new Set(t):t;for(let r of t)if(!e.has(r))return!1;return!0}o(F2,"isSuperset");function $2(e,t){let r=Object.prototype.toString,n=Object.prototype.hasOwnProperty,i=o(a=>r.call(a)==="[object Object]","isObject");if(!i(e))return!1;let s=e.constructor;if(s&&s.prototype&&(!i(s.prototype)||!n.call(s.prototype,"isPrototypeOf")))return!1;if(t){let a=Object.keys(e);return F2(a,t)}return!0}o($2,"isRecord");function Qp(e){if(e==null)return e;if(Array.isArray(e))return e.map(r=>Qp(r));if($2(e)){let r={};for(let n in e)r[n]=Qp(e[n]);return r}let t=e.constructor;if(t)switch(t.name.toLowerCase()){case"date":return new t(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return Buffer.from(e)}return e}o(Qp,"deepCopy");function z2(e){let t=e.version.split(".").map(r=>Number.parseInt(r,10));return{major:t[0],minor:t[1],patch:t[2]}}o(z2,"parsePackageVersion");k_.exports={filterOptions:_2,mergeOptions:v2,translateOptions:E2,shallowClone:f2,getSingleProperty:l2,checkCollectionName:p2,toError:y2,formattedOrderClause:d2,parseIndexOptions:S2,normalizeHintField:g2,handleCallback:m2,decorateCommand:O2,isObject:kc,debugOptions:w2,MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:T2,executeLegacyOperation:N2,applyRetryableWrites:b2,applyWriteConcern:C2,isPromiseLike:A2,decorateWithCollation:I2,decorateWithReadConcern:B2,decorateWithExplain:R2,deprecateOptions:D2,SUPPORTS:Jp,MongoDBNamespace:Zp,emitDeprecationWarning:z_,makeCounter:P2,maybePromise:L2,now:em,calculateDurationInMs:j2,makeInterruptableAsyncInterval:U2,hasAtomicOperators:V_,MONGODB_WARNING_CODE:As,emitWarning:H_,emitWarningOnce:W2,deepCopy:Qp,parsePackageVersion:z2}});var mt=w((Gre,K_)=>{"use strict";var Y_=b().parsePackageVersion,V2=V().MongoError,Kc=Fc()(require);function H2(e,t){let r={};return e.forEach(function(n){r[n]=t[n]}),r}o(H2,"debugOptions");function k2(){let e=Wc();e.native=!1;let t=Kc("bson-ext"),r=Y_(Kc("bson-ext/package.json")||{version:"0.0.0"});if(t){if(r.major>=4)throw new V2("bson-ext version 4 and above does not work with the 3.x version of the mongodb driver");return t.native=!0,t}return e}o(k2,"retrieveBSON");function Gc(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}o(Gc,"noSnappyWarning");var G_=Symbol("kPkgVersion");function Y2(){let e=Kc("snappy");if(!e)return{compress:Gc,uncompress:Gc,compressSync:Gc,uncompressSync:Gc};let t=Kc("snappy/package.json")||{version:"0.0.0"},r=Y_(t);if(e[G_]=r,r.major>=7){let n=e.compress,i=e.uncompress;e.compress=(s,a)=>{n(s).then(u=>a(void 0,u)).catch(u=>a(u))},e.uncompress=(s,a)=>{i(s).then(u=>a(void 0,u)).catch(u=>a(u))}}return e}o(Y2,"retrieveSnappy");K_.exports={PKG_VERSION:G_,debugOptions:H2,retrieveBSON:k2,retrieveSnappy:Y2}});var wt=w((Xre,X_)=>{"use strict";var G2=b().emitWarningOnce,le=o(function(e,t,r){if(!le.isValid(e))throw new TypeError(`Invalid read preference mode ${e}`);if(t&&!Array.isArray(t)){G2("ReadPreference tags must be an array, this will change in the next major version");let n=typeof t.maxStalenessSeconds<"u",i=typeof t.hedge<"u";n||i?(r=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=r&&r.hedge,r=r||{},r.maxStalenessSeconds!=null){if(r.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=r.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===le.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}},"ReadPreference");Object.defineProperty(le.prototype,"preference",{enumerable:!0,get:function(){return this.mode}});le.PRIMARY="primary";le.PRIMARY_PREFERRED="primaryPreferred";le.SECONDARY="secondary";le.SECONDARY_PREFERRED="secondaryPreferred";le.NEAREST="nearest";var K2=[le.PRIMARY,le.PRIMARY_PREFERRED,le.SECONDARY,le.SECONDARY_PREFERRED,le.NEAREST,null];le.fromOptions=function(e){if(!e)return null;let t=e.readPreference;if(!t)return null;let r=e.readPreferenceTags,n=e.maxStalenessSeconds;if(typeof t=="string")return new le(t,r);if(!(t instanceof le)&&typeof t=="object"){let i=t.mode||t.preference;if(i&&typeof i=="string")return new le(i,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||n,hedge:t.hedge})}return t};le.resolve=function(e,t){t=t||{};let r=t.session,n=e&&e.readPreference,i;return t.readPreference?i=le.fromOptions(t):r&&r.inTransaction()&&r.transaction.options.readPreference?i=r.transaction.options.readPreference:n!=null?i=n:i=le.primary,typeof i=="string"?new le(i):i};le.translate=function(e){if(e.readPreference==null)return e;let t=e.readPreference;if(typeof t=="string")e.readPreference=new le(t);else if(t&&!(t instanceof le)&&typeof t=="object"){let r=t.mode||t.preference;r&&typeof r=="string"&&(e.readPreference=new le(r,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}else if(!(t instanceof le))throw new TypeError("Invalid read preference: "+t);return e};le.isValid=function(e){return K2.indexOf(e)!==-1};le.prototype.isValid=function(e){return le.isValid(typeof e=="string"?e:this.mode)};var X2=["primaryPreferred","secondary","secondaryPreferred","nearest"];le.prototype.slaveOk=function(){return X2.indexOf(this.mode)!==-1};le.prototype.equals=function(e){return e.mode===this.mode};le.prototype.toJSON=function(){let e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e};le.primary=new le("primary");le.primaryPreferred=new le("primaryPreferred");le.secondary=new le("secondary");le.secondaryPreferred=new le("secondaryPreferred");le.nearest=new le("nearest");X_.exports=le});var bt=w((Zre,Z_)=>{"use strict";var J2="closing",Z2="closed",Q2="connecting",ej="connected",J_={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"},tj={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};function rj(e){let t=e.s.description||e.s.serverDescription;return t.topologyType===J_.Single?t.servers[0].type:t.type}o(rj,"serverType");var nj={useUnifiedTopology:!0,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500};function ij(e){e.forEach(clearTimeout),e.clear()}o(ij,"drainTimerQueue");function sj(e,t){return clearTimeout(e),t.delete(e)}o(sj,"clearAndRemoveTimerFrom");Z_.exports={STATE_CLOSING:J2,STATE_CLOSED:Z2,STATE_CONNECTING:Q2,STATE_CONNECTED:ej,TOPOLOGY_DEFAULTS:nj,TopologyType:J_,ServerType:tj,serverType:rj,drainTimerQueue:ij,clearAndRemoveTimerFrom:sj}});var Ri=w((ene,tT)=>{"use strict";var oj=re().arrayStrictEqual,aj=re().tagsStrictEqual,uj=re().errorStrictEqual,Ot=bt().ServerType,cj=b().now,fj=new Set([Ot.RSPrimary,Ot.Standalone,Ot.Mongos]),lj=new Set([Ot.RSPrimary,Ot.RSSecondary,Ot.Mongos,Ot.Standalone]),hj=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"],rm=class rm{constructor(t,r,n){n=n||{},r=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},r),r.isWritablePrimary!=null&&(r.ismaster=r.isWritablePrimary),this.address=t,this.error=n.error,this.roundTripTime=n.roundTripTime||-1,this.lastUpdateTime=cj(),this.lastWriteDate=r.lastWrite?r.lastWrite.lastWriteDate:null,this.opTime=r.lastWrite?r.lastWrite.opTime:null,this.type=Q_(r),this.topologyVersion=n.topologyVersion||r.topologyVersion,hj.forEach(i=>{typeof r[i]<"u"&&(this[i]=r[i])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(i=>i.toLowerCase()),this.passives=this.passives.map(i=>i.toLowerCase()),this.arbiters=this.arbiters.map(i=>i.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===Ot.RSSecondary||this.isWritable}get isDataBearing(){return lj.has(this.type)}get isWritable(){return fj.has(this.type)}get host(){let t=`:${this.port}`.length;return this.address.slice(0,-t)}get port(){let t=this.address.split(":").pop();return t&&Number.parseInt(t,10)}equals(t){let r=this.topologyVersion===t.topologyVersion||eT(this.topologyVersion,t.topologyVersion)===0;return t!=null&&uj(this.error,t.error)&&this.type===t.type&&this.minWireVersion===t.minWireVersion&&this.me===t.me&&oj(this.hosts,t.hosts)&&aj(this.tags,t.tags)&&this.setName===t.setName&&this.setVersion===t.setVersion&&(this.electionId?t.electionId&&this.electionId.equals(t.electionId):this.electionId===t.electionId)&&this.primary===t.primary&&this.logicalSessionTimeoutMinutes===t.logicalSessionTimeoutMinutes&&r}};o(rm,"ServerDescription");var tm=rm;function Q_(e){return!e||!e.ok?Ot.Unknown:e.isreplicaset?Ot.RSGhost:e.msg&&e.msg==="isdbgrid"?Ot.Mongos:e.setName?e.hidden?Ot.RSOther:e.ismaster?Ot.RSPrimary:e.secondary?Ot.RSSecondary:e.arbiterOnly?Ot.RSArbiter:Ot.RSOther:Ot.Standalone}o(Q_,"parseServerType");function eT(e,t){return e==null||t==null?-1:e.processId.equals(t.processId)?e.counter===t.counter?0:e.counter{"use strict";var dj="2.6",pj="5.0";rT.exports={MIN_SUPPORTED_SERVER_VERSION:dj,MAX_SUPPORTED_SERVER_VERSION:pj,MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:13}});var sm=w((nne,oT)=>{"use strict";var Je=bt().ServerType,Bs=Ri().ServerDescription,Xc=nm(),Pt=bt().TopologyType,mj=Xc.MIN_SUPPORTED_SERVER_VERSION,yj=Xc.MAX_SUPPORTED_SERVER_VERSION,nT=Xc.MIN_SUPPORTED_WIRE_VERSION,iT=Xc.MAX_SUPPORTED_WIRE_VERSION,Is=class Is{constructor(t,r,n,i,s,a,u){u=u||{},this.type=t||Pt.Unknown,this.setName=n||null,this.maxSetVersion=i||null,this.maxElectionId=s||null,this.servers=r||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=u.heartbeatFrequencyMS||0,this.localThresholdMS=u.localThresholdMS||0,this.commonWireVersion=a||null,Object.defineProperty(this,"options",{value:u,enumberable:!1});for(let c of this.servers.values())if(c.type!==Je.Unknown&&(c.minWireVersion>iT&&(this.compatible=!1,this.compatibilityError=`Server at ${c.address} requires wire version ${c.minWireVersion}, but this version of the driver only supports up to ${iT} (MongoDB ${yj})`),c.maxWireVersion=0&&f.delete(r),c===Je.RSPrimary){let h=sT(f,i,t,s,a);n=h[0],i=h[1],s=h[2],a=h[3]}else if([Je.RSSecondary,Je.RSArbiter,Je.RSOther].indexOf(c)>=0){let h=Oj(f,i,t);n=h[0],i=h[1]}}if(n===Pt.ReplicaSetWithPrimary)if([Je.Standalone,Je.Mongos].indexOf(c)>=0)f.delete(r),n=Rs(f);else if(c===Je.RSPrimary){let h=sT(f,i,t,s,a);n=h[0],i=h[1],s=h[2],a=h[3]}else[Je.RSSecondary,Je.RSArbiter,Je.RSOther].indexOf(c)>=0?n=wj(f,i,t):n=Rs(f);return new Is(n,f,i,s,a,u,this.options)}get error(){let t=Array.from(this.servers.values()).filter(r=>r.error);if(t.length>0)return t[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(t=>t.type!==Je.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(t=>t.isDataBearing)}hasServer(t){return this.servers.has(t)}};o(Is,"TopologyDescription");var im=Is;function gj(e){return e===Je.Standalone?Pt.Single:e===Je.Mongos?Pt.Sharded:e===Je.RSPrimary?Pt.ReplicaSetWithPrimary:e===Je.RSGhost||e===Je.Unknown?Pt.Unknown:Pt.ReplicaSetNoPrimary}o(gj,"topologyTypeForServerType");function Sj(e,t){if(e==null)return-1;if(t==null)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){let i=e.id,s=t.id;return i.compare(s)}let r=e.toString(),n=t.toString();return r.localeCompare(n)}o(Sj,"compareObjectId");function sT(e,t,r,n,i){if(t=t||r.setName,t!==r.setName)return e.delete(r.address),[Rs(e),t,n,i];let s=r.electionId?r.electionId:null;if(r.setVersion&&s){if(n&&i&&(n>r.setVersion||Sj(i,s)>0))return e.set(r.address,new Bs(r.address)),[Rs(e),t,n,i];i=r.electionId}r.setVersion!=null&&(n==null||r.setVersion>n)&&(n=r.setVersion);for(let c of e.keys()){let f=e.get(c);if(f.type===Je.RSPrimary&&f.address!==r.address){e.set(c,new Bs(f.address));break}}r.allHosts.forEach(c=>{e.has(c)||e.set(c,new Bs(c))});let a=Array.from(e.keys()),u=r.allHosts;return a.filter(c=>u.indexOf(c)===-1).forEach(c=>{e.delete(c)}),[Rs(e),t,n,i]}o(sT,"updateRsFromPrimary");function wj(e,t,r){if(t==null)throw new TypeError("setName is required");return(t!==r.setName||r.me&&r.address!==r.me)&&e.delete(r.address),Rs(e)}o(wj,"updateRsWithPrimaryFromMember");function Oj(e,t,r){let n=Pt.ReplicaSetNoPrimary;return t=t||r.setName,t!==r.setName?(e.delete(r.address),[n,t]):(r.allHosts.forEach(i=>{e.has(i)||e.set(i,new Bs(i))}),r.me&&r.address!==r.me&&e.delete(r.address),[n,t])}o(Oj,"updateRsNoPrimaryFromMember");function Rs(e){for(let t of e.keys())if(e.get(t).type===Je.RSPrimary)return Pt.ReplicaSetWithPrimary;return Pt.ReplicaSetNoPrimary}o(Rs,"checkHasPrimary");oT.exports={TopologyDescription:im}});var We=w((sne,uT)=>{"use strict";var om=wt(),vj=V().MongoError,aT=bt().ServerType,Ej=sm().TopologyDescription,_j=16,Tj=9,Nj={OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},bj=o(function(e,t){var r=e.readPreference||new om("primary");if(t.readPreference&&(r=t.readPreference),typeof r=="string"&&(r=new om(r)),!(r instanceof om))throw new vj("read preference must be a ReadPreference instance");return r},"getReadPreference"),Cj=o(function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},"parseHeader");function Aj(e,t){return Object.assign(e,{raw:typeof t.raw=="boolean"?t.raw:!1,promoteLongs:typeof t.promoteLongs=="boolean"?t.promoteLongs:!0,promoteValues:typeof t.promoteValues=="boolean"?t.promoteValues:!0,promoteBuffers:typeof t.promoteBuffers=="boolean"?t.promoteBuffers:!1,bsonRegExp:typeof t.bsonRegExp=="boolean"?t.bsonRegExp:!1,monitoring:typeof t.monitoring=="boolean"?t.monitoring:!1,fullResult:typeof t.fullResult=="boolean"?t.fullResult:!1}),typeof t.socketTimeout=="number"&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),typeof t.documentsReturnedIn=="string"&&(e.documentsReturnedIn=t.documentsReturnedIn),e}o(Aj,"applyCommonQueryOptions");function Ij(e){return e.type==="mongos"||e.description&&e.description.type===aT.Mongos?!0:e.description&&e.description instanceof Ej?Array.from(e.description.servers.values()).some(r=>r.type===aT.Mongos):!1}o(Ij,"isSharded");function Bj(e){return e.split(".")[0]}o(Bj,"databaseNamespace");function Rj(e){return e.split(".").slice(1).join(".")}o(Rj,"collectionNamespace");uT.exports={getReadPreference:bj,MESSAGE_HEADER_SIZE:_j,COMPRESSION_DETAILS_SIZE:Tj,opcodes:Nj,parseHeader:Cj,applyCommonQueryOptions:Aj,isSharded:Ij,databaseNamespace:Bj,collectionNamespace:Rj}});var un=w((ane,lT)=>{"use strict";var cT=mt().retrieveSnappy(),fT=require("zlib"),Jc={snappy:1,zlib:2},Mj=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);function xj(e,t,r){switch(e.options.agreedCompressor){case"snappy":cT.compress(t,r);break;case"zlib":var n={};e.options.zlibCompressionLevel&&(n.level=e.options.zlibCompressionLevel),fT.deflate(t,n,r);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}}o(xj,"compress");function qj(e,t,r){if(e<0||e>Jc.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case Jc.snappy:cT.uncompress(t,r);break;case Jc.zlib:fT.inflate(t,r);break;default:r(null,t)}}o(qj,"decompress");lT.exports={compressorIDs:Jc,uncompressibleCommands:Mj,compress:xj,decompress:qj}});var qr=w((am,dT)=>{var Zc=require("buffer"),Fr=Zc.Buffer;function hT(e,t){for(var r in e)t[r]=e[r]}o(hT,"copyProps");Fr.from&&Fr.alloc&&Fr.allocUnsafe&&Fr.allocUnsafeSlow?dT.exports=Zc:(hT(Zc,am),am.Buffer=Mi);function Mi(e,t,r){return Fr(e,t,r)}o(Mi,"SafeBuffer");Mi.prototype=Object.create(Fr.prototype);hT(Fr,Mi);Mi.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return Fr(e,t,r)};Mi.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=Fr(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};Mi.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Fr(e)};Mi.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Zc.SlowBuffer(e)}});var sr=w((fne,yT)=>{"use strict";var Dj=mt().retrieveBSON,Pj=Dj(),Lj=Pj.Long,Aa=qr().Buffer,Ia=0,mr=We().opcodes,jj=2,Uj=4,Wj=8,Fj=16,$j=32,zj=64,Vj=128,Hj=1,kj=2,Yj=4,Gj=8,Ms=o(function(e,t,r,n){var i=this;if(t==null)throw new Error("ns must be specified for query");if(r==null)throw new Error("query must be specified for query");if(t.indexOf("\0")!==-1)throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=r,this.numberToSkip=n.numberToSkip||0,this.numberToReturn=n.numberToReturn||0,this.returnFieldSelector=n.returnFieldSelector||null,this.requestId=Ms.getRequestId(),this.pre32Limit=n.pre32Limit,this.serializeFunctions=typeof n.serializeFunctions=="boolean"?n.serializeFunctions:!1,this.ignoreUndefined=typeof n.ignoreUndefined=="boolean"?n.ignoreUndefined:!1,this.maxBsonSize=n.maxBsonSize||1024*1024*16,this.checkKeys=typeof n.checkKeys=="boolean"?n.checkKeys:!0,this.batchSize=i.numberToReturn,this.tailable=!1,this.slaveOk=typeof n.slaveOk=="boolean"?n.slaveOk:!1,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1},"Query");Ms.prototype.incRequestId=function(){this.requestId=Ia++};Ms.nextRequestId=function(){return Ia+1};Ms.prototype.toBin=function(){var e=this,t=[],r=null,n=0;this.tailable&&(n|=jj),this.slaveOk&&(n|=Uj),this.oplogReplay&&(n|=Wj),this.noCursorTimeout&&(n|=Fj),this.awaitData&&(n|=$j),this.exhaust&&(n|=zj),this.partial&&(n|=Vj),e.batchSize!==e.numberToReturn&&(e.numberToReturn=e.batchSize);var i=Aa.alloc(4*4+4+Aa.byteLength(e.ns)+1+4+4);t.push(i);var s=e.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(s),e.returnFieldSelector&&Object.keys(e.returnFieldSelector).length>0&&(r=e.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),t.push(r));var a=i.length+s.length+(r?r.length:0),u=4;return i[3]=a>>24&255,i[2]=a>>16&255,i[1]=a>>8&255,i[0]=a&255,i[u+3]=this.requestId>>24&255,i[u+2]=this.requestId>>16&255,i[u+1]=this.requestId>>8&255,i[u]=this.requestId&255,u=u+4,i[u+3]=0,i[u+2]=0,i[u+1]=0,i[u]=0,u=u+4,i[u+3]=mr.OP_QUERY>>24&255,i[u+2]=mr.OP_QUERY>>16&255,i[u+1]=mr.OP_QUERY>>8&255,i[u]=mr.OP_QUERY&255,u=u+4,i[u+3]=n>>24&255,i[u+2]=n>>16&255,i[u+1]=n>>8&255,i[u]=n&255,u=u+4,u=u+i.write(this.ns,u,"utf8")+1,i[u-1]=0,i[u+3]=this.numberToSkip>>24&255,i[u+2]=this.numberToSkip>>16&255,i[u+1]=this.numberToSkip>>8&255,i[u]=this.numberToSkip&255,u=u+4,i[u+3]=this.numberToReturn>>24&255,i[u+2]=this.numberToReturn>>16&255,i[u+1]=this.numberToReturn>>8&255,i[u]=this.numberToReturn&255,u=u+4,t};Ms.getRequestId=function(){return++Ia};var pT=o(function(e,t,r,n){n=n||{},this.numberToReturn=n.numberToReturn||0,this.requestId=Ia++,this.bson=e,this.ns=t,this.cursorId=r},"GetMore");pT.prototype.toBin=function(){var e=4+Aa.byteLength(this.ns)+1+4+8+16,t=0,r=Aa.alloc(e);return r[t+3]=e>>24&255,r[t+2]=e>>16&255,r[t+1]=e>>8&255,r[t]=e&255,t=t+4,r[t+3]=this.requestId>>24&255,r[t+2]=this.requestId>>16&255,r[t+1]=this.requestId>>8&255,r[t]=this.requestId&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,r[t+3]=mr.OP_GETMORE>>24&255,r[t+2]=mr.OP_GETMORE>>16&255,r[t+1]=mr.OP_GETMORE>>8&255,r[t]=mr.OP_GETMORE&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,t=t+r.write(this.ns,t,"utf8")+1,r[t-1]=0,r[t+3]=this.numberToReturn>>24&255,r[t+2]=this.numberToReturn>>16&255,r[t+1]=this.numberToReturn>>8&255,r[t]=this.numberToReturn&255,t=t+4,r[t+3]=this.cursorId.getLowBits()>>24&255,r[t+2]=this.cursorId.getLowBits()>>16&255,r[t+1]=this.cursorId.getLowBits()>>8&255,r[t]=this.cursorId.getLowBits()&255,t=t+4,r[t+3]=this.cursorId.getHighBits()>>24&255,r[t+2]=this.cursorId.getHighBits()>>16&255,r[t+1]=this.cursorId.getHighBits()>>8&255,r[t]=this.cursorId.getHighBits()&255,t=t+4,r};var mT=o(function(e,t,r){this.ns=t,this.requestId=Ia++,this.cursorIds=r},"KillCursor");mT.prototype.toBin=function(){var e=24+this.cursorIds.length*8,t=0,r=Aa.alloc(e);r[t+3]=e>>24&255,r[t+2]=e>>16&255,r[t+1]=e>>8&255,r[t]=e&255,t=t+4,r[t+3]=this.requestId>>24&255,r[t+2]=this.requestId>>16&255,r[t+1]=this.requestId>>8&255,r[t]=this.requestId&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,r[t+3]=mr.OP_KILL_CURSORS>>24&255,r[t+2]=mr.OP_KILL_CURSORS>>16&255,r[t+1]=mr.OP_KILL_CURSORS>>8&255,r[t]=mr.OP_KILL_CURSORS&255,t=t+4,r[t+3]=0,r[t+2]=0,r[t+1]=0,r[t]=0,t=t+4,r[t+3]=this.cursorIds.length>>24&255,r[t+2]=this.cursorIds.length>>16&255,r[t+1]=this.cursorIds.length>>8&255,r[t]=this.cursorIds.length&255,t=t+4;for(var n=0;n>24&255,r[t+2]=this.cursorIds[n].getLowBits()>>16&255,r[t+1]=this.cursorIds[n].getLowBits()>>8&255,r[t]=this.cursorIds[n].getLowBits()&255,t=t+4,r[t+3]=this.cursorIds[n].getHighBits()>>24&255,r[t+2]=this.cursorIds[n].getHighBits()>>16&255,r[t+1]=this.cursorIds[n].getHighBits()>>8&255,r[t]=this.cursorIds[n].getHighBits()&255,t=t+4;return r};var um=o(function(e,t,r,n,i){i=i||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.parsed=!1,this.raw=t,this.data=n,this.bson=e,this.opts=i,this.length=r.length,this.requestId=r.requestId,this.responseTo=r.responseTo,this.opCode=r.opCode,this.fromCompressed=r.fromCompressed,this.responseFlags=n.readInt32LE(0),this.cursorId=new Lj(n.readInt32LE(4),n.readInt32LE(8)),this.startingFrom=n.readInt32LE(12),this.numberReturned=n.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=(this.responseFlags&Hj)!==0,this.queryFailure=(this.responseFlags&kj)!==0,this.shardConfigStale=(this.responseFlags&Yj)!==0,this.awaitCapable=(this.responseFlags&Gj)!==0,this.promoteLongs=typeof i.promoteLongs=="boolean"?i.promoteLongs:!0,this.promoteValues=typeof i.promoteValues=="boolean"?i.promoteValues:!0,this.promoteBuffers=typeof i.promoteBuffers=="boolean"?i.promoteBuffers:!1,this.bsonRegExp=typeof i.bsonRegExp=="boolean"?i.bsonRegExp:!1},"Response");um.prototype.isParsed=function(){return this.parsed};um.prototype.parse=function(e){if(!this.parsed){e=e||{};var t=e.raw||!1,r=e.documentsReturnedIn||null,n=typeof e.promoteLongs=="boolean"?e.promoteLongs:this.opts.promoteLongs,i=typeof e.promoteValues=="boolean"?e.promoteValues:this.opts.promoteValues,s=typeof e.promoteBuffers=="boolean"?e.promoteBuffers:this.opts.promoteBuffers,a=typeof e.bsonRegExp=="boolean"?e.bsonRegExp:this.opts.bsonRegExp,u,c;c={promoteLongs:n,promoteValues:i,promoteBuffers:s,bsonRegExp:a},this.index=20;for(var f=0;f{"use strict";var gT=qr().Buffer,Kj=We().opcodes,Xj=We().databaseNamespace,Jj=wt(),Zj=V().MongoError,cm=0,ST=1,wT=2,OT=65536,ef=class ef{constructor(t,r,n,i){if(n==null)throw new Error("query must be specified for query");this.bson=t,this.ns=r,this.command=n,this.command.$db=Xj(r),i.readPreference&&i.readPreference.mode!==Jj.PRIMARY&&(this.command.$readPreference=i.readPreference.toJSON()),this.options=i||{},this.requestId=i.requestId?i.requestId:ef.getRequestId(),this.serializeFunctions=typeof i.serializeFunctions=="boolean"?i.serializeFunctions:!1,this.ignoreUndefined=typeof i.ignoreUndefined=="boolean"?i.ignoreUndefined:!1,this.checkKeys=typeof i.checkKeys=="boolean"?i.checkKeys:!1,this.maxBsonSize=i.maxBsonSize||1024*1024*16,this.checksumPresent=!1,this.moreToCome=i.moreToCome||!1,this.exhaustAllowed=typeof i.exhaustAllowed=="boolean"?i.exhaustAllowed:!1}toBin(){let t=[],r=0;this.checksumPresent&&(r|=ST),this.moreToCome&&(r|=wT),this.exhaustAllowed&&(r|=OT);let n=gT.alloc(4*4+4);t.push(n);let i=n.length,s=this.command;return i+=this.makeDocumentSegment(t,s),n.writeInt32LE(i,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(Kj.OP_MSG,12),n.writeUInt32LE(r,16),t}makeDocumentSegment(t,r){let n=gT.alloc(1);n[0]=0;let i=this.serializeBson(r);return t.push(n),t.push(i),n.length+i.length}serializeBson(t){return this.bson.serialize(t,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}};o(ef,"Msg");var Qc=ef;Qc.getRequestId=function(){return cm=cm+1&2147483647,cm};var lm=class lm{constructor(t,r,n,i,s){s=s||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.parsed=!1,this.raw=r,this.data=i,this.bson=t,this.opts=s,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=i.readInt32LE(0),this.checksumPresent=(this.responseFlags&ST)!==0,this.moreToCome=(this.responseFlags&wT)!==0,this.exhaustAllowed=(this.responseFlags&OT)!==0,this.promoteLongs=typeof s.promoteLongs=="boolean"?s.promoteLongs:!0,this.promoteValues=typeof s.promoteValues=="boolean"?s.promoteValues:!0,this.promoteBuffers=typeof s.promoteBuffers=="boolean"?s.promoteBuffers:!1,this.bsonRegExp=typeof s.bsonRegExp=="boolean"?s.bsonRegExp:!1,this.documents=[]}isParsed(){return this.parsed}parse(t){if(this.parsed)return;t=t||{},this.index=4;let r=t.raw||!1,n=t.documentsReturnedIn||null,i=typeof t.promoteLongs=="boolean"?t.promoteLongs:this.opts.promoteLongs,s=typeof t.promoteValues=="boolean"?t.promoteValues:this.opts.promoteValues,a=typeof t.promoteBuffers=="boolean"?t.promoteBuffers:this.opts.promoteBuffers,u=typeof t.bsonRegExp=="boolean"?t.bsonRegExp:this.opts.bsonRegExp,c={promoteLongs:i,promoteValues:s,promoteBuffers:a,bsonRegExp:u};for(;this.index{"use strict";var Ba=require("util").format,Qj=V().MongoError,Ra={},Ct={},or=null,Hn=process.pid,cn=null,At=o(function(e,t){if(!(this instanceof At))return new At(e,t);t=t||{},this.className=e,t.logger?cn=t.logger:cn==null&&(cn=console.log),t.loggerLevel&&(or=t.loggerLevel||"error"),Ct[this.className]==null&&(Ra[this.className]=!0)},"Logger");At.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(Ct).length>0&&Ct[this.className]||Object.keys(Ct).length===0&&Ra[this.className])){var r=new Date().getTime(),n=Ba("[%s-%s:%s] %s %s","DEBUG",this.className,Hn,r,e),i={type:"debug",message:e,className:this.className,pid:Hn,date:r};t&&(i.meta=t),cn(n,i)}};At.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(Ct).length>0&&Ct[this.className]||Object.keys(Ct).length===0&&Ra[this.className])){var r=new Date().getTime(),n=Ba("[%s-%s:%s] %s %s","WARN",this.className,Hn,r,e),i={type:"warn",message:e,className:this.className,pid:Hn,date:r};t&&(i.meta=t),cn(n,i)}},At.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(Ct).length>0&&Ct[this.className]||Object.keys(Ct).length===0&&Ra[this.className])){var r=new Date().getTime(),n=Ba("[%s-%s:%s] %s %s","INFO",this.className,Hn,r,e),i={type:"info",message:e,className:this.className,pid:Hn,date:r};t&&(i.meta=t),cn(n,i)}},At.prototype.error=function(e,t){if(this.isError()&&(Object.keys(Ct).length>0&&Ct[this.className]||Object.keys(Ct).length===0&&Ra[this.className])){var r=new Date().getTime(),n=Ba("[%s-%s:%s] %s %s","ERROR",this.className,Hn,r,e),i={type:"error",message:e,className:this.className,pid:Hn,date:r};t&&(i.meta=t),cn(n,i)}},At.prototype.isInfo=function(){return or==="info"||or==="debug"},At.prototype.isError=function(){return or==="error"||or==="info"||or==="debug"},At.prototype.isWarn=function(){return or==="error"||or==="warn"||or==="info"||or==="debug"},At.prototype.isDebug=function(){return or==="debug"};At.reset=function(){or="error",Ct={}};At.currentLogger=function(){return cn};At.setCurrentLogger=function(e){if(typeof e!="function")throw new Qj("current logger must be a function");cn=e};At.filter=function(e,t){e==="class"&&Array.isArray(t)&&(Ct={},t.forEach(function(r){Ct[r]=!0}))};At.setLevel=function(e){if(e!=="info"&&e!=="error"&&e!=="debug"&&e!=="warn")throw new Error(Ba("%s is an illegal logging level",e));or=e};ET.exports=At});var tf=w((yne,_T)=>{"use strict";var hm=o(function(e,t,r){this.result=e,this.connection=t,this.message=r},"CommandResult");hm.prototype.toJSON=function(){let e=Object.assign({},this,this.result);return delete e.message,e};hm.prototype.toString=function(){return JSON.stringify(this.toJSON())};_T.exports=hm});var Sm=w((Sne,IT)=>{"use strict";var eU=require("events").EventEmitter,tU=require("crypto"),rU=mt().debugOptions,nU=We().parseHeader,iU=un().decompress,TT=sr().Response,NT=xi().BinMsg,AT=V().MongoNetworkError,sU=V().MongoNetworkTimeoutError,mm=V().MongoError,oU=yr(),aU=We().opcodes.OP_COMPRESSED,bT=We().opcodes.OP_MSG,CT=We().MESSAGE_HEADER_SIZE,$r=qr().Buffer,uU=sr().Query,cU=tf(),fU=0,lU=1024*1024*16*4,hU=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","checkServerIdentity"],xs,qi=!1,rf={},gm=class gm extends eU{constructor(t,r){if(super(),r=r||{},!r.bson)throw new TypeError("must pass in valid bson parser");this.id=fU++,this.options=r,this.logger=oU("Connection",r),this.bson=r.bson,this.tag=r.tag,this.maxBsonMessageSize=r.maxBsonMessageSize||lU,this.helloOk=void 0,this.port=r.port||27017,this.host=r.host||"localhost",this.socketTimeout=typeof r.socketTimeout=="number"?r.socketTimeout:0,this.keepAlive=typeof r.keepAlive=="boolean"?r.keepAlive:!0,this.keepAliveInitialDelay=typeof r.keepAliveInitialDelay=="number"?r.keepAliveInitialDelay:12e4,this.connectionTimeout=typeof r.connectionTimeout=="number"?r.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(rU(hU,r))}]`),this.responseOptions={promoteLongs:typeof r.promoteLongs=="boolean"?r.promoteLongs:!0,promoteValues:typeof r.promoteValues=="boolean"?r.promoteValues:!0,promoteBuffers:typeof r.promoteBuffers=="boolean"?r.promoteBuffers:!1,bsonRegExp:typeof r.bsonRegExp=="boolean"?r.bsonRegExp:!1},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;let n=tU.createHash("sha1");n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=t,this.socket.once("error",pU(this)),this.socket.once("timeout",mU(this)),this.socket.once("close",yU(this)),this.socket.on("data",gU(this)),qi&&dU(this.id,this)}setSocketTimeout(t){this.socket&&this.socket.setTimeout(t)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(t){t&&(xs=t),qi=!0,rf={}}static disableConnectionAccounting(){qi=!1,xs=void 0}static connections(){return rf}get address(){return`${this.host}:${this.port}`}unref(){if(this.socket==null){this.once("connect",()=>this.socket.unref());return}this.socket.unref()}flush(t){for(;this.workItems.length>0;){let r=this.workItems.shift();r.cb&&r.cb(t)}}destroy(t,r){if(typeof t=="function"&&(r=t,t={}),t=Object.assign({force:!1},t),qi&&nf(this.id),this.socket==null){this.destroyed=!0;return}if(t.force||this.timedOut){this.socket.destroy(),this.destroyed=!0,typeof r=="function"&&r(null,null);return}this.socket.end(n=>{this.destroyed=!0,typeof r=="function"&&r(n,null)})}write(t){if(this.logger.isDebug())if(!Array.isArray(t))this.logger.debug(`writing buffer [ ${t.length} ] to ${this.address}`);else for(let r=0;r{},"noop");function h(m,S){i(m,S),i=f}o(h,"_callback");function l(m){s.resetSocketTimeout(),dm.forEach(S=>s.removeListener(S,l)),s.removeListener("message",d),m==null&&(m=new mm(`runCommand failed for connection to '${s.address}'`)),s.on("error",f),h(m)}o(l,"errorHandler");function d(m){if(m.responseTo!==c.requestId)return;s.resetSocketTimeout(),dm.forEach(E=>s.removeListener(E,l)),s.removeListener("message",d),m.parse({promoteValues:!0});let S=m.documents[0];if(S.ok===0||S.$err||S.errmsg||S.code){h(new mm(S));return}h(void 0,new cU(S,this,m))}o(d,"messageHandler"),s.setSocketTimeout(a),dm.forEach(m=>s.once(m,l)),s.on("message",d),s.write(c.toBin())}};o(gm,"Connection");var ym=gm,dm=["error","close","timeout","parseError"];function nf(e){delete rf[e],xs&&xs.deleteConnection(e)}o(nf,"deleteConnection");function dU(e,t){rf[e]=t,xs&&xs.addConnection(e,t)}o(dU,"addConnection");function pU(e){return function(t){qi&&nf(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] errored out with [${JSON.stringify(t)}]`),e.emit("error",new AT(t),e)}}o(pU,"errorHandler");function mU(e){return function(){qi&&nf(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new sU(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:e.ismaster==null}),e)}}o(mU,"timeoutHandler");function yU(e){return function(t){qi&&nf(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new AT(`connection ${e.id} to ${e.address} closed`),e)}}o(yU,"closeHandler");function pm(e,t){let r=nU(t);if(r.opCode!==aU){let s=r.opCode===bT?NT:TT;e.emit("message",new s(e.bson,t,r,t.slice(CT),e.responseOptions),e);return}r.fromCompressed=!0;let n=CT;r.opCode=t.readInt32LE(n),n+=4,r.length=t.readInt32LE(n),n+=4;let i=t[n];n++,iU(i,t.slice(n),(s,a)=>{if(s){e.emit("error",s);return}if(a.length!==r.length){e.emit("error",new mm("Decompressing a compressed message from the server failed. The message is corrupt."));return}let u=r.opCode===bT?NT:TT;e.emit("message",new u(e.bson,t,r,a,e.responseOptions),e)})}o(pm,"processMessage");function gU(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){let r=e.sizeOfMessage-e.bytesRead;if(r>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=$r.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,r),t=t.slice(r);let n=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,pm(e,n)}}else if(e.stubBuffer!=null&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){let r=$r.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0),t.copy(r,e.stubBuffer.length),t=r,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{let r=$r.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0),t.copy(r,e.stubBuffer.length),t=$r.alloc(0)}else if(t.length>4){let r=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(r<0||r>e.maxBsonMessageSize){let n={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:r,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};e.emit("parseError",n,e);return}if(r>4&&rt.length)e.buffer=$r.alloc(r),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=r,e.stubBuffer=null,t=$r.alloc(0);else if(r>4&&re.maxBsonMessageSize){let n={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:r,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",n,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=$r.alloc(0)}else{let n=t.slice(0,r);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(r),pm(e,n)}}else e.stubBuffer=$r.alloc(t.length),t.copy(e.stubBuffer,0),t=$r.alloc(0)}}o(gU,"dataHandler");IT.exports=ym});var Di=w((One,MT)=>{"use strict";var SU=xi().Msg,wU=sr().KillCursor,OU=sr().GetMore,qs=b().deepCopy,vU=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),EU=new Set(["hello","ismaster","isMaster"]),BT={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},RT={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},_U=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],wm=o(e=>e.ns.split(".")[1],"collectionName"),TU=o((e,t)=>vU.has(e)||EU.has(e)&&!!t.speculativeAuthenticate,"shouldRedactCommand"),NU=o(e=>{let t;if(e instanceof OU)t={getMore:qs(e.cursorId),collection:wm(e),batchSize:e.numberToReturn};else if(e instanceof wU)t={killCursors:wm(e),cursors:qs(e.cursorIds)};else if(e instanceof SU)t=qs(e.command);else if(e.query&&e.query.$query){let n;e.ns==="admin.$cmd"?n=Object.assign({},e.query.$query):(n={find:wm(e)},Object.keys(BT).forEach(i=>{typeof e.query[i]<"u"&&(n[BT[i]]=qs(e.query[i]))})),Object.keys(RT).forEach(i=>{typeof e[i]<"u"&&(n[RT[i]]=qs(e[i]))}),_U.forEach(i=>{e[i]&&(n[i]=e[i])}),typeof e.pre32Limit<"u"&&(n.limit=e.pre32Limit),e.query.$explain?t={explain:n}:t=n}else t=qs(e.query||e);let r=Object.keys(t)[0];return{cmd:t,name:r,shouldRedact:TU(r,t)}},"extractCommand");MT.exports={extractCommand:NU}});var Am=w((Ene,DT)=>{"use strict";var bU=sr().KillCursor,CU=sr().GetMore,qT=b().calculateDurationInMs,_m=Di().extractCommand,xT=o(e=>e.ns,"namespace"),AU=o(e=>e.ns.split(".")[0],"databaseName"),IU=o(e=>e.options?`${e.options.host}:${e.options.port}`:e.address,"generateConnectionId"),BU=o(e=>e.s&&e.queue,"isLegacyPool"),RU=o((e,t)=>e instanceof CU?{ok:1,cursor:{id:t.message.cursorId,ns:xT(e),nextBatch:t.message.documents}}:e instanceof bU?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&typeof e.query.$query<"u"?{ok:1,cursor:{id:t.message.cursorId,ns:xT(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,"extractReply"),Tm=o(e=>{if(BU(e))return{connectionId:IU(e)};let t=e;return{address:t.address,connectionId:t.id}},"extractConnectionDetails"),Nm=class Nm{constructor(t,r){let n=_m(r),i=n.name,s=Tm(t);Object.assign(this,s,{requestId:r.requestId,databaseName:AU(r),commandName:i,command:n.shouldRedact?{}:n.cmd})}};o(Nm,"CommandStartedEvent");var Om=Nm,bm=class bm{constructor(t,r,n,i){let s=_m(r),a=s.name,u=Tm(t);Object.assign(this,u,{requestId:r.requestId,commandName:a,duration:qT(i),reply:s.shouldRedact?{}:RU(r,n)})}};o(bm,"CommandSucceededEvent");var vm=bm,Cm=class Cm{constructor(t,r,n,i){let s=_m(r),a=s.name,u=Tm(t);Object.assign(this,u,{requestId:r.requestId,commandName:a,duration:qT(i),failure:s.shouldRedact?{}:n})}};o(Cm,"CommandFailedEvent");var Em=Cm;DT.exports={CommandStartedEvent:Om,CommandSucceededEvent:vm,CommandFailedEvent:Em}});var kn=w((Tne,PT)=>{"use strict";var Rm=class Rm{constructor(t,r,n){this.connection=t,this.credentials=r,this.options=n}};o(Rm,"AuthContext");var Im=Rm,Mm=class Mm{constructor(t){this.bson=t}prepare(t,r,n){n(void 0,t)}auth(t,r){r(new TypeError("`auth` method must be overridden by subclass"))}};o(Mm,"AuthProvider");var Bm=Mm;PT.exports={AuthContext:Im,AuthProvider:Bm}});var Dm=w((bne,jT)=>{"use strict";var LT=require("crypto"),MU=kn().AuthProvider,qm=class qm extends MU{auth(t,r){let n=t.connection,i=t.credentials,s=i.username,a=i.password,u=i.source;n.command(`${u}.$cmd`,{getnonce:1},(c,f)=>{let h=null,l=null;if(c==null){h=f.result.nonce;let S=LT.createHash("md5");S.update(s+":mongo:"+a,"utf8");let E=S.digest("hex");S=LT.createHash("md5"),S.update(h+s+E,"utf8"),l=S.digest("hex")}let d={authenticate:1,user:s,nonce:h,key:l};n.command(`${u}.$cmd`,d,r)})}};o(qm,"MongoCR");var xm=qm;jT.exports=xm});var jm=w((Ane,WT)=>{"use strict";var xU=kn().AuthProvider,Lm=class Lm extends xU{prepare(t,r,n){let i=r.credentials;Object.assign(t,{speculativeAuthenticate:UT(i)}),n(void 0,t)}auth(t,r){let n=t.connection,i=t.credentials;if(t.response.speculativeAuthenticate)return r();n.command("$external.$cmd",UT(i),r)}};o(Lm,"X509");var Pm=Lm;function UT(e){let t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.assign(t,{user:e.username}),t}o(UT,"x509AuthenticateCommand");WT.exports=Pm});var Fm=w((Bne,FT)=>{"use strict";var qU=mt().retrieveBSON,DU=kn().AuthProvider,PU=qU(),LU=PU.Binary,Wm=class Wm extends DU{auth(t,r){let n=t.connection,i=t.credentials,s=i.username,a=i.password,c={saslStart:1,mechanism:"PLAIN",payload:new LU(`\0${s}\0${a}`),autoAuthorize:1};n.command("$external.$cmd",c,r)}};o(Wm,"Plain");var Um=Wm;FT.exports=Um});var Hm=w((Mne,zT)=>{"use strict";var jU=require("dns"),UU=kn().AuthProvider,WU=re().retrieveKerberos,sf=V().MongoError,$m,Vm=class Vm extends UU{auth(t,r){let n=t.connection,i=t.credentials;if(i==null)return r(new sf("credentials required"));let s=i.username;function a(u,c){return n.command("$external.$cmd",u,c)}o(a,"externalCommand"),FU(t,(u,c)=>{if(u)return r(u);if(c==null)return r(new sf("gssapi client missing"));c.step("",(f,h)=>{if(f)return r(f);a($U(h),(l,d)=>{if(l)return r(l);let m=d.result;$T(c,10,m.payload,(S,E)=>{if(S)return r(S);a(zU(E,m.conversationId),(O,T)=>{if(O)return r(O);let R=T.result;VU(c,s,R.payload,(_,N)=>{if(_)return r(_);a({saslContinue:1,conversationId:R.conversationId,payload:N},(P,q)=>{if(P)return r(P);r(void 0,q)})})})})})})})}};o(Vm,"GSSAPI");var zm=Vm;zT.exports=zm;function FU(e,t){let r=e.options.host,n=e.options.port,i=e.credentials;if(!r||!n||!i)return t(new sf(`Connection must specify: ${r?"host":""}, ${n?"port":""}, ${i?"host":"credentials"}.`));if($m==null)try{$m=WU()}catch(f){return t(f)}let s=i.username,a=i.password,u=i.mechanismProperties,c=u.gssapiservicename||u.gssapiServiceName||"mongodb";HU(r,u,(f,h)=>{if(f)return t(f);let l={};a!=null&&Object.assign(l,{user:s,password:a}),$m.initializeClient(`${c}${process.platform==="win32"?"/":"@"}${h}`,l,(d,m)=>{if(d)return t(new sf(d));t(null,m)})})}o(FU,"makeKerberosClient");function $U(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}o($U,"saslStart");function zU(e,t){return{saslContinue:1,conversationId:t,payload:e}}o(zU,"saslContinue");function $T(e,t,r,n){e.step(r,(i,s)=>{if(i&&t===0)return n(i);if(i)return $T(e,t-1,r,n);n(void 0,s||"")})}o($T,"negotiate");function VU(e,t,r,n){e.unwrap(r,(i,s)=>{if(i)return n(i);e.wrap(s||"",{user:t},(a,u)=>{if(a)return n(a);n(void 0,u)})})}o(VU,"finalize");function HU(e,t,r){if(!(typeof t.gssapiCanonicalizeHostName=="boolean"?t.gssapiCanonicalizeHostName:!1))return r(void 0,e);jU.resolveCname(e,(i,s)=>{if(i)return r(i);if(Array.isArray(s)&&s.length>0)return r(void 0,s[0]);r(void 0,e)})}o(HU,"performGssapiCanonicalizeHostName")});var kT=w((qne,HT)=>{HT.exports=fn;function fn(e,t){if(!(this instanceof fn))return new fn(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?of(this.deduplicate.length):null}o(fn,"Pager");fn.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}e.updated||!this.updates||(e.updated=!0,this.updates.push(e))};fn.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e};fn.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;kU(this,e)}KU(e,this.path);for(var r=this.pages,n=this.level;n>0;n--){var i=this.path[n],s=r[i];if(!s){if(t)return;s=r[i]=new Array(32768)}r=s}return r};fn.prototype.get=function(e,t){var r=this._array(e,t),n=this.path[0],i=r&&r[n];return!i&&!t&&(i=r[n]=new VT(e,of(this.pageSize)),e>=this.length&&(this.length=e+1)),i&&i.buffer===this.deduplicate&&this.deduplicate&&!t&&(i.buffer=GU(i.buffer),i.deduplicate=0),i};fn.prototype.set=function(e,t){var r=this._array(e,!1),n=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=void 0;return}this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=r[n],s=YU(t,this.pageSize);i?i.buffer=s:r[n]=new VT(e,s)};fn.prototype.toBuffer=function(){for(var e=new Array(this.length),t=of(this.pageSize),r=0;rt)return e.slice(0,t);var r=of(t);return e.copy(r),r}o(YU,"truncate");function of(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}o(of,"alloc");function GU(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);return e.copy(t),t}o(GU,"copy");function VT(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}o(VT,"Page");function KU(e,t){e=(e-(t[0]=e&32767))/32768,e=(e-(t[1]=e&32767))/32768,t[3]=(e-(t[2]=e&32767))/32768&32767}o(KU,"factor")});var GT=w((Pne,YT)=>{var XU=kT();YT.exports=Yn;function Yn(e){if(!(this instanceof Yn))return new Yn(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||XU(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,!ZU(this.pageSize))throw new Error("The page size should be a power of two");if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var t=0;t>t)};Yn.prototype.getByte=function(e){var t=e&this._pageMask,r=(e-t)/this.pageSize,n=this.pages.get(r,!0);return n?n.buffer[t+this.pageOffset]:0};Yn.prototype.set=function(e,t){var r=e&7,n=(e-r)/8,i=this.getByte(n);return this.setByte(n,t?i|128>>r:i&(255^128>>r))};Yn.prototype.toBuffer=function(){for(var e=JU(this.pages.length*this.pageSize),t=0;t=this.byteLength&&(this.byteLength=e+1,this.length=this.byteLength*8),this._trackUpdates&&this.pages.updated(i),!0)};function JU(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}o(JU,"alloc");function ZU(e){return!(e&e-1)}o(ZU,"powerOfTwo")});var JT=w((jne,XT)=>{"use strict";var QU=require("fs"),eW=require("path"),tW=GT(),KT=QU.readFileSync(eW.resolve(__dirname,"../code-points.mem")),Ma=0;function Ds(){let e=KT.readUInt32BE(Ma);Ma+=4;let t=KT.slice(Ma,Ma+e);return Ma+=e,tW({buffer:t})}o(Ds,"read");var rW=Ds(),nW=Ds(),iW=Ds(),sW=Ds(),oW=Ds(),aW=Ds();XT.exports={unassigned_code_points:rW,commonly_mapped_to_nothing:nW,non_ASCII_space_characters:iW,prohibited_characters:sW,bidirectional_r_al:oW,bidirectional_l:aW}});var tN=w((Wne,eN)=>{"use strict";var{unassigned_code_points:uW,commonly_mapped_to_nothing:cW,non_ASCII_space_characters:fW,prohibited_characters:lW,bidirectional_r_al:km,bidirectional_l:hW}=JT();eN.exports=gW;var dW=fW,pW=cW,ZT=o(e=>e.codePointAt(0),"getCodePoint"),mW=o(e=>e[0],"first"),yW=o(e=>e[e.length-1],"last");function QT(e){let t=[],r=e.length;for(let n=0;n=55296&&i<=56319&&r>n+1){let s=e.charCodeAt(n+1);if(s>=56320&&s<=57343){t.push((i-55296)*1024+s-56320+65536),n+=1;continue}}t.push(i)}return t}o(QT,"toCodePoints");function gW(e,t={}){if(typeof e!="string")throw new TypeError("Expected string.");if(e.length===0)return"";let r=QT(e).map(h=>dW.get(h)?32:h).filter(h=>!pW.get(h)),n=String.fromCodePoint.apply(null,r).normalize("NFKC"),i=QT(n);if(i.some(h=>lW.get(h)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(t.allowUnassigned!==!0&&i.some(l=>uW.get(l)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5");let a=i.some(h=>km.get(h)),u=i.some(h=>hW.get(h));if(a&&u)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");let c=km.get(ZT(mW(n))),f=km.get(ZT(yW(n)));if(a&&!(c&&f))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return n}o(gW,"saslprep")});var xa=w(($ne,uN)=>{"use strict";var Li=require("crypto"),vt=qr().Buffer,SW=mt().retrieveBSON,Pi=V().MongoError,wW=kn().AuthProvider,OW=b().emitWarning,vW=SW(),Ym=vW.Binary,cf;try{cf=tN()}catch{}var Jm=class Jm extends wW{constructor(t,r){super(t),this.cryptoMethod=r||"sha1"}prepare(t,r,n){let i=this.cryptoMethod;i==="sha256"&&typeof cf!="function"&&OW("Warning: no saslprep library specified. Passwords will not be sanitized"),Li.randomBytes(24,(s,a)=>{if(s)return n(s);Object.assign(r,{nonce:a});let u=r.credentials,c=Object.assign({},t,{speculativeAuthenticate:Object.assign(sN(i,u,a),{db:u.source})});n(void 0,c)})}auth(t,r){let n=t.response;if(n&&n.speculativeAuthenticate){oN(this.cryptoMethod,n.speculativeAuthenticate,t,r);return}EW(this.cryptoMethod,t,r)}};o(Jm,"ScramSHA");var ff=Jm;function nN(e){return e.replace("=","=3D").replace(",","=2C")}o(nN,"cleanUsername");function iN(e,t){return vt.concat([vt.from("n=","utf8"),vt.from(e,"utf8"),vt.from(",r=","utf8"),vt.from(t.toString("base64"),"utf8")])}o(iN,"clientFirstMessageBare");function sN(e,t,r){let n=nN(t.username);return{saslStart:1,mechanism:e==="sha1"?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new Ym(vt.concat([vt.from("n,,","utf8"),iN(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}o(sN,"makeFirstMessage");function EW(e,t,r){let n=t.connection,i=t.credentials,s=t.nonce,a=i.source,u=sN(e,i,s);n.command(`${a}.$cmd`,u,(c,f)=>{let h=aN(c,f);if(h)return r(h);oN(e,f.result,t,r)})}o(EW,"executeScram");function oN(e,t,r,n){let i=r.connection,s=r.credentials,a=r.nonce,u=s.source,c=nN(s.username),f=s.password,h;if(e==="sha256")h=typeof cf=="function"?cf(f):f;else try{h=_W(c,f)}catch(K){return n(K)}let l=vt.isBuffer(t.payload)?new Ym(t.payload):t.payload,d=rN(l.value()),m=parseInt(d.i,10);if(m&&m<4096){n(new Pi(`Server returned an invalid iteration count ${m}`),!1);return}let S=d.s,E=d.r;if(E.startsWith("nonce")){n(new Pi(`Server returned an invalid nonce: ${E}`),!1);return}let O=`c=biws,r=${E}`,T=AW(h,vt.from(S,"base64"),m,e),R=af(e,T,"Client Key"),_=af(e,T,"Server Key"),N=NW(e,R),P=[iN(c,a),l.value().toString("base64"),O].join(","),q=af(e,N,P),H=`p=${TW(R,q)}`,ue=[O,H].join(","),j=af(e,_,P),te={saslContinue:1,conversationId:t.conversationId,payload:new Ym(vt.from(ue))};i.command(`${u}.$cmd`,te,(K,W)=>{let z=aN(K,W);if(z)return n(z);let Y=W.result,fe=rN(Y.payload.value());if(!IW(vt.from(fe.v,"base64"),j)){n(new Pi("Server returned an invalid signature"));return}if(!Y||Y.done!==!1)return n(z,Y);let ee={saslContinue:1,conversationId:Y.conversationId,payload:vt.alloc(0)};i.command(`${u}.$cmd`,ee,n)})}o(oN,"continueScramConversation");function rN(e){let t={},r=e.split(",");for(let n=0;n=200&&bW(),uf[i]=s,Gm+=1,s}o(AW,"HI");function IW(e,t){if(e.length!==t.length)return!1;if(typeof Li.timingSafeEqual=="function")return Li.timingSafeEqual(e,t);let r=0;for(let n=0;n{"use strict";function BW(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}o(BW,"getDefaultAuthMechanism");var lf=class lf{constructor(t){t=t||{},this.username=t.username,this.password=t.password,this.source=t.source||t.db,this.mechanism=t.mechanism||"default",this.mechanismProperties=t.mechanismProperties||{},/MONGODB-AWS/i.test(this.mechanism)&&(!this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),!this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),this.mechanismProperties.AWS_SESSION_TOKEN==null&&process.env.AWS_SESSION_TOKEN!=null&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(t){return this.mechanism===t.mechanism&&this.username===t.username&&this.password===t.password&&this.source===t.source}resolveAuthMechanism(t){return/DEFAULT/i.test(this.mechanism)?new lf({username:this.username,password:this.password,source:this.source,mechanism:BW(t),mechanismProperties:this.mechanismProperties}):this}};o(lf,"MongoCredentials");var ey=lf;cN.exports={MongoCredentials:ey}});var hN=w((kne,lN)=>{"use strict";var RW=kn().AuthProvider,MW=ty().MongoCredentials,ji=V().MongoError,xW=require("crypto"),qW=require("http"),DW=re().maxWireVersion,PW=require("url"),ny;try{ny=require("aws4")}catch{}var LW=110,jW="http://169.254.170.2",ry="http://169.254.169.254",fN="/latest/meta-data/iam/security-credentials",sy=class sy extends RW{auth(t,r){let n=t.connection,i=t.credentials;if(DW(n)<9){r(new ji("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));return}if(ny==null){r(new ji("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));return}if(i.username==null){UW(i,(l,d)=>{if(l)return r(l);t.credentials=d,this.auth(t,r)});return}let s=i.source,a=this.bson,u=i.username,c=i.password,f=i.mechanismProperties.AWS_SESSION_TOKEN,h=u&&c&&f?{accessKeyId:u,secretAccessKey:c,sessionToken:f}:u&&c?{accessKeyId:u,secretAccessKey:c}:void 0;xW.randomBytes(32,(l,d)=>{if(l){r(l);return}let m={saslStart:1,mechanism:"MONGODB-AWS",payload:a.serialize({r:d,p:LW})};n.command(`${s}.$cmd`,m,(S,E)=>{if(S)return r(S);let O=E.result,T=a.deserialize(O.payload.buffer),R=T.h,_=T.s.buffer;if(_.length!==64){r(new ji(`Invalid server nonce length ${_.length}, expected 64`));return}if(_.compare(d,0,d.length,0,d.length)!==0){r(new ji("Server nonce does not begin with client nonce"));return}if(R.length<1||R.length>255||R.indexOf("..")!==-1){r(new ji(`Server returned an invalid host: "${R}"`));return}let N="Action=GetCallerIdentity&Version=2011-06-15",P=ny.sign({method:"POST",host:R,region:WW(T.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":N.length,"X-MongoDB-Server-Nonce":_.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:N},h),q=P.headers.Authorization,H=P.headers["X-Amz-Date"],ue={a:q,d:H};f&&(ue.t=f);let j={saslContinue:1,conversationId:1,payload:a.serialize(ue)};n.command(`${s}.$cmd`,j,te=>{if(te)return r(te);r()})})})}};o(sy,"MongoDBAWS");var iy=sy;function UW(e,t){function r(n){if(n.AccessKeyId==null||n.SecretAccessKey==null||n.Token==null){t(new ji("Could not obtain temporary MONGODB-AWS credentials"));return}t(void 0,new MW({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}}))}if(o(r,"done"),process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI){hf(`${jW}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,void 0,(n,i)=>{if(n)return t(n);r(i)});return}hf(`${ry}/latest/api/token`,{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(n,i)=>{if(n)return t(n);hf(`${ry}/${fN}`,{json:!1,headers:{"X-aws-ec2-metadata-token":i}},(s,a)=>{if(s)return t(s);hf(`${ry}/${fN}/${a}`,{headers:{"X-aws-ec2-metadata-token":i}},(u,c)=>{if(u)return t(u);r(c)})})})}o(UW,"makeTempCredentials");function WW(e){let t=e.split(".");return t.length===1||t[1]==="amazonaws"?"us-east-1":t[1]}o(WW,"deriveRegion");function hf(e,t,r){t=Object.assign({method:"GET",timeout:1e4,json:!0},PW.parse(e),t);let n=qW.request(t,i=>{i.setEncoding("utf8");let s="";i.on("data",a=>s+=a),i.on("end",()=>{if(t.json===!1){r(void 0,s);return}try{let a=JSON.parse(s);r(void 0,a)}catch{r(new ji(`Invalid JSON response: "${s}"`))}})});n.on("error",i=>r(i)),n.end()}o(hf,"request");lN.exports=iy});var oy=w((Gne,dN)=>{"use strict";var FW=Dm(),$W=jm(),zW=Fm(),VW=Hm(),HW=xa().ScramSHA1,kW=xa().ScramSHA256,YW=hN();function GW(e){return{"mongodb-aws":new YW(e),mongocr:new FW(e),x509:new $W(e),plain:new zW(e),gssapi:new VW(e),"scram-sha-1":new HW(e),"scram-sha-256":new kW(e)}}o(GW,"defaultAuthProviders");dN.exports={defaultAuthProviders:GW}});var mf=w((Xne,wN)=>{"use strict";var yN=require("net"),KW=require("tls"),gN=Sm(),qa=V().MongoError,df=V().MongoNetworkError,XW=V().MongoNetworkTimeoutError,JW=oy().defaultAuthProviders,ZW=kn().AuthContext,pf=nm(),QW=re().makeClientMetadata,pN=pf.MAX_SUPPORTED_WIRE_VERSION,e3=pf.MAX_SUPPORTED_SERVER_VERSION,mN=pf.MIN_SUPPORTED_WIRE_VERSION,t3=pf.MIN_SUPPORTED_SERVER_VERSION,Ps;function r3(e,t,r){typeof t=="function"&&(r=t,t=void 0);let n=e&&e.connectionType?e.connectionType:gN;Ps==null&&(Ps=JW(e.bson));let i=e.family!==void 0?e.family:0;c3(i,e,t,(s,a)=>{if(s){r(s,a);return}s3(new n(a,e),e,r)})}o(r3,"connect");function n3(e){return!(e instanceof gN)}o(n3,"isModernConnectionType");function i3(e,t){let r=e&&typeof e.maxWireVersion=="number"&&e.maxWireVersion>=mN,n=e&&typeof e.minWireVersion=="number"&&e.minWireVersion<=pN;if(r){if(n)return null;let s=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${pN} (MongoDB ${e3})`;return new qa(s)}let i=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${mN} (MongoDB ${t3})`;return new qa(i)}o(i3,"checkSupportedServer");function s3(e,t,r){let n=o(function(a,u){a&&e&&e.destroy(),r(a,u)},"callback"),i=t.credentials;if(i&&!i.mechanism.match(/DEFAULT/i)&&!Ps[i.mechanism]){n(new qa(`authMechanism '${i.mechanism}' not supported`));return}let s=new ZW(e,i,t);o3(s,(a,u)=>{if(a)return n(a);let c=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(c.socketTimeout=t.connectTimeoutMS||t.connectionTimeout),u.helloOk=!!t.useUnifiedTopology;let f=new Date().getTime();e.command("admin.$cmd",u,c,(h,l)=>{if(h){n(h);return}let d=l.result;if(d.ok===0){n(new qa(d));return}"isWritablePrimary"in d&&(d.ismaster=d.isWritablePrimary),t.useUnifiedTopology&&d.helloOk&&(e.helloOk=!0);let m=i3(d,t);if(m){n(m);return}if(!n3(e)&&d.compression){let S=u.compression.filter(E=>d.compression.indexOf(E)!==-1);S.length&&(e.agreedCompressor=S[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=d,e.lastIsMasterMS=new Date().getTime()-f,!d.arbiterOnly&&i){Object.assign(s,{response:d});let S=i.resolveAuthMechanism(d);Ps[S.mechanism].auth(s,O=>{if(O)return n(O);n(void 0,e)});return}n(void 0,e)})})}o(s3,"performInitialHandshake");function o3(e,t){let r=e.options,n=e.connection.serverApi,i=r.compression&&r.compression.compressors?r.compression.compressors:[],s={[n?"hello":"ismaster"]:!0,client:r.metadata||QW(r),compression:i},a=e.credentials;if(a){if(a.mechanism.match(/DEFAULT/i)&&a.username){Object.assign(s,{saslSupportedMechs:`${a.source}.${a.username}`}),Ps["scram-sha-256"].prepare(s,e,t);return}let u=Ps[a.mechanism];if(u==null)return t(new qa(`No AuthProvider for ${a.mechanism} defined.`));u.prepare(s,e,t);return}t(void 0,s)}o(o3,"prepareHandshakeDocument");var a3=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function SN(e,t){let r=typeof t.host=="string"?t.host:"localhost";return r.indexOf("/")!==-1?{path:r}:{family:e,host:r,port:typeof t.port=="number"?t.port:27017,rejectUnauthorized:!1}}o(SN,"parseConnectOptions");function u3(e,t){let r=SN(e,t);for(let n in t)t[n]!=null&&a3.indexOf(n)!==-1&&(r[n]=t[n]);return t.checkServerIdentity===!1?r.checkServerIdentity=function(){}:typeof t.checkServerIdentity=="function"&&(r.checkServerIdentity=t.checkServerIdentity),r.servername==null&&!yN.isIP(r.host)&&(r.servername=r.host),r}o(u3,"parseSslOptions");var ay=new Set(["error","close","timeout","parseError"]);function c3(e,t,r,n){let i=typeof t.ssl=="boolean"?t.ssl:!1,s=typeof t.keepAlive=="boolean"?t.keepAlive:!0,a=typeof t.keepAliveInitialDelay=="number"?t.keepAliveInitialDelay:12e4,u=typeof t.noDelay=="boolean"?t.noDelay:!0,c=typeof t.connectionTimeout=="number"?t.connectionTimeout:typeof t.connectTimeoutMS=="number"?t.connectTimeoutMS:3e4,f=typeof t.socketTimeoutMS=="number"?t.socketTimeoutMS:typeof t.socketTimeout=="number"?t.socketTimeout:0,h=typeof t.rejectUnauthorized=="boolean"?t.rejectUnauthorized:!0;a>f&&(a=Math.round(f/2));let l,d=o(function(T,R){T&&l&&l.destroy(),n(T,R)},"callback");try{i?(l=KW.connect(u3(e,t)),typeof l.disableRenegotiation=="function"&&l.disableRenegotiation()):l=yN.createConnection(SN(e,t))}catch(T){return d(T)}l.setKeepAlive(s,a),l.setTimeout(c),l.setNoDelay(u);let m=i?"secureConnect":"connect",S;function E(T){return R=>{ay.forEach(_=>l.removeAllListeners(_)),S&&r.removeListener("cancel",S),l.removeListener(m,O),d(f3(T,R))}}o(E,"errorHandler");function O(){if(ay.forEach(T=>l.removeAllListeners(T)),S&&r.removeListener("cancel",S),l.authorizationError&&h)return d(l.authorizationError);l.setTimeout(f),d(null,l)}o(O,"connectHandler"),ay.forEach(T=>l.once(T,E(T))),r&&(S=E("cancel"),r.once("cancel",S)),l.once(m,O)}o(c3,"makeConnection");function f3(e,t){switch(e){case"error":return new df(t);case"timeout":return new XW("connection timed out");case"close":return new df("connection closed");case"cancel":return new df("connection establishment was cancelled");default:return new df("unknown network error")}}o(f3,"connectionFailureError");wN.exports=r3});var Ui=w((Zne,ON)=>{"use strict";var Ls=class Ls{constructor(t){t!=null&&(this.level=t)}static fromOptions(t){if(t!=null){if(t.readConcern)return t.readConcern instanceof Ls?t.readConcern:new Ls(t.readConcern.level);if(t.level)return new Ls(t.level)}}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}};o(Ls,"ReadConcern");var uy=Ls;ON.exports=uy});var js=w((eie,_N)=>{"use strict";var vN=V().MongoError,l3=wt(),h3=Ui(),d3=an(),Gn,EN;(()=>{let e="NO_TRANSACTION",t="STARTING_TRANSACTION",r="TRANSACTION_IN_PROGRESS",n="TRANSACTION_COMMITTED",i="TRANSACTION_COMMITTED_EMPTY",s="TRANSACTION_ABORTED";Gn={NO_TRANSACTION:e,STARTING_TRANSACTION:t,TRANSACTION_IN_PROGRESS:r,TRANSACTION_COMMITTED:n,TRANSACTION_COMMITTED_EMPTY:i,TRANSACTION_ABORTED:s},EN={[e]:[e,t],[t]:[r,n,i,s],[r]:[r,n,s],[n]:[n,i,t,e],[s]:[t,e],[i]:[i,e]}})();var fy=class fy{constructor(t){t=t||{},this.state=Gn.NO_TRANSACTION,this.options={};let r=d3.fromOptions(t);if(r){if(r.w<=0)throw new vN("Transactions do not support unacknowledged write concern");this.options.writeConcern=r}t.readConcern&&(this.options.readConcern=h3.fromOptions(t)),t.readPreference&&(this.options.readPreference=l3.fromOptions(t)),t.maxCommitTimeMS&&(this.options.maxTimeMS=t.maxCommitTimeMS),this._pinnedServer=void 0,this._recoveryToken=void 0}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return[Gn.STARTING_TRANSACTION,Gn.TRANSACTION_IN_PROGRESS].indexOf(this.state)!==-1}transition(t){let r=EN[this.state];if(r&&r.indexOf(t)!==-1){this.state=t,(this.state===Gn.NO_TRANSACTION||this.state===Gn.STARTING_TRANSACTION||this.state===Gn.TRANSACTION_ABORTED)&&this.unpinServer();return}throw new vN(`Attempted illegal state transition from [${this.state}] to [${t}]`)}pinServer(t){this.isActive&&(this._pinnedServer=t)}unpinServer(){this._pinnedServer=void 0}};o(fy,"Transaction");var cy=fy;function p3(e){return!!(e.commitTransaction||e.abortTransaction)}o(p3,"isTransactionCommand");_N.exports={TxnState:Gn,Transaction:cy,isTransactionCommand:p3}});var rt=w((rie,BN)=>{"use strict";var m3=Ii().MONGODB_ERROR_CODES,y3=wt(),yf=bt().TopologyType,NN=V().MongoError,g3=V().isRetryableWriteError,S3=re().maxWireVersion,w3=V().MongoNetworkError,O3=m3.IllegalOperation;function ly(e,t,r){e.listeners(t).length>0&&e.emit(t,r)}o(ly,"emitSDAMEvent");function v3(e){return!e.compression||!e.compression.compressors?[]:(e.compression.compressors.forEach(function(t){if(t!=="snappy"&&t!=="zlib")throw new Error("compressors must be at least one of snappy or zlib")}),e.compression.compressors)}o(v3,"createCompressionInfo");function E3(e){return JSON.parse(JSON.stringify(e))}o(E3,"clone");var _3=o(function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},"getPreviousDescription"),bN=o(function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:_3(e),newDescription:t}),e.s.serverDescription=t)},"emitServerDescriptionChanged"),T3=o(function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},"getPreviousTopologyDescription"),N3=o(function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:T3(e),newDescription:t}),e.s.serverDescription=t)},"emitTopologyDescriptionChanged"),b3=o(function(e,t,r){var n=gf(e,t),i=gf(e,r);return i!==n},"changedIsMaster"),gf=o(function(e,t){return t||(t=e.ismaster),t?t.ismaster&&t.msg==="isdbgrid"?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},"getTopologyType"),CN=o(function(e){return function(t){if(e.s.state!=="destroyed"){var r=new Date().getTime();ly(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},function(n,i){if(n)ly(e,"serverHeartbeatFailed",{durationMS:s,failure:n,connectionId:e.name});else{e.emit("ismaster",i,e);var s=new Date().getTime()-r;ly(e,"serverHeartbeatSucceeded",{durationMS:s,reply:i.result,connectionId:e.name}),b3(e,e.s.ismaster,i.result)&&bN(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?gf(e):"Standalone"}),e.s.ismaster=i.result,e.s.isMasterLatencyMS=s}if(typeof t=="function")return t(n,i);e.s.inquireServerStateTimeout=setTimeout(CN(e),e.s.haInterval)})}}},"inquireServerState"),C3=o(function(e){var t={};for(var r in e)t[r]=e[r];return t},"cloneOptions");function A3(e,t){var r=!1;this.start=function(){return this.isRunning()||(r=setInterval(e,t)),this},this.stop=function(){return clearInterval(r),r=!1,this},this.isRunning=function(){return r!==!1}}o(A3,"Interval");function I3(e,t){var r=!1,n=o(()=>{r&&(clearTimeout(r),r=!1,e())},"func");this.start=function(){return this.isRunning()||(r=setTimeout(n,t)),this},this.stop=function(){return clearTimeout(r),r=!1,this},this.isRunning=function(){return r!==!1}}o(I3,"Timeout");function B3(e,t){var r={servers:[]};e||(e={servers:[]});for(var n=0;n{typeof t=="function"&&t()})}};function AN(e){return e.description?e.description.type:e.type==="mongos"?yf.Sharded:e.type==="replset"?yf.ReplicaSetWithPrimary:yf.Single}o(AN,"topologyType");var x3=6,IN=o(function(e){return!(e.lastIsMaster().maxWireVersion{"use strict";var P3=mt().retrieveBSON,L3=require("events"),DN=P3(),RN=DN.Binary,j3=re().uuidV4,Dr=V().MongoError,U3=V().isRetryableError,W3=V().isRetryableEndTransactionError,F3=V().MongoNetworkError,$3=V().MongoWriteConcernError,MN=js().Transaction,nt=js().TxnState,z3=re().isPromiseLike,V3=wt(),hy=b().maybePromise,H3=js().isTransactionCommand,k3=rt().resolveClusterTime,Y3=We().isSharded,G3=re().maxWireVersion,py=b().now,PN=b().calculateDurationInMs,K3=8;function LN(e,t){if(e.serverSession==null){let r=new Dr("Cannot use a session that has ended");if(typeof t=="function")return t(r,null),!1;throw r}return!0}o(LN,"assertAlive");var Da=Symbol("serverSession"),Of=class Of extends L3{constructor(t,r,n,i){if(super(),t==null)throw new Error("ClientSession requires a topology");if(r==null||!(r instanceof wf))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},i=i||{},this.topology=t,this.sessionPool=r,this.hasEnded=!1,this.clientOptions=i,this[Da]=void 0,this.supports={causalConsistency:typeof n.causalConsistency<"u"?n.causalConsistency:!0},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new MN}get id(){return this.serverSession.id}get serverSession(){return this[Da]==null&&(this[Da]=this.sessionPool.acquire()),this[Da]}endSession(t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=this;return hy(this,r,i=>{if(n.hasEnded)return i();function s(){n.sessionPool.release(n.serverSession),n[Da]=void 0,n.hasEnded=!0,n.emit("ended",n),i()}if(o(s,"completeEndSession"),n.serverSession&&n.inTransaction()){n.abortTransaction(a=>{if(a)return i(a);s()});return}s()})}advanceOperationTime(t){if(this.operationTime==null){this.operationTime=t;return}t.greaterThan(this.operationTime)&&(this.operationTime=t)}equals(t){return t instanceof Of?this.id.id.buffer.equals(t.id.id.buffer):!1}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(t){if(LN(this),this.inTransaction())throw new Dr("Transaction already in progress");let r=G3(this.topology);if(Y3(this.topology)&&r!=null&&rqN(this,"commitTransaction",r))}abortTransaction(t){return hy(this,t,r=>qN(this,"abortTransaction",r))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(t,r){let n=py();return my(this,n,t,r)}};o(Of,"ClientSession");var dy=Of,jN=12e4,X3=100,J3=79,xN=50,Z3=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function UN(e,t){return PN(e){if(i instanceof Dr&&UN(t,jN)&&!vf(i)){if(i.hasErrorLabel("UnknownTransactionCommitResult"))return WN(e,t,r,n);if(i.hasErrorLabel("TransientTransactionError"))return my(e,t,r,n)}throw i})}o(WN,"attemptTransactionCommit");var e6=new Set([nt.NO_TRANSACTION,nt.TRANSACTION_COMMITTED,nt.TRANSACTION_ABORTED]);function t6(e){return e6.has(e.transaction.state)}o(t6,"userExplicitlyEndedTransaction");function my(e,t,r,n){e.startTransaction(n);let i;try{i=r(e)}catch(s){i=Promise.reject(s)}if(!z3(i))throw e.abortTransaction(),new TypeError("Function provided to `withTransaction` must return a Promise");return i.then(()=>{if(!t6(e))return WN(e,t,r,n)}).catch(s=>{function a(u){if(u instanceof Dr&&u.hasErrorLabel("TransientTransactionError")&&UN(t,jN))return my(e,t,r,n);throw vf(u)&&u.addErrorLabel("UnknownTransactionCommitResult"),u}return o(a,"maybeRetryOrThrow"),e.transaction.isActive?e.abortTransaction().then(()=>a(s)):a(s)})}o(my,"attemptTransaction");function qN(e,t,r){if(!LN(e,r))return;let n=e.transaction.state;if(n===nt.NO_TRANSACTION){r(new Dr("No transaction started"));return}if(t==="commitTransaction"){if(n===nt.STARTING_TRANSACTION||n===nt.TRANSACTION_COMMITTED_EMPTY){e.transaction.transition(nt.TRANSACTION_COMMITTED_EMPTY),r(null,null);return}if(n===nt.TRANSACTION_ABORTED){r(new Dr("Cannot call commitTransaction after calling abortTransaction"));return}}else{if(n===nt.STARTING_TRANSACTION){e.transaction.transition(nt.TRANSACTION_ABORTED),r(null,null);return}if(n===nt.TRANSACTION_ABORTED){r(new Dr("Cannot call abortTransaction twice"));return}if(n===nt.TRANSACTION_COMMITTED||n===nt.TRANSACTION_COMMITTED_EMPTY){r(new Dr("Cannot call abortTransaction after calling commitTransaction"));return}}let i={[t]:1},s;e.transaction.options.writeConcern?s=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(s={w:e.clientOptions.w}),n===nt.TRANSACTION_COMMITTED&&(s=Object.assign({wtimeout:1e4},s,{w:"majority"})),s&&Object.assign(i,{writeConcern:s}),t==="commitTransaction"&&e.transaction.options.maxTimeMS&&Object.assign(i,{maxTimeMS:e.transaction.options.maxTimeMS});function a(c,f){t==="commitTransaction"?(e.transaction.transition(nt.TRANSACTION_COMMITTED),c&&(c instanceof F3||c instanceof $3||U3(c)||vf(c)?Q3(c)&&(c.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer()):c.hasErrorLabel("TransientTransactionError")&&e.transaction.unpinServer())):e.transaction.transition(nt.TRANSACTION_ABORTED),r(c,f)}o(a,"commandHandler");function u(c){return t==="commitTransaction"?c:null}o(u,"transactionError"),e.transaction.recoveryToken&&r6(e)&&(i.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",i,{session:e},(c,f)=>{if(c&&W3(c))return i.commitTransaction&&(e.transaction.unpinServer(),i.writeConcern=Object.assign({wtimeout:1e4},i.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",i,{session:e},(h,l)=>a(u(h),l));a(u(c),f)})}o(qN,"endTransaction");function r6(e){return!!e.topology.s.options.useRecoveryToken}o(r6,"supportsRecoveryToken");var yy=class yy{constructor(){this.id={id:new RN(j3(),RN.SUBTYPE_UUID)},this.lastUse=py(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(t){return Math.round(PN(this.lastUse)%864e5%36e5/6e4)>t-1}};o(yy,"ServerSession");var Sf=yy,gy=class gy{constructor(t){if(t==null)throw new Error("ServerSessionPool requires a topology");this.topology=t,this.sessions=[]}endAllPooledSessions(t){if(this.sessions.length){this.topology.endSessions(this.sessions.map(r=>r.id),()=>{this.sessions=[],typeof t=="function"&&t()});return}typeof t=="function"&&t()}acquire(){let t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){let r=this.sessions.shift();if(!r.hasTimedOut(t))return r}return new Sf}release(t){let r=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length&&this.sessions[this.sessions.length-1].hasTimedOut(r);)this.sessions.pop();if(!t.hasTimedOut(r)){if(t.isDirty)return;this.sessions.unshift(t)}}};o(gy,"ServerSessionPool");var wf=gy;function FN(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch||e.mapReduce&&t&&t.out&&(t.out.inline===1||t.out==="inline"))}o(FN,"commandSupportsReadConcern");function n6(e,t,r){if(e.hasEnded)return new Dr("Cannot use a session that has ended");if(r&&r.writeConcern&&r.writeConcern.w===0)return;let n=e.serverSession;n.lastUse=py(),t.lsid=n.id;let i=e.inTransaction()||H3(t),s=r.willRetryWrite,a=FN(t,r);if(n.txnNumber&&(s||i)&&(t.txnNumber=DN.Long.fromNumber(n.txnNumber)),!i){e.transaction.state!==nt.NO_TRANSACTION&&e.transaction.transition(nt.NO_TRANSACTION),e.supports.causalConsistency&&e.operationTime&&a&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}));return}if(r.readPreference&&!r.readPreference.equals(V3.primary))return new Dr(`Read preference in a transaction must be primary, not: ${r.readPreference.mode}`);if(t.autocommit=!1,e.transaction.state===nt.STARTING_TRANSACTION){e.transaction.transition(nt.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;let u=e.transaction.options.readConcern||e.clientOptions.readConcern;u&&(t.readConcern=u),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}}o(n6,"applySession");function i6(e,t){t.$clusterTime&&k3(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)}o(i6,"updateSessionFromResponse");$N.exports={ClientSession:dy,ServerSession:Sf,ServerSessionPool:wf,TxnState:nt,applySession:n6,updateSessionFromResponse:i6,commandSupportsReadConcern:FN}});var QN=w((oie,ZN)=>{"use strict";var s6=require("util").inherits,Oy=require("events").EventEmitter,gr=V().MongoError,o6=V().MongoTimeoutError,a6=V().MongoWriteConcernError,u6=yr(),c6=require("util").format,f6=xi().Msg,l6=tf(),Sy=We().MESSAGE_HEADER_SIZE,zN=We().COMPRESSION_DETAILS_SIZE,h6=We().opcodes,d6=un().compress,p6=un().compressorIDs,m6=un().uncompressibleCommands,Ef=Am(),wy=qr().Buffer,y6=mf(),g6=Kn().updateSessionFromResponse,kN=re().eachAsync,S6=re().makeStateMachine,w6=b().now,Jn="disconnected",Us="connecting",Pa="connected",Xn="draining",ar="destroying",Lt="destroyed",Ws=S6({[Jn]:[Us,Xn,Jn],[Us]:[Us,Pa,Xn,Jn],[Pa]:[Pa,Jn,Xn],[Xn]:[Xn,ar,Lt],[ar]:[ar,Lt],[Lt]:[Lt]}),YN=new Set(["error","close","timeout","parseError","connect","message"]),O6=0,at=o(function(e,t){if(Oy.call(this),this.topology=e,this.s={state:Jn,cancellationToken:new Oy},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=O6++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&(typeof t.bson.serialize!="function"||typeof t.bson.deserialize!="function"))throw new Error("must pass in valid bson parser");this.logger=u6("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;let r=this;this._messageHandler=v6(this),this._connectionCloseHandler=function(n){_f(r,"close",n,this)},this._connectionErrorHandler=function(n){_f(r,"error",n,this)},this._connectionTimeoutHandler=function(n){_f(r,"timeout",n,this)},this._connectionParseErrorHandler=function(n){_f(r,"parseError",n,this)}},"Pool");s6(at,Oy);Object.defineProperty(at.prototype,"size",{enumerable:!0,get:function(){return this.options.size}});Object.defineProperty(at.prototype,"minSize",{enumerable:!0,get:function(){return this.options.minSize}});Object.defineProperty(at.prototype,"connectionTimeout",{enumerable:!0,get:function(){return this.options.connectionTimeout}});Object.defineProperty(at.prototype,"socketTimeout",{enumerable:!0,get:function(){return this.options.socketTimeout}});Object.defineProperty(at.prototype,"state",{enumerable:!0,get:function(){return this.s.state}});function GN(e){e.inUseConnections=[],e.availableConnections=[],e.connectingConnections=0,e.executing=!1,e.numberOfConsecutiveTimeouts=0,e.connectionIndex=0,e.retriesLeft=e.options.reconnectTries,e.reconnectId=null}o(GN,"resetPoolState");function _f(e,t,r,n){if(n){if(n._connectionFailHandled)return;n._connectionFailHandled=!0,n.destroy(),vy(e,n),n.flush(r)}if(t==="timeout"&&(e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1,e.numberOfConsecutiveTimeouts>e.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);e.socketCount()===0&&(e.state!==Lt&&e.state!==ar&&e.state!==Xn&&e.options.reconnect&&Ws(e,Jn),t=t==="error"?"close":t,e.emit(t,r)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=r,e.reconnectId=setTimeout(KN(e),e.options.reconnectInterval)),JN(e){r==null&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),typeof t=="function"&&t(r,n)})}}o(KN,"attemptReconnect");function XN(e,t,r){var n=t.indexOf(e);n!==-1&&(t.splice(n,1),r.push(e))}o(XN,"moveConnectionBetween");function v6(e){return function(t,r){for(var n=null,i=0;i{if(t){if(typeof e=="function"){this.destroy(),e(t);return}this.state===Us&&this.emit("error",t),this.destroy();return}if(Ws(this,Pa),this.minSize)for(let n=0;n{for(let a of YN)i.removeAllListeners(a);i.on("error",()=>{}),i.destroy(r,s)},i=>{if(i){typeof n=="function"&&n(i,null);return}GN(e),e.queue=[],Ws(e,Lt),typeof n=="function"&&n(null,null)})}o(VN,"destroy");at.prototype.destroy=function(e,t){var r=this;if(typeof e=="function"&&(t=e,e=!1),this.state===Lt||r.state===ar){typeof t=="function"&&t(null,null);return}if(Ws(this,Xn),e){for(var n=r.availableConnections.concat(r.inUseConnections);r.queue.length>0;){var i=r.queue.shift();typeof i.cb=="function"&&i.cb(new gr("Pool was force destroyed"))}return VN(r,n,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId);function s(){if(r.state===Lt||r.state===ar){typeof t=="function"&&t();return}if(Tf(r.queue),r.queue.length===0){for(var a=r.availableConnections.concat(r.inUseConnections),u=0;u0)return setTimeout(s,1);VN(r,a,{force:!1},t)}else Fs(r)(),setTimeout(s,1)}o(s,"checkStatus"),s()};at.prototype.reset=function(e){if(this.s.state!==Pa){typeof e=="function"&&e(new gr("pool is not connected, reset aborted"));return}this.s.cancellationToken.emit("cancel");let t=this.availableConnections.concat(this.inUseConnections);kN(t,(r,n)=>{for(let i of YN)r.removeAllListeners(i);r.destroy({force:!0},n)},r=>{if(r&&typeof e=="function"){e(r,null);return}GN(this),Zn(this,()=>{typeof e=="function"&&e(null,null)})})};function E6(e,t,r){let n=t.toBin();if(!!!e.options.agreedCompressor||!_6(t))return r(null,n);let s=wy.concat(n),a=s.slice(Sy),u=s.readInt32LE(12);d6(e,a,function(c,f){if(c)return r(c,null);let h=wy.alloc(Sy);h.writeInt32LE(Sy+zN+f.length,0),h.writeInt32LE(t.requestId,4),h.writeInt32LE(0,8),h.writeInt32LE(h6.OP_COMPRESSED,12);let l=wy.alloc(zN);return l.writeInt32LE(u,0),l.writeInt32LE(a.length,4),l.writeUInt8(p6[e.options.agreedCompressor],8),r(null,[h,l,f])})}o(E6,"serializeCommand");at.prototype.write=function(e,t,r){var n=this;if(typeof t=="function"&&(r=t),t=t||{},typeof r!="function"&&!t.noResponse)throw new gr("write method must provide a callback");if(this.state===Lt||this.state===ar){r(new gr("pool destroyed"));return}if(this.state===Xn){r(new gr("pool is draining, new operations prohibited"));return}if(this.options.domainsEnabled&&process.domain&&typeof r=="function"){var i=r;r=process.domain.bind(function(){for(var a=new Array(arguments.length),u=0;u{a?n.emit("commandFailed",new Ef.CommandFailedEvent(this,e,a,s.started)):u&&u.result&&(u.result.ok===0||u.result.$err)?n.emit("commandFailed",new Ef.CommandFailedEvent(this,e,u.result,s.started)):n.emit("commandSucceeded",new Ef.CommandSucceededEvent(this,e,u,s.started)),typeof r=="function"&&r(a,u)}),E6(n,e,(a,u)=>{if(a)throw a;s.buffer=u,t.monitoring?n.queue.unshift(s):n.queue.push(s),n.executing||process.nextTick(function(){Fs(n)()})})};function _6(e){let t=e instanceof f6?e.command:e.query,r=Object.keys(t)[0];return!m6.has(r)}o(_6,"canCompress");function HN(e,t){for(var r=0;r{if(e.connectingConnections--,r){if(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(r)}]`),!e.reconnectId&&e.options.reconnect){if(e.state===Us&&e.options.legacyCompatMode){t(r);return}e.reconnectError=r,e.reconnectId=setTimeout(KN(e,t),e.options.reconnectInterval);return}typeof t=="function"&&t(r);return}if(e.state===Lt||e.state===ar){typeof t=="function"&&t(new gr("Pool was destroyed after connection creation")),n.destroy();return}n.on("error",e._connectionErrorHandler),n.on("close",e._connectionCloseHandler),n.on("timeout",e._connectionTimeoutHandler),n.on("parseError",e._connectionParseErrorHandler),n.on("message",e._messageHandler),e.availableConnections.push(n),typeof t=="function"&&t(null,n),Fs(e)()})}o(Zn,"createConnection");function Tf(e){for(var t=0;t0){e.executing=!1;return}for(;;){let a=JN(e);if(e.availableConnections.length===0){Tf(e.queue),a0&&Zn(e);break}if(e.queue.length===0)break;var t=null;let u=e.availableConnections.filter(c=>c.workItems.length===0);if(u.length===0?t=e.availableConnections[e.connectionIndex++%e.availableConnections.length]:t=u[e.connectionIndex++%u.length],!t.isConnected()){vy(e,t),Tf(e.queue);break}var r=e.queue.shift();if(r.monitoring){var n=!1;for(let c=0;c0&&Zn(e),setTimeout(()=>Fs(e)(),10);break}}if(a0){e.queue.unshift(r),Zn(e);break}var i=r.buffer;r.monitoring&&XN(t,e.availableConnections,e.inUseConnections),r.noResponse||t.workItems.push(r),!r.immediateRelease&&typeof r.socketTimeout=="number"&&t.setSocketTimeout(r.socketTimeout);var s=!0;if(Array.isArray(i))for(let c=0;c{"use strict";var T6=sr().Query,N6=xi().Msg,Ey=V().MongoError,b6=We().getReadPreference,C6=We().isSharded,A6=We().databaseNamespace,I6=js().isTransactionCommand,B6=Kn().applySession,R6=V().MongoNetworkError,eb=re().maxWireVersion;function M6(e){return eb(e)&&e.autoEncrypter}o(M6,"isClientEncryptionEnabled");function x6(e,t,r,n,i){if(typeof n=="function"&&(i=n,n={}),n=n||{},r==null)return i(new Ey(`command ${JSON.stringify(r)} does not return a cursor`));if(!M6(e)){tb(e,t,r,n,i);return}let s=eb(e);if(typeof s!="number"||s<8){i(new Ey("Auto-encryption requires a minimum MongoDB version of 4.2"));return}P6(e,t,r,n,i)}o(x6,"command");function tb(e,t,r,n,i){let s=e.s.bson,a=e.s.pool,u=b6(r,n),c=D6(e),f=n.session,h=e.clusterTime,l=h,d=Object.assign({},r),m=n.serverApi;if(m&&(d.apiVersion=m.version||m,m.strict!=null&&(d.apiStrict=m.strict),m.deprecationErrors!=null&&(d.apiDeprecationErrors=m.deprecationErrors)),q6(e)&&f){let _=f.clusterTime;h&&h.clusterTime&&_&&_.clusterTime&&_.clusterTime.greaterThan(h.clusterTime)&&(l=_),!f.transaction.isActive&&f.transaction.isPinned&&!d.startTransaction&&!d.commitTransaction&&f.transaction.unpinServer();let N=B6(f,d,n);if(N)return i(N)}l&&(d.$clusterTime=l),C6(e)&&!c&&u&&u.mode!=="primary"&&(d={$query:d,$readPreference:u.toJSON()});let S=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},n);S.slaveOk=u.slaveOk();let E=`${A6(t)}.$cmd`,O=c?new N6(s,E,d,S):new T6(s,E,d,S),R=f&&(f.inTransaction()||I6(d))?function(_){return _&&_ instanceof R6&&!_.hasErrorLabel("TransientTransactionError")&&_.addErrorLabel("TransientTransactionError"),!r.commitTransaction&&_&&_ instanceof Ey&&_.hasErrorLabel("TransientTransactionError")&&f.transaction.unpinServer(),i.apply(null,arguments)}:i;try{a.write(O,S,R)}catch(_){R(_)}}o(tb,"_command");function q6(e){return e==null?!1:e.description?e.description.maxWireVersion>=6:e.ismaster==null?!1:e.ismaster.maxWireVersion>=6}o(q6,"hasSessionSupport");function D6(e){let t=e.ismaster?e.ismaster:e.description;return t==null?!1:t.maxWireVersion>=6&&t.__nodejs_mock_server__==null}o(D6,"supportsOpMsg");function P6(e,t,r,n,i){let s=e.autoEncrypter;function a(u,c){if(u||c==null){i(u,c);return}s.decrypt(c.result,n,(f,h)=>{if(f){i(f,null);return}c.result=h,c.message.documents=[h],i(null,c)})}o(a,"commandResponseHandler"),s.encrypt(t,r,n,(u,c)=>{if(u){i(u,null);return}tb(e,t,c,n,a)})}o(P6,"_cryptCommand");rb.exports=x6});var La=w((fie,nb)=>{"use strict";var L6=V().MongoError,Nf=class Nf{constructor(t){typeof t=="boolean"?this.verbosity=t?"allPlansExecution":"queryPlanner":this.verbosity=t}static fromOptions(t){if(t==null||t.explain===void 0)return;let r=t.explain;if(typeof r=="boolean"||typeof r=="string")return new Nf(t.explain);throw new L6("explain must be a string or a boolean")}};o(Nf,"Explain");var _y=Nf;nb.exports={Explain:_y}});var sb=w((hie,ib)=>{"use strict";var j6=V().MongoError,U6=We().collectionNamespace,W6=$s(),F6=b().decorateWithExplain,$6=La().Explain;function z6(e,t,r,n,i,s,a){if(i.length===0)throw new j6(`${t} must contain at least one document`);typeof s=="function"&&(a=s,s={}),s=s||{};let u=typeof s.ordered=="boolean"?s.ordered:!0,c=s.writeConcern,f={};if(f[t]=U6(n),f[r]=i,f.ordered=u,c&&Object.keys(c).length>0&&(f.writeConcern=c),s.collation)for(let d=0;d{"use strict";var V6=sr().KillCursor,H6=V().MongoError,k6=V().MongoNetworkError,Y6=We().collectionNamespace,G6=re().maxWireVersion,K6=re().emitWarning,X6=$s();function J6(e,t,r,n,i){typeof n=="function"&&(i=n,n={}),i=typeof i=="function"?i:()=>{};let s=r.cursorId;if(G6(e)<4){let c=e.s.bson,f=e.s.pool,h=new V6(c,t,[s]),l={immediateRelease:!0,noResponse:!0};if(typeof r.session=="object"&&(l.session=r.session),f&&f.isConnected())try{f.write(h,l,i)}catch(d){typeof i=="function"?i(d,null):K6(d)}return}let a={killCursors:Y6(t),cursors:[s]},u=n||{};typeof r.session=="object"&&(u.session=r.session),X6(e,t,a,u,(c,f)=>{if(c)return i(c);let h=f.message;if(h.cursorNotFound)return i(new k6("cursor killed or timed out"),null);if(!Array.isArray(h.documents)||h.documents.length===0)return i(new H6(`invalid killCursors result returned for cursor id ${s}`));i(null,h.documents[0])})}o(J6,"killCursors");ob.exports=J6});var cb=w((yie,ub)=>{"use strict";var Z6=sr().GetMore,Q6=mt().retrieveBSON,eF=V().MongoError,tF=V().MongoNetworkError,rF=Q6(),bf=rF.Long,nF=We().collectionNamespace,iF=re().maxWireVersion,sF=We().applyCommonQueryOptions,oF=$s();function aF(e,t,r,n,i,s){i=i||{};let a=iF(e);function u(l,d){if(l)return s(l);let m=d.message;if(m.cursorNotFound)return s(new tF("cursor killed or timed out"),null);if(a<4){let E=typeof m.cursorId=="number"?bf.fromNumber(m.cursorId):m.cursorId;r.documents=m.documents,r.cursorId=E,s(null,null,m.connection);return}if(m.documents[0].ok===0)return s(new eF(m.documents[0]));let S=typeof m.documents[0].cursor.id=="number"?bf.fromNumber(m.documents[0].cursor.id):m.documents[0].cursor.id;r.documents=m.documents[0].cursor.nextBatch,r.cursorId=S,s(null,m.documents[0],m.connection)}if(o(u,"queryCallback"),a<4){let l=e.s.bson,d=new Z6(l,t,r.cursorId,{numberToReturn:n}),m=sF({},r);e.s.pool.write(d,m,u);return}let f={getMore:r.cursorId instanceof bf?r.cursorId:bf.fromNumber(r.cursorId),collection:nF(t),batchSize:Math.abs(n)};r.cmd.tailable&&typeof r.cmd.maxAwaitTimeMS=="number"&&(f.maxTimeMS=r.cmd.maxAwaitTimeMS);let h=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},i);r.session&&(h.session=r.session),oF(e,t,f,h,u)}o(aF,"getMore");ub.exports=aF});var db=w((Sie,hb)=>{"use strict";var uF=sr().Query,fb=V().MongoError,lb=We().getReadPreference,cF=We().collectionNamespace,fF=We().isSharded,lF=re().maxWireVersion,hF=We().applyCommonQueryOptions,dF=$s(),pF=b().decorateWithExplain,mF=La().Explain;function yF(e,t,r,n,i,s){if(i=i||{},n.cursorId!=null)return s();if(r==null)return s(new fb(`command ${JSON.stringify(r)} does not return a cursor`));if(lF(e)<4){let f=SF(e,t,r,n,i),h=hF({},n);typeof f.documentsReturnedIn=="string"&&(h.documentsReturnedIn=f.documentsReturnedIn),e.s.pool.write(f,h,s);return}let a=lb(r,i),u=gF(e,t,r,n,i);try{let f=mF.fromOptions(i);f&&(u=pF(u,f))}catch(f){return s(f)}r.virtual=!1;let c=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:a.slaveOk()},i);r.readPreference&&(c.readPreference=a),n.session&&(c.session=n.session),dF(e,t,u,c,s)}o(yF,"query");function gF(e,t,r,n){n.batchSize=r.batchSize||n.batchSize;let i={find:cF(t)};r.query&&(r.query.$query?i.filter=r.query.$query:i.filter=r.query);let s=r.sort;if(Array.isArray(s)){let a={};if(s.length>0&&!Array.isArray(s[0])){let u=s[1];u==="asc"?u=1:u==="desc"&&(u=-1),a[s[0]]=u}else for(let u=0;u0&&n.batchSize===0?u=n.limit:u=n.batchSize;let c=n.skip||0,f={};if(fF(e)&&a&&(f.$readPreference=a.toJSON()),r.sort&&(f.$orderby=r.sort),r.hint&&(f.$hint=r.hint),r.snapshot&&(f.$snapshot=r.snapshot),typeof r.returnKey<"u"&&(f.$returnKey=r.returnKey),r.maxScan&&(f.$maxScan=r.maxScan),r.min&&(f.$min=r.min),r.max&&(f.$max=r.max),typeof r.showDiskLoc<"u"&&(f.$showDiskLoc=r.showDiskLoc),r.comment&&(f.$comment=r.comment),r.maxTimeMS&&(f.$maxTimeMS=r.maxTimeMS),i.explain!==void 0&&(u=-Math.abs(r.limit||0),f.$explain=!0),f.$query=r.query,r.readConcern&&r.readConcern.level!=="local")throw new fb(`server find command does not support a readConcern level of ${r.readConcern.level}`);r.readConcern&&(r=Object.assign({},r),delete r.readConcern);let h=typeof i.serializeFunctions=="boolean"?i.serializeFunctions:!1,l=typeof i.ignoreUndefined=="boolean"?i.ignoreUndefined:!1,d=new uF(s,t,f,{numberToSkip:c,numberToReturn:u,pre32Limit:typeof r.limit<"u"?r.limit:void 0,checkKeys:!1,returnFieldSelector:r.fields,serializeFunctions:h,ignoreUndefined:l});return typeof r.tailable=="boolean"&&(d.tailable=r.tailable),typeof r.oplogReplay=="boolean"&&(d.oplogReplay=r.oplogReplay),typeof r.noCursorTimeout=="boolean"&&(d.noCursorTimeout=r.noCursorTimeout),typeof r.awaitData=="boolean"&&(d.awaitData=r.awaitData),typeof r.partial=="boolean"&&(d.partial=r.partial),d.slaveOk=a.slaveOk(),d}o(SF,"prepareLegacyFindQuery");hb.exports=yF});var Ny=w((Oie,pb)=>{"use strict";var Ty=sb();pb.exports={insert:o(function(t,r,n,i,s){Ty(t,"insert","documents",r,n,i,s)},"insert"),update:o(function(t,r,n,i,s){Ty(t,"update","updates",r,n,i,s)},"update"),remove:o(function(t,r,n,i,s){Ty(t,"delete","deletes",r,n,i,s)},"remove"),killCursors:ab(),getMore:cb(),query:db(),command:$s()}});var F=w((Eie,yb)=>{"use strict";var wF=La().Explain,OF=V().MongoError,mb={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS"),EXPLAINABLE:Symbol("EXPLAINABLE")},Cy=class Cy{constructor(t){if(this.options=Object.assign({},t),this.hasAspect(mb.EXPLAINABLE))this.explain=wF.fromOptions(t);else if(this.options.explain!==void 0)throw new OF("explain is not supported on this command")}hasAspect(t){return this.constructor.aspects==null?!1:this.constructor.aspects.has(t)}set session(t){Object.assign(this.options,{session:t})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}};o(Cy,"OperationBase");var by=Cy;function vF(e,t){return!Array.isArray(t)&&!(t instanceof Set)&&(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t}o(vF,"defineAspects");yb.exports={Aspect:mb,defineAspects:vF,OperationBase:by}});var zs=w((Tie,Ob)=>{"use strict";var EF=b().maybePromise,Ay=V().MongoError,Sb=F().Aspect,_F=F().OperationBase,Iy=wt(),TF=V().isRetryableError,NF=re().maxWireVersion,bF=re().isUnifiedTopology;function wb(e,t,r){if(e==null)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof _F))throw new TypeError("This method requires a valid operation instance");return EF(e,r,n=>{if(bF(e)&&e.shouldCheckForSessionSupport())return AF(e,t,n);let i,s;if(e.hasSessionSupport()){if(t.session==null)s=Symbol(),i=e.startSession({owner:s}),t.session=i;else if(t.session.hasEnded)return n(new Ay("Use of expired sessions is not permitted"))}else if(t.session)return n(new Ay("Current topology does not support sessions"));function a(u,c){i&&i.owner===s&&(i.endSession(),t.session===i&&t.clearSession()),n(u,c)}o(a,"executeCallback");try{t.hasAspect(Sb.EXECUTE_WITH_SELECTION)?CF(e,t,a):t.execute(a)}catch(u){i&&i.owner===s&&(i.endSession(),t.session===i&&t.clearSession()),n(u)}})}o(wb,"executeOperation");function gb(e){return NF(e)>=6}o(gb,"supportsRetryableReads");function CF(e,t,r){let n=t.readPreference||Iy.primary,i=t.session&&t.session.inTransaction();if(i&&!n.equals(Iy.primary)){r(new Ay(`Read preference in a transaction must be primary, not: ${n.mode}`));return}let s={readPreference:n,session:t.session};function a(u,c){if(u==null)return r(null,c);if(!TF(u))return r(u);e.selectServer(s,(f,h)=>{if(f||!gb(h)){r(f,null);return}t.execute(h,r)})}o(a,"callbackWithRetry"),e.selectServer(s,(u,c)=>{if(u){r(u,null);return}let f=e.s.options.retryReads!==!1&&t.session&&!i&&gb(c)&&t.canRetryRead;if(t.hasAspect(Sb.RETRYABLE)&&f){t.execute(c,a);return}t.execute(c,r)})}o(CF,"executeWithServerSelection");function AF(e,t,r){e.selectServer(Iy.primaryPreferred,n=>{if(n)return r(n);wb(e,t,r)})}o(AF,"selectServerForSessionSupport");Ob.exports=wb});var Sr=w((bie,Tb)=>{"use strict";var IF=yr(),BF=mt().retrieveBSON,ln=V().MongoError,vb=V().MongoNetworkError,RF=re().collationNotSupported,MF=wt(),xF=re().isUnifiedTopology,qF=zs(),DF=require("stream").Readable,PF=b().SUPPORTS,LF=b().MongoDBNamespace,jF=b().mergeOptions,UF=F().OperationBase,WF=BF(),zr=WF.Long,Eb={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function Wi(e,t,r){try{e(t,r)}catch(n){process.nextTick(function(){throw n})}}o(Wi,"handleCallback");var By=class By extends DF{constructor(t,r,n,i){super({objectMode:!0}),i=i||{},r instanceof UF&&(this.operation=r,r=this.operation.ns.toString(),i=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=i.disconnectHandler,this.bson=t.s.bson,this.ns=r,this.namespace=LF.fromString(r),this.cmd=n,this.options=i,this.topology=t,this.cursorState={cursorId:null,cmd:n,documents:i.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:i.limit||n.limit||0,skip:i.skip||n.skip||0,batchSize:i.batchSize||n.batchSize||1e3,currentLimit:0,transforms:i.transforms,raw:i.raw||n&&n.raw},typeof i.session=="object"&&(this.cursorState.session=i.session);let s=t.s.options;typeof s.promoteLongs=="boolean"?this.cursorState.promoteLongs=s.promoteLongs:typeof i.promoteLongs=="boolean"&&(this.cursorState.promoteLongs=i.promoteLongs),typeof s.promoteValues=="boolean"?this.cursorState.promoteValues=s.promoteValues:typeof i.promoteValues=="boolean"&&(this.cursorState.promoteValues=i.promoteValues),typeof s.promoteBuffers=="boolean"?this.cursorState.promoteBuffers=s.promoteBuffers:typeof i.promoteBuffers=="boolean"&&(this.cursorState.promoteBuffers=i.promoteBuffers),typeof s.bsonRegExp=="boolean"?this.cursorState.bsonRegExp=s.bsonRegExp:typeof i.bsonRegExp=="boolean"&&(this.cursorState.bsonRegExp=i.bsonRegExp),s.reconnect&&(this.cursorState.reconnect=s.reconnect),this.logger=IF("Cursor",s),typeof n=="number"?(this.cursorState.cursorId=zr.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof zr&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(t){this.cursorState.batchSize=t}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(t){this.cursorState.limit=t}cursorLimit(){return this.cursorState.limit}setCursorSkip(t){this.cursorState.skip=t}cursorSkip(){return this.cursorState.skip}_next(t){Cf(this,t)}clone(){let t=jF({},this.options);return delete t.session,this.topology.cursor(this.ns,this.cmd,t)}isDead(){return this.cursorState.dead===!0}isKilled(){return this.cursorState.killed===!0}isNotified(){return this.cursorState.notified===!0}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(t){let r=this.cursorState.documents.length-this.cursorState.cursorIndex,n=t0&&this.cursorState.currentLimit+i.length>this.cursorState.limit&&(i=i.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+i.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+i.length,i}kill(t){if(this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],this.cursorState.cursorId==null||this.cursorState.cursorId.isZero()||this.cursorState.init===!1){t&&t(null,null);return}this.server.killCursors(this.ns,this.cursorState,t)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===Eb.CLOSED||this.isDead())return this.push(null);this._next((t,r)=>{if(t)return this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",t),this.isDead()||this.close(),this.emit("end"),this.emit("finish");if(this.cursorState.streamOptions&&typeof this.cursorState.streamOptions.transform=="function"&&r!=null)return this.push(this.cursorState.streamOptions.transform(r));this.push(r),r===null&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")})})}_endSession(t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=this.cursorState.session;return n&&(t.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(r),!0):(r&&r(),!1)}_getMore(t){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let r=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+r>this.cursorState.limit&&(r=this.cursorState.limit-this.cursorState.currentLimit);let n=this.cursorState;this.server.getMore(this.ns,n,r,this.options,(i,s,a)=>{(i||n.cursorId&&n.cursorId.isZero())&&this._endSession(),t(i,s,a)})}_initializeCursor(t){let r=this;if(xF(r.topology)&&r.topology.shouldCheckForSessionSupport()){r.topology.selectServer(MF.primaryPreferred,a=>{if(a){t(a);return}this._initializeCursor(t)});return}function n(a,u){let c=r.cursorState;if((a||c.cursorId&&c.cursorId.isZero())&&r._endSession(),c.documents.length===0&&c.cursorId&&c.cursorId.isZero()&&!r.cmd.tailable&&!r.cmd.awaitData)return If(r,t);t(a,u)}o(n,"done");let i=o((a,u)=>{if(a)return n(a);let c=u.message;if(Array.isArray(c.documents)&&c.documents.length===1){let h=c.documents[0];if(c.queryFailure)return n(new ln(h),null);if(!r.cmd.find||r.cmd.find&&r.cmd.virtual===!1){if(h.$err||h.errmsg)return n(new ln(h),null);if(h.cursor!=null&&typeof h.cursor!="string"){let l=h.cursor.id;return h.cursor.ns&&(r.ns=h.cursor.ns),r.cursorState.cursorId=typeof l=="number"?zr.fromNumber(l):l,r.cursorState.lastCursorId=r.cursorState.cursorId,r.cursorState.operationTime=h.operationTime,Array.isArray(h.cursor.firstBatch)&&(r.cursorState.documents=h.cursor.firstBatch),n(null,c)}}}let f=c.cursorId||0;r.cursorState.cursorId=f instanceof zr?f:zr.fromNumber(f),r.cursorState.documents=c.documents,r.cursorState.lastCursorId=c.cursorId,r.cursorState.transforms&&typeof r.cursorState.transforms.query=="function"&&(r.cursorState.documents=r.cursorState.transforms.query(c)),n(null,c)},"queryCallback");if(r.operation){r.logger.isDebug()&&r.logger.debug(`issue initial query [${JSON.stringify(r.cmd)}] with flags [${JSON.stringify(r.query)}]`),qF(r.topology,r.operation,(a,u)=>{if(a){n(a);return}if(r.server=r.operation.server,r.cursorState.init=!0,r.cursorState.cursorId!=null)return n();i(a,u)});return}let s={};return r.cursorState.session&&(s.session=r.cursorState.session),r.operation?s.readPreference=r.operation.readPreference:r.options.readPreference&&(s.readPreference=r.options.readPreference),r.topology.selectServer(s,(a,u)=>{if(a){let f=r.disconnectHandler;return f!=null?f.addObjectAndMethod("cursor",r,"next",[t],t):t(a)}if(r.server=u,r.cursorState.init=!0,RF(r.server,r.cmd))return t(new ln(`server ${r.server.name} does not support collation`));if(r.cursorState.cursorId!=null)return n();if(r.logger.isDebug()&&r.logger.debug(`issue initial query [${JSON.stringify(r.cmd)}] with flags [${JSON.stringify(r.query)}]`),r.cmd.find!=null){u.query(r.ns,r.cmd,r.cursorState,r.options,i);return}let c=Object.assign({session:r.cursorState.session},r.options);u.command(r.ns,r.cmd,c,i)})}};o(By,"CoreCursor");var Af=By;PF.ASYNC_ITERATOR&&(Af.prototype[Symbol.asyncIterator]=Xp().asyncIterator);function FF(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;let r=new vb(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return _b(e,()=>t(r)),!0}return!1}o(FF,"isConnectionDead");function $F(e,t){return e.cursorState.dead&&!e.cursorState.killed?(e.cursorState.killed=!0,If(e,t),!0):!1}o($F,"isCursorDeadButNotkilled");function zF(e,t){return e.cursorState.dead&&e.cursorState.killed?(Wi(t,new ln("cursor is dead")),!0):!1}o(zF,"isCursorDeadAndKilled");function VF(e,t){return e.cursorState.killed?(If(e,t),!0):!1}o(VF,"isCursorKilled");function ja(e,t){e.cursorState.dead=!0,If(e,t)}o(ja,"setCursorDeadAndNotified");function If(e,t){_b(e,()=>Wi(t,null,null))}o(If,"setCursorNotified");function _b(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,e.cursorState.session){e._endSession(t);return}return t()}o(_b,"_setCursorNotifiedImpl");function Cf(e,t){if(e.cursorState.notified)return t(new Error("cursor is exhausted"));if(!VF(e,t)&&!$F(e,t)&&!zF(e,t)){if(!e.cursorState.init){if(!e.topology.isConnected(e.options)){if(e.topology._type==="server"&&!e.topology.s.options.reconnect)return t(new ln("no connection available"));if(e.disconnectHandler!=null){if(e.topology.isDestroyed())return t(new ln("Topology was destroyed"));e.disconnectHandler.addObjectAndMethod("cursor",e,"next",[t],t);return}}e._initializeCursor((r,n)=>{if(r||n===null){t(r,n);return}Cf(e,t)});return}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit)e.kill(()=>ja(e,t));else if(e.cursorState.cursorIndex===e.cursorState.documents.length&&!zr.ZERO.equals(e.cursorState.cursorId)){if(e.cursorState.documents=[],e.cursorState.cursorIndex=0,e.topology.isDestroyed())return t(new vb("connection destroyed, not possible to instantiate cursor"));if(FF(e,t))return;e._getMore(function(r,n,i){if(r)return Wi(t,r);if(e.connection=i,e.cursorState.documents.length===0&&e.cmd.tailable&&zr.ZERO.equals(e.cursorState.cursorId))return Wi(t,new ln({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}));if(e.cursorState.documents.length===0&&e.cmd.tailable&&!zr.ZERO.equals(e.cursorState.cursorId))return Cf(e,t);if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit)return ja(e,t);Cf(e,t)})}else{if(e.cursorState.documents.length===e.cursorState.cursorIndex&&e.cmd.tailable&&zr.ZERO.equals(e.cursorState.cursorId))return Wi(t,new ln({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}));if(e.cursorState.documents.length===e.cursorState.cursorIndex&&zr.ZERO.equals(e.cursorState.cursorId))ja(e,t);else{if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill(()=>ja(e,t));return}e.cursorState.currentLimit+=1;let r=e.cursorState.documents[e.cursorState.cursorIndex++];if(!r||r.$err){e.kill(()=>ja(e,function(){Wi(t,new ln(r?r.$err:void 0))}));return}e.cursorState.transforms&&typeof e.cursorState.transforms.doc=="function"&&(r=e.cursorState.transforms.doc(r)),Wi(t,null,r)}}}}o(Cf,"nextFunction");Tb.exports={CursorState:Eb,CoreCursor:Af}});var xf=w((Aie,Cb)=>{"use strict";var HF=require("util").inherits,$i=require("util").format,Nb=require("events").EventEmitter,kF=wt(),YF=yr(),GF=mt().debugOptions,KF=mt().retrieveBSON,XF=QN(),ei=V().MongoError,JF=V().MongoNetworkError,zi=Ny(),ZF=Sr().CoreCursor,Qn=rt(),QF=rt().createCompressionInfo,e8=rt().resolveClusterTime,t8=rt().SessionMixins,r8=Di().extractCommand,n8=re().relayEvents,Ry=re().collationNotSupported,i8=re().makeClientMetadata,s8=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"],o8=0,Ua=!1,Wa={},It=KF();function Bf(e){return e.s.parent==null?e.id:e.s.parent.id}o(Bf,"topologyId");var De=o(function(e){e=e||{},Nb.call(this),this.id=o8++,this.s={options:Object.assign({metadata:i8(e)},e),logger:YF("Server",e),Cursor:e.cursorFactory||ZF,bson:e.bson||new It([It.Binary,It.Code,It.DBRef,It.Decimal128,It.Double,It.Int32,It.Long,It.Map,It.MaxKey,It.MinKey,It.ObjectId,It.BSONRegExp,It.Symbol,It.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:typeof e.monitoring=="boolean"?e.monitoring:!0,inTopology:!!e.parent,monitoringInterval:typeof e.monitoringInterval=="number"?e.monitoringInterval:5e3,compression:{compressors:QF(e)},parent:e.parent},this.s.parent||(this.s.clusterTime=null),this.ismaster=null,this.lastIsMasterMS=-1,this.monitoringProcessId=null,this.initialConnect=!0,this._type="server",this.lastUpdateTime=0,this.lastWriteDate=0,this.staleness=0},"Server");HF(De,Nb);Object.assign(De.prototype,t8);Object.defineProperty(De.prototype,"type",{enumerable:!0,get:function(){return this._type}});Object.defineProperty(De.prototype,"parserType",{enumerable:!0,get:function(){return It.native?"c++":"js"}});Object.defineProperty(De.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});Object.defineProperty(De.prototype,"clientMetadata",{enumerable:!0,get:function(){return this.s.options.metadata}});Object.defineProperty(De.prototype,"clusterTime",{enumerable:!0,set:function(e){let t=this.s.parent?this.s.parent:this.s;e8(t,e)},get:function(){return(this.s.parent?this.s.parent:this.s).clusterTime||null}});De.enableServerAccounting=function(){Ua=!0,Wa={}};De.disableServerAccounting=function(){Ua=!1};De.servers=function(){return Wa};Object.defineProperty(De.prototype,"name",{enumerable:!0,get:function(){return this.s.options.host+":"+this.s.options.port}});function Rf(e,t,r,n,i,s){if(!e.s.pool.isConnected()&&e.s.options.reconnect&&e.s.disconnectHandler!=null&&!i.monitoring)return e.s.disconnectHandler.add(t,r,n,i,s),!0;if(!e.s.pool.isConnected())return s(new ei($i("no connection available to server %s",e.name))),!0}o(Rf,"disconnectHandler");function bb(e){return function(){if(!e.s.pool.isDestroyed()){e.emit("monitoring",e);var t=new Date().getTime();e.command("admin.$cmd",{ismaster:!0},{socketTimeout:typeof e.s.options.connectionTimeout!="number"?2e3:e.s.options.connectionTimeout,monitoring:!0},(r,n)=>{e.lastIsMasterMS=new Date().getTime()-t,!e.s.pool.isDestroyed()&&(n&&(e.ismaster=n.result),e.monitoringProcessId=setTimeout(bb(e),e.s.monitoringInterval))})}}}o(bb,"monitoringProcess");var Fi=o(function(e,t){return function(r,n){if(e.s.logger.isInfo()){var i=r instanceof ei?JSON.stringify(r):{};e.s.logger.info($i("server %s fired event %s out with message %s",e.name,t,i))}if(t==="connect"){if(e.initialConnect=!1,e.ismaster=n.ismaster,e.lastIsMasterMS=n.lastIsMasterMS,n.agreedCompressor&&(e.s.pool.options.agreedCompressor=n.agreedCompressor),n.zlibCompressionLevel&&(e.s.pool.options.zlibCompressionLevel=n.zlibCompressionLevel),n.ismaster.$clusterTime){let s=n.ismaster.$clusterTime;e.clusterTime=s}e.ismaster.msg==="isdbgrid"&&(e._type="mongos"),e.s.monitoring&&(e.monitoringProcessId=setTimeout(bb(e),e.s.monitoringInterval)),Qn.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:Qn.getTopologyType(e)}),e.s.inTopology||Qn.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:Qn.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info($i("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else if(t==="error"||t==="parseError"||t==="close"||t==="timeout"||t==="reconnect"||t==="attemptReconnect"||t==="reconnectFailed"){if(Ua&&["close","timeout","error","parseError","reconnectFailed"].indexOf(t)!==-1&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete Wa[e.id]),t==="close"&&Qn.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),t==="reconnectFailed"){e.emit("reconnectFailed",r),e.listeners("error").length>0&&e.emit("error",r);return}if(["disconnected","connecting"].indexOf(e.s.pool.state)!==-1&&e.initialConnect&&["close","timeout","error","parseError"].indexOf(t)!==-1)return e.initialConnect=!1,e.emit("error",new JF($i("failed to connect to server [%s] on first connect [%s]",e.name,r)));if(t==="reconnect")return Qn.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:Qn.getTopologyType(e)}),e.emit(t,e);e.emit(t,r)}}},"eventHandler");De.prototype.connect=function(e){var t=this;if(e=e||{},Ua&&(Wa[this.id]=this),t.s.pool&&!t.s.pool.isDisconnected()&&!t.s.pool.isDestroyed())throw new ei($i("server instance in invalid state %s",t.s.pool.state));t.s.pool=new XF(this,Object.assign(t.s.options,e,{bson:this.s.bson})),t.s.pool.on("close",Fi(t,"close")),t.s.pool.on("error",Fi(t,"error")),t.s.pool.on("timeout",Fi(t,"timeout")),t.s.pool.on("parseError",Fi(t,"parseError")),t.s.pool.on("connect",Fi(t,"connect")),t.s.pool.on("reconnect",Fi(t,"reconnect")),t.s.pool.on("reconnectFailed",Fi(t,"reconnectFailed")),n8(t.s.pool,t,["commandStarted","commandSucceeded","commandFailed"]),t.s.inTopology||this.emit("topologyOpening",{topologyId:Bf(t)}),t.emit("serverOpening",{topologyId:Bf(t),address:t.name}),t.s.pool.connect()};De.prototype.auth=function(e,t){typeof t=="function"&&t(null,null)};De.prototype.getDescription=function(){var e=this.ismaster||{},t={type:Qn.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t};De.prototype.lastIsMaster=function(){return this.ismaster};De.prototype.unref=function(){this.s.pool.unref()};De.prototype.isConnected=function(){return this.s.pool?this.s.pool.isConnected():!1};De.prototype.isDestroyed=function(){return this.s.pool?this.s.pool.isDestroyed():!1};function Mf(e){if(!e.s.pool)return new ei("server instance is not connected");if(e.s.pool.isDestroyed())return new ei("server instance pool was destroyed")}o(Mf,"basicWriteValidations");function a8(e,t){if(Mf(e,t),t.readPreference&&!(t.readPreference instanceof kF))throw new Error("readPreference must be an instance of ReadPreference")}o(a8,"basicReadValidations");De.prototype.command=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var s=a8(i,r);if(s)return n(s);if(r=Object.assign({},r,{wireProtocolCommand:!1}),i.s.logger.isDebug()){let a=r8(t);i.s.logger.debug($i("executing command [%s] against %s",JSON.stringify({ns:e,cmd:a.shouldRedact?`${a.name} details REDACTED`:t,options:GF(s8,r)}),i.name))}if(!Rf(i,"command",e,t,r,n)){if(Ry(this,t))return n(new ei(`server ${this.name} does not support collation`));zi.command(i,e,t,r,n)}};De.prototype.query=function(e,t,r,n,i){zi.query(this,e,t,r,n,i)};De.prototype.getMore=function(e,t,r,n,i){zi.getMore(this,e,t,r,n,i)};De.prototype.killCursors=function(e,t,r){zi.killCursors(this,e,t,r)};De.prototype.insert=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var s=Mf(i,r);if(s)return n(s);if(!Rf(i,"insert",e,t,r,n))return t=Array.isArray(t)?t:[t],zi.insert(i,e,t,r,n)};De.prototype.update=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var s=Mf(i,r);if(s)return n(s);if(!Rf(i,"update",e,t,r,n))return Ry(this,r)?n(new ei(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],zi.update(i,e,t,r,n))};De.prototype.remove=function(e,t,r,n){var i=this;typeof r=="function"&&(n=r,r={},r=r||{});var s=Mf(i,r);if(s)return n(s);if(!Rf(i,"remove",e,t,r,n))return Ry(this,r)?n(new ei(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],zi.remove(i,e,t,r,n))};De.prototype.cursor=function(e,t,r){r=r||{};let n=r.topology||this;var i=r.cursorFactory||this.s.Cursor;return new i(n,e,t,r)};De.prototype.equals=function(e){return typeof e=="string"?this.name.toLowerCase()===e.toLowerCase():e.name?this.name.toLowerCase()===e.name.toLowerCase():!1};De.prototype.connections=function(){return this.s.pool.allConnections()};De.prototype.selectServer=function(e,t,r){typeof e=="function"&&typeof r>"u"&&(r=e,e=void 0,t={}),typeof t=="function"&&(r=t,t=e,e=void 0),r(null,this)};var u8=["close","error","timeout","parseError","connect"];De.prototype.destroy=function(e,t){if(this._destroyed){typeof t=="function"&&t(null,null);return}typeof e=="function"&&(t=e,e={}),e=e||{};var r=this;if(Ua&&delete Wa[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!r.s.pool||this._destroyed){this._destroyed=!0,typeof t=="function"&&t(null,null);return}this._destroyed=!0,e.emitClose&&r.emit("close",r),e.emitDestroy&&r.emit("destroy",r),u8.forEach(function(n){r.s.pool.removeAllListeners(n)}),r.listeners("serverClosed").length>0&&r.emit("serverClosed",{topologyId:Bf(r),address:r.name}),r.listeners("topologyClosed").length>0&&!r.s.inTopology&&r.emit("topologyClosed",{topologyId:Bf(r)}),r.s.logger.isDebug()&&r.s.logger.debug($i("destroy called on server %s",r.name)),this.s.pool.destroy(e.force,t)};Cb.exports=De});var xb=w((Bie,Mb)=>{"use strict";var c8=require("util").inherits,Ab=require("util").format,f8=rt().diff,Bb=require("events").EventEmitter,l8=yr(),ti=wt(),Vi=V().MongoError,qf=qr().Buffer,ze={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"},Bt={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"},Gt=o(function(e){e=e||{},Bb.call(this),this.topologyType=e.setName?ze.ReplicaSetNoPrimary:ze.Unknown,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||l8("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0},"ReplSetState");c8(Gt,Bb);Gt.prototype.hasPrimaryAndSecondary=function(){return this.primary!=null&&this.secondaries.length>0};Gt.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()};Gt.prototype.hasPrimary=function(){return this.primary!=null};Gt.prototype.hasSecondary=function(){return this.secondaries.length>0};Gt.prototype.get=function(e){for(var t=this.allServers(),r=0;r{n--,!(n>0)&&(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,Vs(this),typeof t=="function"&&t(null,null))},"serverDestroyed");if(n===0){i();return}r.forEach(s=>s.destroy(e,i))};Gt.prototype.remove=function(e,t){t=t||{};var r=e.name.toLowerCase(),n=this.primary?[this.primary]:[];n=n.concat(this.secondaries),n=n.concat(this.arbiters),n=n.concat(this.passives);for(var i=0;ie.arbiterOnly&&e.setName,"isArbiter");Gt.prototype.update=function(e){var t=this;let r=e.lastIsMaster();r&&r.isWritablePrimary&&(r.ismaster=r.isWritablePrimary);var n=e.name.toLowerCase();if(r){var i=Array.isArray(r.hosts)?r.hosts:[];i=i.concat(Array.isArray(r.arbiters)?r.arbiters:[]),i=i.concat(Array.isArray(r.passives)?r.passives:[]),i=i.map(function(E){return E.toLowerCase()});for(var s=0;sc)return!1}else if(!l&&a&&c&&c=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=r-e.lastWriteDate+t)};Gt.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&e.maxStalenessSeconds==null){var i=xy(this,e);if(i)return i}else if(n.length>0&&e.maxStalenessSeconds!=null&&(i=My(this,e),i))return i;return e.equals(ti.secondaryPreferred)?this.primary:null}if(e.equals(ti.primaryPreferred)){if(i=null,this.primary)return this.primary;if(n.length>0&&e.maxStalenessSeconds==null?i=xy(this,e):n.length>0&&e.maxStalenessSeconds!=null&&(i=My(this,e)),i)return i}return this.primary};var Rb=o(function(e,t){if(e.tags==null)return t;for(var r=[],n=Array.isArray(e.tags)?e.tags:[e.tags],i=0;i0?r[0].lastIsMasterMS:0;if(r=r.filter(function(a){return a.lastIsMasterMS<=i+e.acceptableLatency}),r.length===0)return null;e.index=e.index%r.length;var s=r[e.index];return e.index=e.index+1,s}o(xy,"pickNearest");function Df(e,t,r){for(var n=0;n0){var t="Unknown",r=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var n={topologyType:t,setName:r,servers:[]};if(e.hasPrimary()){var i=e.primary.getDescription();i.type="RSPrimary",n.servers.push(i)}n.servers=n.servers.concat(e.secondaries.map(function(u){var c=u.getDescription();return c.type="RSSecondary",c})),n.servers=n.servers.concat(e.arbiters.map(function(u){var c=u.getDescription();return c.type="RSArbiter",c})),n.servers=n.servers.concat(e.passives.map(function(u){var c=u.getDescription();return c.type="RSSecondary",c}));var s=f8(e.replicasetDescription,n),a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:n,diff:s};e.emit("topologyDescriptionChanged",a),e.replicasetDescription=n}}o(Vs,"emitTopologyDescriptionChanged");Mb.exports=Gt});var Vb=w((Mie,zb)=>{"use strict";var h8=require("util").inherits,dn=require("util").format,Pb=require("events").EventEmitter,hn=wt(),d8=Sr().CoreCursor,p8=mt().retrieveBSON,m8=yr(),wr=V().MongoError,jf=xf(),y8=xb(),Hs=rt().Timeout,Lb=rt().Interval,g8=rt().SessionMixins,jb=rt().isRetryableWritesSupported,Ub=re().relayEvents,Rt=p8(),S8=rt().getMMAPError,w8=re().makeClientMetadata,Wb=rt().legacyIsRetryableWriteError,Fb=b().now,O8=b().calculateDurationInMs,Hi="disconnected",ki="connecting",Pf="connected",Kt="unreferenced",ut="destroyed";function ni(e,t){var r={disconnected:[ki,ut,Hi],connecting:[ki,ut,Pf,Hi],connected:[Pf,Hi,ut,Kt],unreferenced:[Kt,ut],destroyed:[ut]},n=r[e.state];n&&n.indexOf(t)!==-1?e.state=t:e.s.logger.error(dn("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}o(ni,"stateTransition");var v8=1,Lf=["connect","close","error","timeout","parseError"],ct=o(function(e,t){var r=this;if(t=t||{},!Array.isArray(e))throw new wr("seedlist must be an array");if(e.length===0)throw new wr("seedlist must contain at least one entry");e.forEach(function(a){if(typeof a.host!="string"||typeof a.port!="number")throw new wr("seedlist entry must contain a host and port")}),Pb.call(this),this.id=v8++;var n=t.localThresholdMS||15;t.acceptableLatency&&(n=t.acceptableLatency);var i=m8("ReplSet",t);this.s={options:Object.assign({metadata:w8(t)},t),bson:t.bson||new Rt([Rt.Binary,Rt.Code,Rt.DBRef,Rt.Decimal128,Rt.Double,Rt.Int32,Rt.Long,Rt.Map,Rt.MaxKey,Rt.MinKey,Rt.ObjectId,Rt.BSONRegExp,Rt.Symbol,Rt.Timestamp]),Cursor:t.cursorFactory||d8,logger:i,seedlist:e,replicaSetState:new y8({id:this.id,setName:t.setName,acceptableLatency:n,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:i}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug=="boolean"?t.debug:!1},this.s.replicaSetState.on("topologyDescriptionChanged",function(a){r.emit("topologyDescriptionChanged",a)}),this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeoutm.name===f);if(l>=0)return e.s.connectingServers[l].destroy({force:!0}),e.s.connectingServers.splice(l,1),s();var d=new jf(Object.assign({},e.s.options,{host:f.split(":")[0],port:parseInt(f.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));d.once("connect",a(e,"connect")),d.once("close",a(e,"close")),d.once("timeout",a(e,"timeout")),d.once("error",a(e,"error")),d.once("parseError",a(e,"parseError")),d.on("serverOpening",m=>e.emit("serverOpening",m)),d.on("serverDescriptionChanged",m=>e.emit("serverDescriptionChanged",m)),d.on("serverClosed",m=>e.emit("serverClosed",m)),Ub(d,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(d),d.connect(e.s.connectOptions)},h)}o(u,"execute");for(var c=0;ce.emit("serverOpening",a)),i.on("serverDescriptionChanged",a=>e.emit("serverDescriptionChanged",a)),i.on("serverClosed",a=>e.emit("serverClosed",a)),Ub(i,e,["commandStarted","commandSucceeded","commandFailed"]),i.connect(e.s.connectOptions)},s)}for(o(n,"connect");t.length>0;)n(t.shift(),r++)}o(T8,"connectServers");function $a(e,t,r){e.listeners(t).length>0&&e.emit(t,r)}o($a,"emitSDAMEvent");ct.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},ni(this,ki);var r=this.s.seedlist.map(function(n){return new jf(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))});if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new wr(dn("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));$a(this,"topologyOpening",{topologyId:this.id}),T8(t,r)};ct.prototype.auth=function(e,t){typeof t=="function"&&t(null,null)};ct.prototype.destroy=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=this.s.connectingServers.length+1,n=o(()=>{r--,!(r>0)&&($a(this,"topologyClosed",{topologyId:this.id}),typeof t=="function"&&t(null,null))},"serverDestroyed");if(this.state===ut){typeof t=="function"&&t(null,null);return}ni(this,ut),this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var i=0;i"u"&&(r=e,e=void 0,t={}),typeof t=="function"&&(r=t,t=e),t=t||{};let n;e instanceof hn?n=e:n=t.readPreference||hn.primary;let i,s=Fb(),a=o(()=>{if(O8(s)>=N8){i!=null?r(i,null):r(new wr("Server selection timed out"));return}let u=this.s.replicaSetState.pickServer(n);if(u==null){setTimeout(a,Db);return}if(!(u instanceof jf)){i=u,setTimeout(a,Db);return}this.s.debug&&this.emit("pickedServer",t.readPreference,u),r(null,u)},"_selectServer");a()};ct.prototype.getServers=function(){return this.s.replicaSetState.allServers()};function Uf(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.self,i=e.op,s=e.ns,a=e.ops;if(n.state===ut)return r(new wr(dn("topology was destroyed")));let u=!e.retrying&&!!t.retryWrites&&t.session&&jb(n)&&!t.session.inTransaction()&&t.explain===void 0;if(!n.s.replicaSetState.hasPrimary()){if(n.s.disconnectHandler)return n.s.disconnectHandler.add(i,s,a,t,r);if(!u)return r(new wr("no primary server found"))}let c=o((f,h)=>{if(!f)return r(null,h);if(!Wb(f,n))return f=S8(f),r(f);if(u){let l=Object.assign({},e,{retrying:!0});return Uf(l,t,r)}return n.s.replicaSetState.primary&&(n.s.replicaSetState.primary.destroy(),n.s.replicaSetState.remove(n.s.replicaSetState.primary,{force:!0})),r(f)},"handler");r.operationId&&(c.operationId=r.operationId),u&&(t.session.incrementTransactionNumber(),t.willRetryWrite=u),n.s.replicaSetState.primary[i](s,a,t,c)}o(Uf,"executeWriteOperation");ct.prototype.insert=function(e,t,r,n){Uf({self:this,op:"insert",ns:e,ops:t},r,n)};ct.prototype.update=function(e,t,r,n){Uf({self:this,op:"update",ns:e,ops:t},r,n)};ct.prototype.remove=function(e,t,r,n){Uf({self:this,op:"remove",ns:e,ops:t},r,n)};var b8=["findAndModify","insert","update","delete"];function C8(e){return b8.some(t=>e[t])}o(C8,"isWriteCommand");ct.prototype.command=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===ut)return n(new wr(dn("topology was destroyed")));var i=this,s=r.readPreference?r.readPreference:hn.primary;if(s.preference==="primary"&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);if(s.preference==="secondary"&&!this.s.replicaSetState.hasSecondary()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);if(s.preference!=="primary"&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);var a=this.s.replicaSetState.pickServer(s);if(!(a instanceof jf))return n(a);if(i.s.debug&&i.emit("pickedServer",hn.primary,a),a==null)return n(new wr(dn("no server found that matches the provided readPreference %s",s)));let u=!r.retrying&&!!r.retryWrites&&r.session&&jb(i)&&!r.session.inTransaction()&&C8(t),c=o((f,h)=>{if(!f)return n(null,h);if(!Wb(f,i))return n(f);if(u){let l=Object.assign({},r,{retrying:!0});return this.command(e,t,l,n)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),n(f)},"cb");u&&(r.session.incrementTransactionNumber(),r.willRetryWrite=u),a.command(e,t,r,c)};ct.prototype.cursor=function(e,t,r){r=r||{};let n=r.topology||this;var i=r.cursorFactory||this.s.Cursor;return new i(n,e,t,r)};zb.exports=ct});var Qb=w((qie,Zb)=>{"use strict";var A8=require("util").inherits,si=require("util").format,kb=require("events").EventEmitter,I8=Sr().CoreCursor,B8=yr(),R8=mt().retrieveBSON,Er=V().MongoError,Yb=xf(),M8=rt().diff,x8=rt().cloneOptions,q8=rt().SessionMixins,Gb=rt().isRetryableWritesSupported,Ff=re().relayEvents,Mt=R8(),D8=rt().getMMAPError,P8=re().makeClientMetadata,Kb=rt().legacyIsRetryableWriteError,Wf="disconnected",ks="connecting",Uy="connected",Or="unreferenced",Ut="destroying",it="destroyed";function Ha(e,t){var r={disconnected:[ks,Ut,it,Wf],connecting:[ks,Ut,it,Uy,Wf],connected:[Uy,Wf,Ut,it,Or],unreferenced:[Or,Ut,it],destroyed:[it]},n=r[e.state];n&&n.indexOf(t)!==-1?e.state=t:e.s.logger.error(si("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}o(Ha,"stateTransition");var L8=1,$f=["connect","close","error","timeout","parseError"],lt=o(function(e,t){t=t||{},this.id=L8++,Array.isArray(e)&&(e=e.reduce((r,n)=>(r.find(i=>i.host===n.host&&i.port===n.port)||r.push(n),r),[])),this.s={options:Object.assign({metadata:P8(t)},t),bson:t.bson||new Mt([Mt.Binary,Mt.Code,Mt.DBRef,Mt.Decimal128,Mt.Double,Mt.Int32,Mt.Long,Mt.Map,Mt.MaxKey,Mt.MinKey,Mt.ObjectId,Mt.BSONRegExp,Mt.Symbol,Mt.Timestamp]),Cursor:t.cursorFactory||I8,logger:B8("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug=="boolean"?t.debug:!1,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeout0&&e.emit(t,r)}o(Va,"emitSDAMEvent");var j8=["serverDescriptionChanged","error","close","timeout","parseError"];function Xb(e,t,r){t=t||{},j8.forEach(n=>e.removeAllListeners(n)),e.destroy(t,r)}o(Xb,"destroyServer");lt.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},Ha(this,ks);var r=this.s.seedlist.map(function(n){let i=new Yb(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return Ff(i,t,["serverDescriptionChanged"]),i});Va(this,"topologyOpening",{topologyId:this.id}),U8(t,r)};lt.prototype.auth=function(e,t){typeof t=="function"&&t(null,null)};function ii(e){return function(){e.state===it||e.state===Ut||(vr(e.connectedProxies,e.disconnectedProxies,this),Yi(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}o(ii,"handleEvent");function za(e,t){return function(){var r=this;if(e.state===it)return Yi(e),vr(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if(t==="connect")if(e.ismaster=r.lastIsMaster(),e.ismaster.msg==="isdbgrid"){for(let i=0;i0&&e.state===ks)Ha(e,Uy),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(e.disconnectedProxies.length===0)return e.s.logger.isWarn()&&e.s.logger.warn(si("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new Er("no mongos proxies found in seed list"));Wy(e,{firstConnect:!0})}}}o(za,"handleInitialConnectEvent");function U8(e,t){e.connectingProxies=e.connectingProxies.concat(t);var r=0;function n(i,s){setTimeout(function(){e.emit("serverOpening",{topologyId:e.id,address:i.name}),Yi(e),i.once("close",za(e,"close")),i.once("timeout",za(e,"timeout")),i.once("parseError",za(e,"parseError")),i.once("error",za(e,"error")),i.once("connect",za(e,"connect")),Ff(i,e,["commandStarted","commandSucceeded","commandFailed"]),i.connect(e.s.connectOptions)},s)}o(n,"connect"),t.forEach(i=>n(i,r++))}o(U8,"connectProxies");function zf(e,t){let r=t&&t.transaction;if(r&&r.server){if(r.server.isConnected())return r.server;r.unpinServer()}for(var n=e.connectedProxies.slice(0),i=Number.MAX_VALUE,s=0;s0&&e.state===ks?e.emit("error",new Er("no mongos proxy available")):e.emit("close",e),Hb(e,e.disconnectedProxies,function(){e.state===it||e.state===Ut||e.state===Or||(e.state===ks&&t.firstConnect?(e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e)):e.isConnected()?e.emit("reconnect",e):!e.isConnected()&&e.listeners("close").length>0&&e.emit("close",e),Wy(e))});for(var s=0;s{n--,!(n>0)&&(Yi(this),Va(this,"topologyClosed",{topologyId:this.id}),Ha(this,it),typeof t=="function"&&t(null,null))},"serverDestroyed");if(n===0){i();return}r.forEach(s=>{this.emit("serverClosed",{topologyId:this.id,address:s.name}),Xb(s,e,i),vr(this.connectedProxies,this.disconnectedProxies,s)})};lt.prototype.isConnected=function(){return this.connectedProxies.length>0};lt.prototype.isDestroyed=function(){return this.state===it};function Vf(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.self,i=e.op,s=e.ns,a=e.ops,u=zf(n,t.session);if(!u)return r(new Er("no mongos proxy available"));let c=!e.retrying&&!!t.retryWrites&&t.session&&Gb(n)&&!t.session.inTransaction()&&t.explain===void 0,f=o((h,l)=>{if(!h)return r(null,l);if(!Kb(h,n)||!c)return h=D8(h),r(h);if(u=zf(n,t.session),!u)return r(h);let d=Object.assign({},e,{retrying:!0});return Vf(d,t,r)},"handler");r.operationId&&(f.operationId=r.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),u[i](s,a,t,f)}o(Vf,"executeWriteOperation");lt.prototype.insert=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===it)return n(new Er(si("topology was destroyed")));if(!this.isConnected()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("insert",e,t,r,n);if(!this.isConnected())return n(new Er("no mongos proxy available"));Vf({self:this,op:"insert",ns:e,ops:t},r,n)};lt.prototype.update=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===it)return n(new Er(si("topology was destroyed")));if(!this.isConnected()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("update",e,t,r,n);if(!this.isConnected())return n(new Er("no mongos proxy available"));Vf({self:this,op:"update",ns:e,ops:t},r,n)};lt.prototype.remove=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===it)return n(new Er(si("topology was destroyed")));if(!this.isConnected()&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("remove",e,t,r,n);if(!this.isConnected())return n(new Er("no mongos proxy available"));Vf({self:this,op:"remove",ns:e,ops:t},r,n)};var W8=["findAndModify","insert","update","delete"];function F8(e){return W8.some(t=>e[t])}o(F8,"isWriteCommand");lt.prototype.command=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={},r=r||{}),this.state===it)return n(new Er(si("topology was destroyed")));var i=this,s=zf(i,r.session);if((s==null||!s.isConnected())&&this.s.disconnectHandler!=null)return this.s.disconnectHandler.add("command",e,t,r,n);if(s==null)return n(new Er("no mongos proxy available"));var a=x8(r);a.topology=i;let u=!r.retrying&&r.retryWrites&&r.session&&Gb(i)&&!r.session.inTransaction()&&F8(t),c=o((f,h)=>{if(!f)return n(null,h);if(!Kb(f,i))return n(f);if(u){let l=Object.assign({},a,{retrying:!0});return this.command(e,t,l,n)}return n(f)},"cb");u&&(a.session.incrementTransactionNumber(),a.willRetryWrite=u),s.command(e,t,a,c)};lt.prototype.cursor=function(e,t,r){r=r||{};let n=r.topology||this;var i=r.cursorFactory||this.s.Cursor;return new i(n,e,t,r)};lt.prototype.selectServer=function(e,t,r){typeof e=="function"&&typeof r>"u"&&(r=e,e=void 0,t={}),typeof t=="function"&&(r=t,t=e,e=void 0),t=t||{};let n=zf(this,t.session);if(n==null){r(new Er("server selection failed"));return}this.s.debug&&this.emit("pickedServer",null,n),r(null,n)};lt.prototype.connections=function(){for(var e=[],t=0;t0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var r={topologyType:t,servers:[]},n=e.disconnectedProxies.concat(e.connectingProxies);r.servers=r.servers.concat(n.map(function(a){var u=a.getDescription();return u.type="Unknown",u})),r.servers=r.servers.concat(e.connectedProxies.map(function(a){var u=a.getDescription();return u.type="Mongos",u}));var i=M8(e.topologyDescription,r),s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:r,diff:i};i.servers.length>0&&e.emit("topologyDescriptionChanged",s),e.topologyDescription=r}}o(Yi,"emitTopologyDescriptionChanged");Zb.exports=lt});var Hf=w((Pie,eC)=>{"use strict";function st(e,r){var r=r||{};this._head=0,this._tail=0,this._capacity=r.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}o(st,"Denque");st.prototype.peekAt=o(function(t){var r=t;if(r===(r|0)){var n=this.size();if(!(r>=n||r<-n))return r<0&&(r+=n),r=this._head+r&this._capacityMask,this._list[r]}},"peekAt");st.prototype.get=o(function(t){return this.peekAt(t)},"get");st.prototype.peek=o(function(){if(this._head!==this._tail)return this._list[this._head]},"peek");st.prototype.peekFront=o(function(){return this.peek()},"peekFront");st.prototype.peekBack=o(function(){return this.peekAt(-1)},"peekBack");Object.defineProperty(st.prototype,"length",{get:o(function(){return this.size()},"length")});st.prototype.size=o(function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),r}},"shift");st.prototype.push=o(function(t){if(t===void 0)return this.size();var r=this._tail;return this._list[r]=t,this._tail=r+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&t<=r>>>2&&this._shrinkArray(),n}},"pop");st.prototype.removeOne=o(function(t){var r=t;if(r===(r|0)&&this._head!==this._tail){var n=this.size(),i=this._list.length;if(!(r>=n||r<-n)){r<0&&(r+=n),r=this._head+r&this._capacityMask;var s=this._list[r],a;if(t0;a--)this._list[r]=this._list[r=r-1+i&this._capacityMask];this._list[r]=void 0,this._head=this._head+1+i&this._capacityMask}else{for(a=n-1-t;a>0;a--)this._list[r]=this._list[r=r+1+i&this._capacityMask];this._list[r]=void 0,this._tail=this._tail-1+i&this._capacityMask}return s}}},"removeOne");st.prototype.remove=o(function(t,r){var n=t,i,s=r;if(n===(n|0)&&this._head!==this._tail){var a=this.size(),u=this._list.length;if(!(n>=a||n<-a||r<1)){if(n<0&&(n+=a),r===1||!r)return i=new Array(1),i[0]=this.removeOne(n),i;if(n===0&&n+r>=a)return i=this.toArray(),this.clear(),i;n+r>a&&(r=a-n);var c;for(i=new Array(r),c=0;c0;c--)this._list[n=n+1+u&this._capacityMask]=void 0;return i}if(t===0){for(this._head=this._head+r+u&this._capacityMask,c=r-1;c>0;c--)this._list[n=n+1+u&this._capacityMask]=void 0;return i}if(n0;c--)this.unshift(this._list[n=n-1+u&this._capacityMask]);for(n=this._head-1+u&this._capacityMask;s>0;)this._list[n=n-1+u&this._capacityMask]=void 0,s--;t<0&&(this._tail=n)}else{for(this._tail=n,n=n+r+u&this._capacityMask,c=a-(r+t);c>0;c--)this.push(this._list[n++]);for(n=this._tail;s>0;)this._list[n=n+1+u&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=u>>>2&&this._shrinkArray(),i}}},"remove");st.prototype.splice=o(function(t,r){var n=t;if(n===(n|0)){var i=this.size();if(n<0&&(n+=i),!(n>i))if(arguments.length>2){var s,a,u,c=arguments.length,f=this._list.length,h=2;if(!i||n0&&(this._head=this._head+n+f&this._capacityMask)):(u=this.remove(n,r),this._head=this._head+n+f&this._capacityMask);c>h;)this.unshift(arguments[--c]);for(s=n;s>0;s--)this.unshift(a[s-1])}else{a=new Array(i-(n+r));var l=a.length;for(s=0;sthis._tail){for(s=this._head;s>>=1,this._capacityMask>>>=1},"_shrinkArray");eC.exports=st});var sg=w((jie,tC)=>{"use strict";var Xy=class Xy{constructor(t,r,n,i){Object.assign(this,{topologyId:t,address:r,previousDescription:n,newDescription:i})}};o(Xy,"ServerDescriptionChangedEvent");var Fy=Xy,Jy=class Jy{constructor(t,r){Object.assign(this,{topologyId:t,address:r})}};o(Jy,"ServerOpeningEvent");var $y=Jy,Zy=class Zy{constructor(t,r){Object.assign(this,{topologyId:t,address:r})}};o(Zy,"ServerClosedEvent");var zy=Zy,Qy=class Qy{constructor(t,r,n){Object.assign(this,{topologyId:t,previousDescription:r,newDescription:n})}};o(Qy,"TopologyDescriptionChangedEvent");var Vy=Qy,eg=class eg{constructor(t){Object.assign(this,{topologyId:t})}};o(eg,"TopologyOpeningEvent");var Hy=eg,tg=class tg{constructor(t){Object.assign(this,{topologyId:t})}};o(tg,"TopologyClosedEvent");var ky=tg,rg=class rg{constructor(t){Object.assign(this,{connectionId:t})}};o(rg,"ServerHeartbeatStartedEvent");var Yy=rg,ng=class ng{constructor(t,r,n){Object.assign(this,{connectionId:n,duration:t,reply:r})}};o(ng,"ServerHeartbeatSucceededEvent");var Gy=ng,ig=class ig{constructor(t,r,n){Object.assign(this,{connectionId:n,duration:t,failure:r})}};o(ig,"ServerHeartbeatFailedEvent");var Ky=ig;tC.exports={ServerDescriptionChangedEvent:Fy,ServerOpeningEvent:$y,ServerClosedEvent:zy,TopologyDescriptionChangedEvent:Vy,TopologyOpeningEvent:Hy,TopologyClosedEvent:ky,ServerHeartbeatStartedEvent:Yy,ServerHeartbeatSucceededEvent:Gy,ServerHeartbeatFailedEvent:Ky}});var ka=w((Wie,og)=>{"use strict";typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0?og.exports={nextTick:$8}:og.exports=process;function $8(e,t,r,n){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var i=arguments.length,s,a;switch(i){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(o(function(){e.call(null,t)},"afterTickOne"));case 3:return process.nextTick(o(function(){e.call(null,t,r)},"afterTickTwo"));case 4:return process.nextTick(o(function(){e.call(null,t,r,n)},"afterTickThree"));default:for(s=new Array(i-1),a=0;a{var z8={}.toString;rC.exports=Array.isArray||function(e){return z8.call(e)=="[object Array]"}});var ag=w((zie,iC)=>{iC.exports=require("stream")});var Yf=w((ug,oC)=>{var kf=require("buffer"),pn=kf.Buffer;function sC(e,t){for(var r in e)t[r]=e[r]}o(sC,"copyProps");pn.from&&pn.alloc&&pn.allocUnsafe&&pn.allocUnsafeSlow?oC.exports=kf:(sC(kf,ug),ug.Buffer=Ys);function Ys(e,t,r){return pn(e,t,r)}o(Ys,"SafeBuffer");sC(pn,Ys);Ys.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return pn(e,t,r)};Ys.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=pn(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};Ys.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return pn(e)};Ys.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return kf.SlowBuffer(e)}});var Gs=w(xt=>{function V8(e){return Array.isArray?Array.isArray(e):Gf(e)==="[object Array]"}o(V8,"isArray");xt.isArray=V8;function H8(e){return typeof e=="boolean"}o(H8,"isBoolean");xt.isBoolean=H8;function k8(e){return e===null}o(k8,"isNull");xt.isNull=k8;function Y8(e){return e==null}o(Y8,"isNullOrUndefined");xt.isNullOrUndefined=Y8;function G8(e){return typeof e=="number"}o(G8,"isNumber");xt.isNumber=G8;function K8(e){return typeof e=="string"}o(K8,"isString");xt.isString=K8;function X8(e){return typeof e=="symbol"}o(X8,"isSymbol");xt.isSymbol=X8;function J8(e){return e===void 0}o(J8,"isUndefined");xt.isUndefined=J8;function Z8(e){return Gf(e)==="[object RegExp]"}o(Z8,"isRegExp");xt.isRegExp=Z8;function Q8(e){return typeof e=="object"&&e!==null}o(Q8,"isObject");xt.isObject=Q8;function e$(e){return Gf(e)==="[object Date]"}o(e$,"isDate");xt.isDate=e$;function t$(e){return Gf(e)==="[object Error]"||e instanceof Error}o(t$,"isError");xt.isError=t$;function r$(e){return typeof e=="function"}o(r$,"isFunction");xt.isFunction=r$;function n$(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e>"u"}o(n$,"isPrimitive");xt.isPrimitive=n$;xt.isBuffer=require("buffer").Buffer.isBuffer;function Gf(e){return Object.prototype.toString.call(e)}o(Gf,"objectToString")});var aC=w((Yie,cg)=>{typeof Object.create=="function"?cg.exports=o(function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))},"inherits"):cg.exports=o(function(t,r){if(r){t.super_=r;var n=o(function(){},"TempCtor");n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}},"inherits")});var Ks=w((Kie,lg)=>{try{if(fg=require("util"),typeof fg.inherits!="function")throw"";lg.exports=fg.inherits}catch{lg.exports=aC()}var fg});var cC=w((Xie,hg)=>{"use strict";function i$(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}o(i$,"_classCallCheck");var uC=Yf().Buffer,Ya=require("util");function s$(e,t,r){e.copy(t,r)}o(s$,"copyBuffer");hg.exports=function(){function e(){i$(this,e),this.head=null,this.tail=null,this.length=0}return o(e,"BufferList"),e.prototype.push=o(function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},"push"),e.prototype.unshift=o(function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length},"unshift"),e.prototype.shift=o(function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}},"shift"),e.prototype.clear=o(function(){this.head=this.tail=null,this.length=0},"clear"),e.prototype.join=o(function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i},"join"),e.prototype.concat=o(function(r){if(this.length===0)return uC.alloc(0);for(var n=uC.allocUnsafe(r>>>0),i=this.head,s=0;i;)s$(i.data,n,s),s+=i.data.length,i=i.next;return n},"concat"),e}();Ya&&Ya.inspect&&Ya.inspect.custom&&(hg.exports.prototype[Ya.inspect.custom]=function(){var e=Ya.inspect({length:this.length});return this.constructor.name+" "+e})});var dg=w((Zie,fC)=>{"use strict";var Kf=ka();function o$(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,Kf.nextTick(Xf,this,e)):Kf.nextTick(Xf,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(s){!t&&s?r._writableState?r._writableState.errorEmitted||(r._writableState.errorEmitted=!0,Kf.nextTick(Xf,r,s)):Kf.nextTick(Xf,r,s):t&&t(s)}),this)}o(o$,"destroy");function a$(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}o(a$,"undestroy");function Xf(e,t){e.emit("error",t)}o(Xf,"emitErrorNT");fC.exports={destroy:o$,undestroy:a$}});var hC=w((ese,lC)=>{lC.exports=require("util").deprecate});var mg=w((tse,OC)=>{"use strict";var Gi=ka();OC.exports=ht;function pC(e){var t=this;this.next=null,this.entry=null,this.finish=function(){N$(t,e)}}o(pC,"CorkedRequest");var u$=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:Gi.nextTick,Xs;ht.WritableState=Ka;var mC=Object.create(Gs());mC.inherits=Ks();var c$={deprecate:hC()},yC=ag(),Zf=Yf().Buffer,f$=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function l$(e){return Zf.from(e)}o(l$,"_uint8ArrayToBuffer");function h$(e){return Zf.isBuffer(e)||e instanceof f$}o(h$,"_isUint8Array");var gC=dg();mC.inherits(ht,yC);function d$(){}o(d$,"nop");function Ka(e,t){Xs=Xs||Ki(),e=e||{};var r=t instanceof Xs;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,i=e.writableHighWaterMark,s=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(i||i===0)?this.highWaterMark=i:this.highWaterMark=s,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=e.decodeStrings===!1;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(u){O$(t,u)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new pC(this)}o(Ka,"WritableState");Ka.prototype.getBuffer=o(function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r},"getBuffer");(function(){try{Object.defineProperty(Ka.prototype,"buffer",{get:c$.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var Jf;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Jf=Function.prototype[Symbol.hasInstance],Object.defineProperty(ht,Symbol.hasInstance,{value:function(e){return Jf.call(this,e)?!0:this!==ht?!1:e&&e._writableState instanceof Ka}})):Jf=o(function(e){return e instanceof this},"realHasInstance");function ht(e){if(Xs=Xs||Ki(),!Jf.call(ht,this)&&!(this instanceof Xs))return new ht(e);this._writableState=new Ka(e,this),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),yC.call(this)}o(ht,"Writable");ht.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function p$(e,t){var r=new Error("write after end");e.emit("error",r),Gi.nextTick(t,r)}o(p$,"writeAfterEnd");function m$(e,t,r,n){var i=!0,s=!1;return r===null?s=new TypeError("May not write null values to stream"):typeof r!="string"&&r!==void 0&&!t.objectMode&&(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),Gi.nextTick(n,s),i=!1),i}o(m$,"validChunk");ht.prototype.write=function(e,t,r){var n=this._writableState,i=!1,s=!n.objectMode&&h$(e);return s&&!Zf.isBuffer(e)&&(e=l$(e)),typeof t=="function"&&(r=t,t=null),s?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=d$),n.ended?p$(this,r):(s||m$(this,n,e,r))&&(n.pendingcb++,i=g$(this,n,s,e,t,r)),i};ht.prototype.cork=function(){var e=this._writableState;e.corked++};ht.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&SC(this,e))};ht.prototype.setDefaultEncoding=o(function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},"setDefaultEncoding");function y$(e,t,r){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=Zf.from(t,r)),t}o(y$,"decodeChunk");Object.defineProperty(ht.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function g$(e,t,r,n,i,s){if(!r){var a=y$(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var u=t.objectMode?1:n.length;t.length+=u;var c=t.length{"use strict";var vC=ka(),b$=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};TC.exports=mn;var EC=Object.create(Gs());EC.inherits=Ks();var _C=Sg(),gg=mg();EC.inherits(mn,_C);for(yg=b$(gg.prototype),Qf=0;Qf{var tl=require("buffer"),yn=tl.Buffer;function NC(e,t){for(var r in e)t[r]=e[r]}o(NC,"copyProps");yn.from&&yn.alloc&&yn.allocUnsafe&&yn.allocUnsafeSlow?bC.exports=tl:(NC(tl,wg),wg.Buffer=Js);function Js(e,t,r){return yn(e,t,r)}o(Js,"SafeBuffer");NC(yn,Js);Js.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return yn(e,t,r)};Js.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=yn(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};Js.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return yn(e)};Js.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return tl.SlowBuffer(e)}});var Eg=w(IC=>{"use strict";var vg=CC().Buffer,AC=vg.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function I$(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}o(I$,"_normalizeEncoding");function B$(e){var t=I$(e);if(typeof t!="string"&&(vg.isEncoding===AC||!AC(e)))throw new Error("Unknown encoding: "+e);return t||e}o(B$,"normalizeEncoding");IC.StringDecoder=Xa;function Xa(e){this.encoding=B$(e);var t;switch(this.encoding){case"utf16le":this.text=P$,this.end=L$,t=4;break;case"utf8":this.fillLast=x$,t=4;break;case"base64":this.text=j$,this.end=U$,t=3;break;default:this.write=W$,this.end=F$;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=vg.allocUnsafe(t)}o(Xa,"StringDecoder");Xa.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}o(Og,"utf8CheckByte");function R$(e,t,r){var n=t.length-1;if(n=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}o(R$,"utf8CheckIncomplete");function M$(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}o(M$,"utf8CheckExtraBytes");function x$(e){var t=this.lastTotal-this.lastNeed,r=M$(this,e,t);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}o(x$,"utf8FillLast");function q$(e,t){var r=R$(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}o(q$,"utf8Text");function D$(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}o(D$,"utf8End");function P$(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}o(P$,"utf16Text");function L$(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}o(L$,"utf16End");function j$(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}o(j$,"base64Text");function U$(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}o(U$,"base64End");function W$(e){return e.toString(this.encoding)}o(W$,"simpleWrite");function F$(e){return e&&e.length?this.write(e):""}o(F$,"simpleEnd")});var Sg=w((cse,FC)=>{"use strict";var Qs=ka();FC.exports=Ke;var $$=nC(),Ja;Ke.ReadableState=PC;var use=require("events").EventEmitter,xC=o(function(e,t){return e.listeners(t).length},"EElistenerCount"),Cg=ag(),Za=Yf().Buffer,z$=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function V$(e){return Za.from(e)}o(V$,"_uint8ArrayToBuffer");function H$(e){return Za.isBuffer(e)||e instanceof z$}o(H$,"_isUint8Array");var qC=Object.create(Gs());qC.inherits=Ks();var _g=require("util"),Pe=void 0;_g&&_g.debuglog?Pe=_g.debuglog("stream"):Pe=o(function(){},"debug");var k$=cC(),DC=dg(),Zs;qC.inherits(Ke,Cg);var Tg=["error","close","destroy","pause","resume"];function Y$(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):$$(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]}o(Y$,"prependListener");function PC(e,t){Ja=Ja||Ki(),e=e||{};var r=t instanceof Ja;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,i=e.readableHighWaterMark,s=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(i||i===0)?this.highWaterMark=i:this.highWaterMark=s,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new k$,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(Zs||(Zs=Eg().StringDecoder),this.decoder=new Zs(e.encoding),this.encoding=e.encoding)}o(PC,"ReadableState");function Ke(e){if(Ja=Ja||Ki(),!(this instanceof Ke))return new Ke(e);this._readableState=new PC(e,this),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),Cg.call(this)}o(Ke,"Readable");Object.defineProperty(Ke.prototype,"destroyed",{get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});Ke.prototype.destroy=DC.destroy;Ke.prototype._undestroy=DC.undestroy;Ke.prototype._destroy=function(e,t){this.push(null),t(e)};Ke.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=!0:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=Za.from(e,t),t=""),n=!0),LC(this,e,t,!1,n)};Ke.prototype.unshift=function(e){return LC(this,e,null,!0,!1)};function LC(e,t,r,n,i){var s=e._readableState;if(t===null)s.reading=!1,J$(e,s);else{var a;i||(a=G$(s,t)),a?e.emit("error",a):s.objectMode||t&&t.length>0?(typeof t!="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==Za.prototype&&(t=V$(t)),n?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):Ng(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!r?(t=s.decoder.write(t),s.objectMode||t.length!==0?Ng(e,s,t,!1):jC(e,s)):Ng(e,s,t,!1))):n||(s.reading=!1)}return K$(s)}o(LC,"readableAddChunk");function Ng(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&rl(e)),jC(e,t)}o(Ng,"addChunk");function G$(e,t){var r;return!H$(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new TypeError("Invalid non-string/buffer chunk")),r}o(G$,"chunkInvalid");function K$(e){return!e.ended&&(e.needReadable||e.length=BC?e=BC:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}o(X$,"computeNewHighWaterMark");function RC(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=X$(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}o(RC,"howMuchToRead");Ke.prototype.read=function(e){Pe("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return Pe("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?bg(this):rl(this),null;if(e=RC(e,t),e===0&&t.ended)return t.length===0&&bg(this),null;var n=t.needReadable;Pe("need readable",n),(t.length===0||t.length-e0?i=UC(e,t):i=null,i===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&bg(this)),i!==null&&this.emit("data",i),i};function J$(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,rl(e)}}o(J$,"onEofChunk");function rl(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Pe("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?Qs.nextTick(MC,e):MC(e))}o(rl,"emitReadable");function MC(e){Pe("emit readable"),e.emit("readable"),Ag(e)}o(MC,"emitReadable_");function jC(e,t){t.readingMore||(t.readingMore=!0,Qs.nextTick(Z$,e,t))}o(jC,"maybeReadMore");function Z$(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length1&&WC(n.pipes,e)!==-1)&&!f&&(Pe("false write response, pause",n.awaitDrain),n.awaitDrain++,l=!0),r.pause())}o(d,"ondata");function m(T){Pe("onerror",T),O(),e.removeListener("error",m),xC(e,"error")===0&&e.emit("error",T)}o(m,"onerror"),Y$(e,"error",m);function S(){e.removeListener("finish",E),O()}o(S,"onclose"),e.once("close",S);function E(){Pe("onfinish"),e.removeListener("close",S),O()}o(E,"onfinish"),e.once("finish",E);function O(){Pe("unpipe"),r.unpipe(e)}return o(O,"unpipe"),e.emit("pipe",r),n.flowing||(Pe("pipe resume"),r.resume()),e};function Q$(e){return function(){var t=e._readableState;Pe("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&xC(e,"data")&&(t.flowing=!0,Ag(e))}}o(Q$,"pipeOnDrain");Ke.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.head.data:r=t.buffer.concat(t.length),t.buffer.clear()):r=n4(e,t.buffer,t.decoder),r}o(UC,"fromList");function n4(e,t,r){var n;return es.length?s.length:e;if(a===s.length?i+=s:i+=s.slice(0,e),e-=a,e===0){a===s.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=s.slice(a));break}++n}return t.length-=n,i}o(i4,"copyFromBufferString");function s4(e,t){var r=Za.allocUnsafe(e),n=t.head,i=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var s=n.data,a=e>s.length?s.length:e;if(s.copy(r,r.length-e,0,a),e-=a,e===0){a===s.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=s.slice(a));break}++i}return t.length-=i,r}o(s4,"copyFromBuffer");function bg(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,Qs.nextTick(o4,t,e))}o(bg,"endReadable");function o4(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"))}o(o4,"endReadableNT");function WC(e,t){for(var r=0,n=e.length;r{"use strict";VC.exports=gn;var nl=Ki(),zC=Object.create(Gs());zC.inherits=Ks();zC.inherits(gn,nl);function a4(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";YC.exports=Qa;var HC=Ig(),kC=Object.create(Gs());kC.inherits=Ks();kC.inherits(Qa,HC);function Qa(e){if(!(this instanceof Qa))return new Qa(e);HC.call(this,e)}o(Qa,"PassThrough");Qa.prototype._transform=function(e,t,r){r(null,e)}});var KC=w((Et,il)=>{var Vr=require("stream");process.env.READABLE_STREAM==="disable"&&Vr?(il.exports=Vr,Et=il.exports=Vr.Readable,Et.Readable=Vr.Readable,Et.Writable=Vr.Writable,Et.Duplex=Vr.Duplex,Et.Transform=Vr.Transform,Et.PassThrough=Vr.PassThrough,Et.Stream=Vr):(Et=il.exports=Sg(),Et.Stream=Vr||Et,Et.Readable=Et,Et.Writable=mg(),Et.Duplex=Ki(),Et.Transform=Ig(),Et.PassThrough=GC())});var JC=w((mse,XC)=>{"use strict";var Bg=KC().Duplex,c4=require("util"),Hr=qr().Buffer;function Fe(e){if(!(this instanceof Fe))return new Fe(e);if(this._bufs=[],this.length=0,typeof e=="function"){this._callback=e;var t=o(function(n){this._callback&&(this._callback(n),this._callback=null)},"piper").bind(this);this.on("pipe",o(function(n){n.on("error",t)},"onPipe")),this.on("unpipe",o(function(n){n.removeListener("error",t)},"onUnpipe"))}else this.append(e);Bg.call(this)}o(Fe,"BufferList");c4.inherits(Fe,Bg);Fe.prototype._offset=o(function(t){var r=0,n=0,i;if(t===0)return[0,0];for(;nthis.length||t<0)){var r=this._offset(t);return this._bufs[r[0]][r[1]]}},"get");Fe.prototype.slice=o(function(t,r){return typeof t=="number"&&t<0&&(t+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,t,r)},"slice");Fe.prototype.copy=o(function(t,r,n,i){if((typeof n!="number"||n<0)&&(n=0),(typeof i!="number"||i>this.length)&&(i=this.length),n>=this.length||i<=0)return t||Hr.alloc(0);var s=!!t,a=this._offset(n),u=i-n,c=u,f=s&&r||0,h=a[1],l,d;if(n===0&&i==this.length){if(!s)return this._bufs.length===1?this._bufs[0]:Hr.concat(this._bufs,this.length);for(d=0;dl)this._bufs[d].copy(t,f,h),f+=l;else{this._bufs[d].copy(t,f,h,h+c),f+=l;break}c-=l,h&&(h=0)}return t.length>f?t.slice(0,f):t},"copy");Fe.prototype.shallowSlice=o(function(t,r){if(t=t||0,r=typeof r!="number"?this.length:r,t<0&&(t+=this.length),r<0&&(r+=this.length),t===r)return new Fe;var n=this._offset(t),i=this._offset(r),s=this._bufs.slice(n[0],i[0]+1);return i[1]==0?s.pop():s[s.length-1]=s[s.length-1].slice(0,i[1]),n[1]!=0&&(s[0]=s[0].slice(n[1])),new Fe(s)},"shallowSlice");Fe.prototype.toString=o(function(t,r,n){return this.slice(r,n).toString(t)},"toString");Fe.prototype.consume=o(function(t){if(t=Math.trunc(t),Number.isNaN(t)||t<=0)return this;for(;this._bufs.length;)if(t>=this._bufs[0].length)t-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(t),this.length-=t;break}return this},"consume");Fe.prototype.duplicate=o(function(){for(var t=0,r=new Fe;tthis.length?this.length:t;var n=this._offset(t),i=n[0],s=n[1];for(i;i=e.length){var c=a.indexOf(e,s);if(c!==-1)return this._reverseOffset([i,c]);s=a.length-e.length+1}else{var f=this._reverseOffset([i,s]);if(this._match(f,e))return f;s++}}s=0}return-1};Fe.prototype._match=function(e,t){if(this.length-e{"use strict";var f4=require("stream").Duplex,l4=JC(),ZC=V().MongoParseError,h4=un().decompress,QC=sr().Response,eA=xi().BinMsg,d4=V().MongoError,p4=We().opcodes.OP_COMPRESSED,tA=We().opcodes.OP_MSG,oi=We().MESSAGE_HEADER_SIZE,rA=We().COMPRESSION_DETAILS_SIZE,m4=We().opcodes,y4=un().compress,g4=un().compressorIDs,S4=un().uncompressibleCommands,w4=xi().Msg,O4=1024*1024*16*4,Rg=Symbol("buffer"),qg=class qg extends f4{constructor(t){t=t||{},super(t),this.bson=t.bson,this.maxBsonMessageSize=t.maxBsonMessageSize||O4,this[Rg]=new l4}_write(t,r,n){this[Rg].append(t),xg(this,n)}_read(){}writeCommand(t,r){if(!(r&&!!r.agreedCompressor)||!v4(t)){let u=t.toBin();this.push(Array.isArray(u)?Buffer.concat(u):u);return}let i=Buffer.concat(t.toBin()),s=i.slice(oi),a=i.readInt32LE(12);y4({options:r},s,(u,c)=>{if(u){r.cb(u,null);return}let f=Buffer.alloc(oi);f.writeInt32LE(oi+rA+c.length,0),f.writeInt32LE(t.requestId,4),f.writeInt32LE(0,8),f.writeInt32LE(m4.OP_COMPRESSED,12);let h=Buffer.alloc(rA);h.writeInt32LE(a,0),h.writeInt32LE(s.length,4),h.writeUInt8(g4[r.agreedCompressor],8),this.push(Buffer.concat([f,h,c]))})}};o(qg,"MessageStream");var Mg=qg;function v4(e){let t=e instanceof w4?e.command:e.query,r=Object.keys(t)[0];return!S4.has(r)}o(v4,"canCompress");function xg(e,t){let r=e[Rg];if(r.length<4){t();return}let n=r.readInt32LE(0);if(n<0){t(new ZC(`Invalid message size: ${n}`));return}if(n>e.maxBsonMessageSize){t(new ZC(`Invalid message size: ${n}, max allowed: ${e.maxBsonMessageSize}`));return}if(n>r.length){t();return}let i=r.slice(0,n);r.consume(n);let s={length:i.readInt32LE(0),requestId:i.readInt32LE(4),responseTo:i.readInt32LE(8),opCode:i.readInt32LE(12)},a=s.opCode===tA?eA:QC,u=e.responseOptions;if(s.opCode!==p4){let h=i.slice(oi);e.emit("message",new a(e.bson,i,s,h,u)),r.length>=4?xg(e,t):t();return}s.fromCompressed=!0,s.opCode=i.readInt32LE(oi),s.length=i.readInt32LE(oi+4);let c=i[oi+8],f=i.slice(oi+9);a=s.opCode===tA?eA:QC,h4(c,f,(h,l)=>{if(h){t(h);return}if(l.length!==s.length){t(new d4("Decompressing a compressed message from the server failed. The message is corrupt."));return}e.emit("message",new a(e.bson,i,s,l,u)),r.length>=4?xg(e,t):t()})}o(xg,"processIncomingData");nA.exports=Mg});var aA=w((wse,oA)=>{"use strict";var sA=Ri().parseServerType,E4=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"],Pg=class Pg{constructor(t,r){this.address=t,this.type=sA(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=r&&r.compression&&Array.isArray(r.compression.compressors)?r.compression.compressors:[]}receiveResponse(t){this.type=sA(t),E4.forEach(r=>{typeof t[r]<"u"&&(this[r]=t[r])}),t.compression&&(this.compressor=this.compressors.filter(r=>t.compression.indexOf(r)!==-1)[0])}};o(Pg,"StreamDescription");var Dg=Pg;oA.exports={StreamDescription:Dg}});var zg=w((vse,lA)=>{"use strict";var _4=require("events"),T4=iA(),uA=V().MongoError,N4=V().MongoNetworkError,b4=V().MongoNetworkTimeoutError,C4=V().MongoWriteConcernError,A4=tf(),I4=aA().StreamDescription,Xi=Ny(),sl=Am(),B4=Kn().updateSessionFromResponse,R4=re().uuidV4,jg=b().now,M4=b().calculateDurationInMs,ai=Symbol("stream"),Sn=Symbol("queue"),eo=Symbol("messageStream"),cA=Symbol("generation"),Lg=Symbol("lastUseTime"),Fg=Symbol("clusterTime"),ui=Symbol("description"),fA=Symbol("ismaster"),Ug=Symbol("autoEncrypter"),$g=class $g extends _4{constructor(t,r){super(r),this.id=r.id,this.address=q4(t),this.bson=r.bson,this.socketTimeout=typeof r.socketTimeout=="number"?r.socketTimeout:0,this.host=r.host||"localhost",this.port=r.port||27017,this.monitorCommands=typeof r.monitorCommands=="boolean"?r.monitorCommands:!1,this.serverApi=r.serverApi,this.closed=!1,this.destroyed=!1,this[ui]=new I4(this.address,r),this[cA]=r.generation,this[Lg]=jg(),r.autoEncrypter&&(this[Ug]=r.autoEncrypter),this[Sn]=new Map,this[eo]=new T4(r),this[eo].on("message",x4(this)),this[ai]=t,t.on("error",()=>{}),this[eo].on("error",n=>this.handleIssue({destroy:n})),t.on("close",()=>this.handleIssue({isClose:!0})),t.on("timeout",()=>this.handleIssue({isTimeout:!0,destroy:!0})),t.pipe(this[eo]),this[eo].pipe(t)}get description(){return this[ui]}get ismaster(){return this[fA]}set ismaster(t){this[ui].receiveResponse(t),this[fA]=t}get generation(){return this[cA]||0}get idleTime(){return M4(this[Lg])}get clusterTime(){return this[Fg]}get stream(){return this[ai]}markAvailable(){this[Lg]=jg()}handleIssue(t){if(!this.closed){t.destroy&&this[ai].destroy(typeof t.destroy=="boolean"?void 0:t.destroy),this.closed=!0;for(let r of this[Sn]){let n=r[1];t.isTimeout?n.cb(new b4(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:this.ismaster==null})):t.isClose?n.cb(new N4(`connection ${this.id} to ${this.address} closed`)):n.cb(typeof t.destroy=="boolean"?void 0:t.destroy)}this[Sn].clear(),this.emit("close")}}destroy(t,r){if(typeof t=="function"&&(r=t,t={}),t=Object.assign({force:!1},t),this[ai]==null||this.destroyed){this.destroyed=!0,typeof r=="function"&&r();return}if(t.force){this[ai].destroy(),this.destroyed=!0,typeof r=="function"&&r();return}this[ai].end(n=>{this.destroyed=!0,typeof r=="function"&&r(n)})}applyApiVersion(t){return this.serverApi&&(t.serverApi=this.serverApi),t}command(t,r,n,i){typeof n=="function"&&(i=n,n={}),Xi.command(Ji(this),t,r,this.applyApiVersion(n),i)}query(t,r,n,i,s){Xi.query(Ji(this),t,r,n,this.applyApiVersion(i),s)}getMore(t,r,n,i,s){Xi.getMore(Ji(this),t,r,n,this.applyApiVersion(i),s)}killCursors(t,r,n){Xi.killCursors(Ji(this),t,r,this.applyApiVersion({}),n)}insert(t,r,n,i){Xi.insert(Ji(this),t,r,this.applyApiVersion(n),i)}update(t,r,n,i){Xi.update(Ji(this),t,r,this.applyApiVersion(n),i)}remove(t,r,n,i){Xi.remove(Ji(this),t,r,this.applyApiVersion(n),i)}};o($g,"Connection");var Wg=$g;function Ji(e){let t={description:e.description,clusterTime:e[Fg],s:{bson:e.bson,pool:{write:D4.bind(e),isConnected:()=>!0}}};return e[Ug]&&(t.autoEncrypter=e[Ug]),t}o(Ji,"makeServerTrampoline");function x4(e){return o(function(r){if(e.emit("message",r),!e[Sn].has(r.responseTo))return;let n=e[Sn].get(r.responseTo),i=n.cb;e[Sn].delete(r.responseTo),r.moreToCome?e[Sn].set(r.requestId,n):n.socketTimeoutOverride&&e[ai].setTimeout(e.socketTimeout);try{r.parse(n)}catch(s){i(new uA(s));return}if(r.documents[0]){let s=r.documents[0],a=n.session;if(a&&B4(a,s),s.$clusterTime&&(e[Fg]=s.$clusterTime,e.emit("clusterTimeReceived",s.$clusterTime)),n.command){if(s.writeConcernError){i(new C4(s.writeConcernError,s));return}if(s.ok===0||s.$err||s.errmsg||s.code){i(new uA(s));return}}}i(void 0,new A4(n.fullResult?r:r.documents[0],e,r))},"messageHandler")}o(x4,"messageHandler");function q4(e){return typeof e.address=="function"?`${e.remoteAddress}:${e.remotePort}`:R4().toString("hex")}o(q4,"streamIdentifier");function D4(e,t,r){typeof t=="function"&&(r=t),t=t||{};let n={requestId:e.requestId,cb:r,session:t.session,fullResult:typeof t.fullResult=="boolean"?t.fullResult:!1,noResponse:typeof t.noResponse=="boolean"?t.noResponse:!1,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:typeof t.promoteLongs=="boolean"?t.promoteLongs:!0,promoteValues:typeof t.promoteValues=="boolean"?t.promoteValues:!0,promoteBuffers:typeof t.promoteBuffers=="boolean"?t.promoteBuffers:!1,bsonRegExp:typeof t.bsonRegExp=="boolean"?t.bsonRegExp:!1,raw:typeof t.raw=="boolean"?t.raw:!1};this[ui]&&this[ui].compressor&&(n.agreedCompressor=this[ui].compressor,this[ui].zlibCompressionLevel&&(n.zlibCompressionLevel=this[ui].zlibCompressionLevel)),typeof t.socketTimeout=="number"&&(n.socketTimeoutOverride=!0,this[ai].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new sl.CommandStartedEvent(this,e)),n.started=jg(),n.cb=(i,s)=>{i?this.emit("commandFailed",new sl.CommandFailedEvent(this,e,i,n.started)):s&&s.result&&(s.result.ok===0||s.result.$err)?this.emit("commandFailed",new sl.CommandFailedEvent(this,e,s.result,n.started)):this.emit("commandSucceeded",new sl.CommandSucceededEvent(this,e,s,n.started)),typeof r=="function"&&r(i,s)}),n.noResponse||this[Sn].set(n.requestId,n);try{this[eo].writeCommand(e,n)}catch(i){if(!n.noResponse){this[Sn].delete(n.requestId),n.cb(i);return}}n.noResponse&&n.cb()}o(D4,"write");lA.exports={Connection:Wg}});var pA=w((_se,dA)=>{"use strict";var hA=V().MongoError,kg=class kg extends hA{constructor(t){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=t.address}};o(kg,"PoolClosedError");var Vg=kg,Yg=class Yg extends hA{constructor(t){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=t.address}};o(Yg,"WaitQueueTimeoutError");var Hg=Yg;dA.exports={PoolClosedError:Vg,WaitQueueTimeoutError:Hg}});var eu=w((Nse,mA)=>{"use strict";var iS=class iS{constructor(t){this.time=new Date,this.address=t.address}};o(iS,"ConnectionPoolMonitoringEvent");var _r=iS,sS=class sS extends _r{constructor(t){super(t),this.options=t.options}};o(sS,"ConnectionPoolCreatedEvent");var Gg=sS,oS=class oS extends _r{constructor(t){super(t)}};o(oS,"ConnectionPoolClosedEvent");var Kg=oS,aS=class aS extends _r{constructor(t,r){super(t),this.connectionId=r.id}};o(aS,"ConnectionCreatedEvent");var Xg=aS,uS=class uS extends _r{constructor(t,r){super(t),this.connectionId=r.id}};o(uS,"ConnectionReadyEvent");var Jg=uS,cS=class cS extends _r{constructor(t,r,n){super(t),this.connectionId=r.id,this.reason=n||"unknown"}};o(cS,"ConnectionClosedEvent");var Zg=cS,fS=class fS extends _r{constructor(t){super(t)}};o(fS,"ConnectionCheckOutStartedEvent");var Qg=fS,lS=class lS extends _r{constructor(t,r){super(t),this.reason=r}};o(lS,"ConnectionCheckOutFailedEvent");var eS=lS,hS=class hS extends _r{constructor(t,r){super(t),this.connectionId=r.id}};o(hS,"ConnectionCheckedOutEvent");var tS=hS,dS=class dS extends _r{constructor(t,r){super(t),this.connectionId=r.id}};o(dS,"ConnectionCheckedInEvent");var rS=dS,pS=class pS extends _r{constructor(t){super(t)}};o(pS,"ConnectionPoolClearedEvent");var nS=pS,P4=["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];mA.exports={CMAP_EVENT_NAMES:P4,ConnectionPoolCreatedEvent:Gg,ConnectionPoolClosedEvent:Kg,ConnectionCreatedEvent:Xg,ConnectionReadyEvent:Jg,ConnectionClosedEvent:Zg,ConnectionCheckOutStartedEvent:Qg,ConnectionCheckOutFailedEvent:eS,ConnectionCheckedOutEvent:tS,ConnectionCheckedInEvent:rS,ConnectionPoolClearedEvent:nS}});var CA=w((Cse,bA)=>{"use strict";var yA=Hf(),gA=require("events").EventEmitter,L4=yr(),j4=b().makeCounter,U4=V().MongoError,W4=zg().Connection,F4=re().eachAsync,$4=mf(),z4=re().relayEvents,wA=pA(),V4=wA.PoolClosedError,H4=wA.WaitQueueTimeoutError,kr=eu(),k4=kr.ConnectionPoolCreatedEvent,Y4=kr.ConnectionPoolClosedEvent,G4=kr.ConnectionCreatedEvent,K4=kr.ConnectionReadyEvent,OA=kr.ConnectionClosedEvent,X4=kr.ConnectionCheckOutStartedEvent,mS=kr.ConnectionCheckOutFailedEvent,SA=kr.ConnectionCheckedOutEvent,J4=kr.ConnectionCheckedInEvent,Z4=kr.ConnectionPoolClearedEvent,vA=Symbol("logger"),wn=Symbol("connections"),ru=Symbol("permits"),ol=Symbol("minPoolSizeTimer"),tu=Symbol("generation"),al=Symbol("connectionCounter"),ul=Symbol("cancellationToken"),ci=Symbol("waitQueue"),cl=Symbol("cancelled"),Q4=new Set(["ssl","bson","connectionType","serverApi","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function ez(e,t){let r=Array.from(Q4).reduce((n,i)=>(Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]),n),{});return Object.freeze(Object.assign({},t,r))}o(ez,"resolveOptions");var SS=class SS extends gA{constructor(t){if(super(),t=t||{},this.closed=!1,this.options=ez(t,{connectionType:W4,maxPoolSize:typeof t.maxPoolSize=="number"?t.maxPoolSize:100,minPoolSize:typeof t.minPoolSize=="number"?t.minPoolSize:0,maxIdleTimeMS:typeof t.maxIdleTimeMS=="number"?t.maxIdleTimeMS:0,waitQueueTimeoutMS:typeof t.waitQueueTimeoutMS=="number"?t.waitQueueTimeoutMS:0,autoEncrypter:t.autoEncrypter,metadata:t.metadata,useUnifiedTopology:t.useUnifiedTopology}),t.minSize>t.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maximum pool size");this[vA]=L4("ConnectionPool",t),this[wn]=new yA,this[ru]=this.options.maxPoolSize,this[ol]=void 0,this[tu]=0,this[al]=j4(1),this[ul]=new gA,this[ul].setMaxListeners(1/0),this[ci]=new yA,process.nextTick(()=>{this.emit("connectionPoolCreated",new k4(this)),EA(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[tu]}get totalConnectionCount(){return this[wn].length+(this.options.maxPoolSize-this[ru])}get availableConnectionCount(){return this[wn].length}get waitQueueSize(){return this[ci].length}checkOut(t){if(this.emit("connectionCheckOutStarted",new X4(this)),this.closed){this.emit("connectionCheckOutFailed",new mS(this,"poolClosed")),t(new V4(this));return}let r={callback:t},n=this,i=this.options.waitQueueTimeoutMS;i&&(r.timer=setTimeout(()=>{r[cl]=!0,r.timer=void 0,n.emit("connectionCheckOutFailed",new mS(n,"timeout")),r.callback(new H4(n))},i)),this[ci].push(r),process.nextTick(()=>gS(this))}checkIn(t){let r=this.closed,n=_A(this,t),i=!!(r||n||t.closed);if(i||(t.markAvailable(),this[wn].push(t)),this.emit("connectionCheckedIn",new J4(this,t)),i){let s=t.closed?"error":r?"poolClosed":"stale";NA(this,t,s)}process.nextTick(()=>gS(this))}clear(){this[tu]+=1,this.emit("connectionPoolCleared",new Z4(this))}close(t,r){if(typeof t=="function"&&(r=t),t=Object.assign({force:!1},t),this.closed)return r();for(this[ul].emit("cancel");this.waitQueueSize;){let n=this[ci].pop();clearTimeout(n.timer),n[cl]||n.callback(new U4("connection pool closed"))}this[ol]&&clearTimeout(this[ol]),typeof this[al].return=="function"&&this[al].return(),this.closed=!0,F4(this[wn].toArray(),(n,i)=>{this.emit("connectionClosed",new OA(this,n,"poolClosed")),n.destroy(t,i)},n=>{this[wn].clear(),this.emit("connectionPoolClosed",new Y4(this)),r(n)})}withConnection(t,r){this.checkOut((n,i)=>{t(n,i,(s,a)=>{typeof r=="function"&&(s?r(s):r(void 0,a)),i&&this.checkIn(i)})})}};o(SS,"ConnectionPool");var yS=SS;function EA(e){if(e.closed||e.options.minPoolSize===0)return;let t=e.options.minPoolSize;for(let r=e.totalConnectionCount;rEA(e),10)}o(EA,"ensureMinPoolSize");function _A(e,t){return t.generation!==e[tu]}o(_A,"connectionIsStale");function tz(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}o(tz,"connectionIsIdle");function TA(e,t){let r=Object.assign({id:e[al].next().value,generation:e[tu]},e.options);e[ru]--,$4(r,e[ul],(n,i)=>{if(n){e[ru]++,e[vA].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),typeof t=="function"&&t(n);return}if(e.closed){i.destroy({force:!0});return}if(z4(i,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new G4(e,i)),i.markAvailable(),e.emit("connectionReady",new K4(e,i)),typeof t=="function"){t(void 0,i);return}e[wn].push(i),process.nextTick(()=>gS(e))})}o(TA,"createConnection");function NA(e,t,r){e.emit("connectionClosed",new OA(e,t,r)),e[ru]++,process.nextTick(()=>t.destroy())}o(NA,"destroyConnection");function gS(e){if(e.closed)return;for(;e.waitQueueSize;){let r=e[ci].peekFront();if(r[cl]){e[ci].shift();continue}if(!e.availableConnectionCount)break;let n=e[wn].shift(),i=_A(e,n),s=tz(e,n);if(!i&&!s&&!n.closed){e.emit("connectionCheckedOut",new SA(e,n)),clearTimeout(r.timer),e[ci].shift(),r.callback(void 0,n);return}let a=n.closed?"error":i?"stale":"idle";NA(e,n,a)}let t=e.options.maxPoolSize;if(e.waitQueueSize&&(t<=0||e.totalConnectionCount{let i=e[ci].shift();if(i==null||i[cl]){r==null&&e[wn].push(n);return}r?e.emit("connectionCheckOutFailed",new mS(e,r)):e.emit("connectionCheckedOut",new SA(e,n)),clearTimeout(i.timer),i.callback(r,n)});return}}o(gS,"processWaitQueue");bA.exports={ConnectionPool:yS}});var jA=w((Ise,LA)=>{"use strict";var rz=bt().ServerType,AA=require("events"),qA=mf(),nz=zg().Connection,DA=bt(),iz=re().makeStateMachine,sz=V().MongoNetworkError,oz=mt().retrieveBSON(),IA=b().makeInterruptableAsyncInterval,fl=b().calculateDurationInMs,wS=b().now,ES=sg(),BA=ES.ServerHeartbeatStartedEvent,RA=ES.ServerHeartbeatSucceededEvent,az=ES.ServerHeartbeatFailedEvent,iu=Symbol("server"),Wt=Symbol("monitorId"),ot=Symbol("connection"),Zi=Symbol("cancellationToken"),On=Symbol("rttPinger"),nu=Symbol("roundTripTime"),li=DA.STATE_CLOSED,fi=DA.STATE_CLOSING,to="idle",ro="monitoring",no=iz({[fi]:[fi,to,li],[li]:[li,ro],[to]:[to,ro,fi],[ro]:[ro,to,fi]}),uz=new Set([fi,li,ro]);function su(e){return e.s.state===li||e.s.state===fi}o(su,"isInCloseState");var _S=class _S extends AA{constructor(t,r){super(r),this[iu]=t,this[ot]=void 0,this[Zi]=new AA,this[Zi].setMaxListeners(1/0),this[Wt]=null,this.s={state:li},this.address=t.description.address,this.options=Object.freeze({connectTimeoutMS:typeof r.connectionTimeout=="number"?r.connectionTimeout:typeof r.connectTimeoutMS=="number"?r.connectTimeoutMS:1e4,heartbeatFrequencyMS:typeof r.heartbeatFrequencyMS=="number"?r.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:typeof r.minHeartbeatFrequencyMS=="number"?r.minHeartbeatFrequencyMS:500,useUnifiedTopology:r.useUnifiedTopology});let n=Object.assign({id:"",host:t.description.host,port:t.description.port,bson:t.s.bson,connectionType:nz},t.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0,bsonRegExp:!0});delete n.credentials,delete n.autoEncrypter,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==li)return;let t=this.options.heartbeatFrequencyMS,r=this.options.minHeartbeatFrequencyMS;this[Wt]=IA(xA(this),{interval:t,minInterval:r,immediate:!0})}requestCheck(){uz.has(this.s.state)||this[Wt].wake()}reset(){let t=this[iu].description.topologyVersion;if(su(this)||t==null)return;no(this,fi),MA(this),no(this,to);let r=this.options.heartbeatFrequencyMS,n=this.options.minHeartbeatFrequencyMS;this[Wt]=IA(xA(this),{interval:r,minInterval:n})}close(){su(this)||(no(this,fi),MA(this),this.emit("close"),no(this,li))}};o(_S,"Monitor");var OS=_S;function MA(e){e[Wt]&&(e[Wt].stop(),e[Wt]=null),e[On]&&(e[On].close(),e[On]=void 0),e[Zi].emit("cancel"),e[Wt]&&(clearTimeout(e[Wt]),e[Wt]=void 0),e[ot]&&e[ot].destroy({force:!0})}o(MA,"resetMonitorState");function cz(e,t){let r=wS();e.emit("serverHeartbeatStarted",new BA(e.address));function n(i){e[ot]&&(e[ot].destroy({force:!0}),e[ot]=void 0),e.emit("serverHeartbeatFailed",new az(fl(r),i,e.address)),e.emit("resetServer",i),e.emit("resetConnectionPool"),t(i)}if(o(n,"failureHandler"),e[ot]!=null&&!e[ot].closed){let i=e.options.connectTimeoutMS,s=e.options.heartbeatFrequencyMS,a=e[iu].description.topologyVersion,u=a!=null,c=e[ot].serverApi,f=e[ot].helloOk,h={[c||f?"hello":"ismaster"]:!0};f&&(h.helloOk=f);let l={socketTimeout:i};u&&(h.maxAwaitTimeMS=s,h.topologyVersion=fz(a),i&&(l.socketTimeout=i+s),l.exhaustAllowed=!0,e[On]==null&&(e[On]=new vS(e[Zi],e.connectOptions))),e[ot].command("admin.$cmd",h,l,(d,m)=>{if(d){n(d);return}let S=m.result,E=e[On];"isWritablePrimary"in S&&(S.ismaster=S.isWritablePrimary);let O=u&&E?E.roundTripTime:fl(r);e.emit("serverHeartbeatSucceeded",new RA(O,S,e.address)),u&&S.topologyVersion?(e.emit("serverHeartbeatStarted",new BA(e.address)),r=wS()):(e[On]&&(e[On].close(),e[On]=void 0),t(void 0,S))});return}qA(e.connectOptions,e[Zi],(i,s)=>{if(s&&su(e)){s.destroy({force:!0});return}if(i){e[ot]=void 0,i instanceof sz||e.emit("resetConnectionPool"),n(i);return}e[ot]=s,e.emit("serverHeartbeatSucceeded",new RA(fl(r),s.ismaster,e.address)),t(void 0,s.ismaster)})}o(cz,"checkServer");function xA(e){return t=>{no(e,ro);function r(){su(e)||no(e,to),t()}o(r,"done"),process.nextTick(()=>e.emit("monitoring",e[iu])),cz(e,(n,i)=>{if(n&&e[iu].description.type===rz.Unknown)return e.emit("resetServer",n),r();i&&i.topologyVersion&&setTimeout(()=>{su(e)||e[Wt].wake()}),r()})}}o(xA,"monitorServer");function fz(e){return{processId:e.processId,counter:oz.Long.fromNumber(e.counter)}}o(fz,"makeTopologyVersion");var TS=class TS{constructor(t,r){this[ot]=null,this[Zi]=t,this[nu]=0,this.closed=!1;let n=r.heartbeatFrequencyMS;this[Wt]=setTimeout(()=>PA(this,r),n)}get roundTripTime(){return this[nu]}close(){this.closed=!0,clearTimeout(this[Wt]),this[Wt]=void 0,this[ot]&&this[ot].destroy({force:!0})}};o(TS,"RTTPinger");var vS=TS;function PA(e,t){let r=wS(),n=e[Zi],i=t.heartbeatFrequencyMS;if(e.closed)return;function s(a){if(e.closed){a.destroy({force:!0});return}e[ot]==null&&(e[ot]=a),e[nu]=fl(r),e[Wt]=setTimeout(()=>PA(e,t),i)}if(o(s,"measureAndReschedule"),e[ot]==null){qA(t,n,(a,u)=>{if(a){e[ot]=void 0,e[nu]=0;return}s(u)});return}e[ot].command("admin.$cmd",{ismaster:1},a=>{if(a){e[ot]=void 0,e[nu]=0;return}s()})}o(PA,"measureRoundTripTime");LA.exports={Monitor:OS}});var YA=w((Rse,kA)=>{"use strict";var lz=require("events"),hz=CA().ConnectionPool,dz=eu().CMAP_EVENT_NAMES,En=V().MongoError,UA=re().relayEvents,Ft=mt().retrieveBSON(),pz=yr(),FA=Ri().ServerDescription,mz=Ri().compareTopologyVersion,yz=wt(),gz=jA().Monitor,$A=V().MongoNetworkError,zA=V().MongoNetworkTimeoutError,VA=re().collationNotSupported,Sz=mt().debugOptions,wz=V().isSDAMUnrecoverableError,Oz=V().isRetryableWriteError,vz=V().isNodeShuttingDownError,Ez=V().isNetworkErrorBeforeHandshake,bS=re().maxWireVersion,_z=re().makeStateMachine,Tz=Di().extractCommand,uu=bt(),Nz=uu.ServerType,bz=js().isTransactionCommand,Cz=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"],Yr=uu.STATE_CLOSING,Xt=uu.STATE_CLOSED,au=uu.STATE_CONNECTING,hl=uu.STATE_CONNECTED,ll=_z({[Xt]:[Xt,au],[au]:[au,Yr,hl,Xt],[hl]:[hl,Yr,Xt],[Yr]:[Yr,Xt]}),vn=Symbol("monitor"),CS=class CS extends lz{constructor(t,r,n){super(),this.s={description:t,options:r,logger:pz("Server",r),bson:r.bson||new Ft([Ft.Binary,Ft.Code,Ft.DBRef,Ft.Decimal128,Ft.Double,Ft.Int32,Ft.Long,Ft.Map,Ft.MaxKey,Ft.MinKey,Ft.ObjectId,Ft.BSONRegExp,Ft.Symbol,Ft.Timestamp]),state:Xt,credentials:r.credentials,topology:n},this.serverApi=r.serverApi;let i=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},r);this.s.pool=new hz(i),UA(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(dz)),this.s.pool.on("clusterTimeReceived",s=>{this.clusterTime=s}),this[vn]=new gz(this,this.s.options),UA(this[vn],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[vn].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[vn].on("resetServer",s=>hi(this,s)),this[vn].on("serverHeartbeatSucceeded",s=>{this.emit("descriptionReceived",new FA(this.description.address,s.reply,{roundTripTime:Az(this.description.roundTripTime,s.duration)})),this.s.state===au&&(ll(this,hl),this.emit("connect",this))})}get description(){return this.s.description}get supportsRetryableWrites(){return HA(this)}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===Xt&&(ll(this,au),this[vn].connect())}destroy(t,r){if(typeof t=="function"&&(r=t,t={}),t=Object.assign({},{force:!1},t),this.s.state===Xt){typeof r=="function"&&r();return}ll(this,Yr),this[vn].close(),this.s.pool.close(t,n=>{ll(this,Xt),this.emit("closed"),typeof r=="function"&&r(n)})}requestCheck(){this[vn].requestCheck()}command(t,r,n,i){if(typeof n=="function"&&(i=n,n={},n=n||{}),n.serverApi=this.serverApi,this.s.state===Yr||this.s.state===Xt){i(new En("server is closed"));return}let s=Iz(this,n);if(s)return i(s);if(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()){let a=Tz(r);this.s.logger.debug(`executing command [${JSON.stringify({ns:t,cmd:a.shouldRedact?`${a.name} details REDACTED`:r,options:Sz(Cz,n)})}] against ${this.name}`)}if(VA(this,r)){i(new En(`server ${this.name} does not support collation`));return}this.s.pool.withConnection((a,u,c)=>{if(a)return hi(this,a),c(a);u.command(t,r,n,ou(this,u,r,n,c))},i)}query(t,r,n,i,s){if(this.s.state===Yr||this.s.state===Xt){s(new En("server is closed"));return}this.s.pool.withConnection((a,u,c)=>{if(a)return hi(this,a),c(a);u.query(t,r,n,i,ou(this,u,r,i,c))},s)}getMore(t,r,n,i,s){if(this.s.state===Yr||this.s.state===Xt){s(new En("server is closed"));return}this.s.pool.withConnection((a,u,c)=>{if(a)return hi(this,a),c(a);u.getMore(t,r,n,i,ou(this,u,null,i,c))},s)}killCursors(t,r,n){if(this.s.state===Yr||this.s.state===Xt){typeof n=="function"&&n(new En("server is closed"));return}this.s.pool.withConnection((i,s,a)=>{if(i)return hi(this,i),a(i);s.killCursors(t,r,ou(this,s,null,void 0,a))},n)}insert(t,r,n,i){NS({server:this,op:"insert",ns:t,ops:r},n,i)}update(t,r,n,i){NS({server:this,op:"update",ns:t,ops:r},n,i)}remove(t,r,n,i){NS({server:this,op:"remove",ns:t,ops:r},n,i)}};o(CS,"Server");var dl=CS;Object.defineProperty(dl.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}});function HA(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==Nz.Standalone}o(HA,"supportsRetryableWrites");function Az(e,t){if(e===-1)return t;let r=.2;return r*t+(1-r)*e}o(Az,"calculateRoundTripTime");function Iz(e,t){if(t.readPreference&&!(t.readPreference instanceof yz))return new En("readPreference must be an instance of ReadPreference")}o(Iz,"basicReadValidations");function NS(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.server,i=e.op,s=e.ns,a=Array.isArray(e.ops)?e.ops:[e.ops];if(n.s.state===Yr||n.s.state===Xt){r(new En("server is closed"));return}if(VA(n,t)){r(new En(`server ${n.name} does not support collation`));return}if((t.writeConcern&&t.writeConcern.w===0||bS(n)<5)&&(i==="update"||i==="remove")&&a.find(c=>c.hint)){r(new En(`servers < 3.4 do not support hint on ${i}`));return}n.s.pool.withConnection((c,f,h)=>{if(c)return hi(n,c),h(c);f[i](s,a,t,ou(n,f,a,t,h))},r)}o(NS,"executeWriteOperation");function hi(e,t){t instanceof $A&&!(t instanceof zA)&&e[vn].reset(),e.emit("descriptionReceived",new FA(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}o(hi,"markServerUnknown");function Bz(e,t){return t.generation!==e.generation}o(Bz,"connectionIsStale");function Rz(e,t){let r=t.topologyVersion,n=e.description.topologyVersion;return mz(n,r)<0}o(Rz,"shouldHandleStateChangeError");function WA(e,t){return e&&e.inTransaction()&&!bz(t)}o(WA,"inActiveTransaction");function ou(e,t,r,n,i){let s=n&&n.session;return o(function(u,c){u&&!Bz(e.s.pool,t)&&(u instanceof $A?(s&&!s.hasEnded&&(s.serverSession.isDirty=!0),HA(e)&&!WA(s,r)&&u.addErrorLabel("RetryableWriteError"),(!(u instanceof zA)||Ez(u))&&(hi(e,u),e.s.pool.clear())):(bS(e)<9&&Oz(u)&&!WA(s,r)&&u.addErrorLabel("RetryableWriteError"),wz(u)&&Rz(e,u)&&((bS(e)<=7||vz(u))&&e.s.pool.clear(),hi(e,u),process.nextTick(()=>e.requestCheck())))),i(u,c)},"handleOperationResult")}o(ou,"makeOperationHandler");kA.exports={Server:dl}});var GA=w((xse,IS)=>{"use strict";var Mz=yr(),xz=require("events").EventEmitter,qz=require("dns");function Dz(e,t){let r=/^.*?\./,n=`.${e.replace(r,"")}`,i=`.${t.replace(r,"")}`;return n.endsWith(i)}o(Dz,"matchesParentDomain");var BS=class BS{constructor(t){this.srvRecords=t}addresses(){return new Set(this.srvRecords.map(t=>`${t.name}:${t.port}`))}};o(BS,"SrvPollingEvent");var pl=BS,RS=class RS extends xz{constructor(t){if(super(),!t||!t.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=t.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=t.heartbeatFrequencyMS||1e4,this.logger=Mz("srvPoller",t),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(t){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new pl(t))}failure(t,r){this.logger.warn(t,r),this.haMode=!0,this.schedule()}parentDomainMismatch(t){this.logger.warn(`parent domain mismatch on SRV record (${t.name}:${t.port})`,t)}_poll(){let t=this.generation;qz.resolveSrv(this.srvAddress,(r,n)=>{if(t!==this.generation)return;if(r){this.failure("DNS error",r);return}let i=[];if(n.forEach(s=>{Dz(s.name,this.srvHost)?i.push(s):this.parentDomainMismatch(s)}),!i.length){this.failure("No valid addresses found at host");return}this.success(i)})}};o(RS,"SrvPoller");var AS=RS;IS.exports.SrvPollingEvent=pl;IS.exports.SrvPoller=AS});var JA=w((Dse,XA)=>{"use strict";var fu=bt().ServerType,cu=bt().TopologyType,ml=wt(),MS=V().MongoError,Pz=1e4,KA=90;function Lz(){return function(e,t){return xS(e,t.filter(r=>r.isWritable))}}o(Lz,"writableServerSelector");function jz(e,t,r){if(e.maxStalenessSeconds==null||e.maxStalenessSeconds<0)return r;let n=e.maxStalenessSeconds,i=(t.heartbeatFrequencyMS+Pz)/1e3;if(n((u.lastUpdateTime-u.lastWriteDate-(s.lastUpdateTime-s.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&a.push(u),a),[])}if(t.type===cu.ReplicaSetNoPrimary){if(r.length===0)return r;let s=r.reduce((a,u)=>u.lastWriteDate>a.lastWriteDate?u:a);return r.reduce((a,u)=>((s.lastWriteDate-u.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&a.push(u),a),[])}return r}o(jz,"maxStalenessReducer");function Uz(e,t){let r=Object.keys(e),n=Object.keys(t);for(let i=0;i(Uz(n,a.tags)&&s.push(a),s),[]);if(i.length)return i}return[]}o(Wz,"tagSetReducer");function xS(e,t){let r=t.reduce((i,s)=>i===-1?s.roundTripTime:Math.min(s.roundTripTime,i),-1),n=r+e.localThresholdMS;return t.reduce((i,s)=>(s.roundTripTime<=n&&s.roundTripTime>=r&&i.push(s),i),[])}o(xS,"latencyWindowReducer");function yl(e){return e.type===fu.RSPrimary}o(yl,"primaryFilter");function Fz(e){return e.type===fu.RSSecondary}o(Fz,"secondaryFilter");function $z(e){return e.type===fu.RSSecondary||e.type===fu.RSPrimary}o($z,"nearestFilter");function zz(e){return e.type!==fu.Unknown}o(zz,"knownFilter");function Vz(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,r){let n=t.commonWireVersion;if(n&&e.minWireVersion&&e.minWireVersion>n)throw new MS(`Minimum wire version '${e.minWireVersion}' required, but found '${n}'`);if(t.type===cu.Unknown)return[];if(t.type===cu.Single||t.type===cu.Sharded)return xS(t,r.filter(zz));let i=e.mode;if(i===ml.PRIMARY)return r.filter(yl);if(i===ml.PRIMARY_PREFERRED){let u=r.filter(yl);if(u.length)return u}let s=i===ml.NEAREST?$z:Fz,a=xS(t,Wz(e,jz(e,t,r.filter(s))));return i===ml.SECONDARY_PREFERRED&&a.length===0?r.filter(yl):a}}o(Vz,"readPreferenceServerSelector");XA.exports={writableServerSelector:Lz,readPreferenceServerSelector:Vz}});var uI=w((Lse,aI)=>{"use strict";var Hz=Hf(),kz=require("events"),Yz=Ri().ServerDescription,Gz=bt().ServerType,ZA=sm().TopologyDescription,_n=bt().TopologyType,di=sg(),Kz=YA().Server,Xz=re().relayEvents,Pr=wt(),Jz=Sr().CoreCursor,Zz=require("util").deprecate,qt=mt().retrieveBSON(),Qz=rt().createCompressionInfo,eV=Kn().ClientSession,vl=V().MongoError,tV=V().MongoServerSelectionError,rV=rt().resolveClusterTime,nV=GA().SrvPoller,iV=rt().getMMAPError,sV=re().makeStateMachine,oV=re().eachAsync,aV=b().emitDeprecationWarning,uV=Kn().ServerSessionPool,cV=re().makeClientMetadata,fV=eu().CMAP_EVENT_NAMES,lV=Ri().compareTopologyVersion,hV=b().emitWarning,Qi=bt(),dV=Qi.drainTimerQueue,pV=Qi.clearAndRemoveTimerFrom,eI=JA(),gl=eI.readPreferenceServerSelector,mV=eI.writableServerSelector,yV=0,tI=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(fV),gV=["connect","descriptionReceived","close","ended"],io=Qi.STATE_CLOSING,Kr=Qi.STATE_CLOSED,wl=Qi.STATE_CONNECTING,so=Qi.STATE_CONNECTED,Sl=sV({[Kr]:[Kr,wl],[wl]:[wl,io,so,Kr],[so]:[so,io,Kr],[io]:[io,Kr]}),SV=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]),qS=Symbol("cancelled"),Gr=Symbol("waitQueue"),DS=class DS extends kz{constructor(t,r){super(),typeof r>"u"&&typeof t!="string"&&(r=t,t=[],r.host&&t.push({host:r.host,port:r.port})),t=t||[],typeof t=="string"&&(t=EV(t)),r=Object.assign({},Qi.TOPOLOGY_DEFAULTS,r),r=Object.freeze(Object.assign(r,{metadata:cV(r),compression:{compressors:Qz(r)}})),SV.forEach(a=>{r[a]&&aV(`The option \`${a}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});let n=_V(t,r),i=yV++,s=t.reduce((a,u)=>{u.domain_socket&&(u.host=u.domain_socket);let c=u.port?`${u.host}:${u.port}`:`${u.host}:27017`;return a.set(c,new Yz(c)),a},new Map);this[Gr]=new Hz,this.s={id:i,options:r,seedlist:t,state:Kr,description:new ZA(n,s,r.replicaSet,null,null,null,r),serverSelectionTimeoutMS:r.serverSelectionTimeoutMS,heartbeatFrequencyMS:r.heartbeatFrequencyMS,minHeartbeatFrequencyMS:r.minHeartbeatFrequencyMS,Cursor:r.cursorFactory||Jz,bson:r.bson||new qt([qt.Binary,qt.Code,qt.DBRef,qt.Decimal128,qt.Double,qt.Int32,qt.Long,qt.Map,qt.MaxKey,qt.MinKey,qt.ObjectId,qt.BSONRegExp,qt.Symbol,qt.Timestamp]),servers:new Map,sessionPool:new uV(this),sessions:new Set,promiseLibrary:r.promiseLibrary||Promise,credentials:r.credentials,clusterTime:null,connectionTimers:new Set},this.serverApi=r.serverApi,r.srvHost&&(this.s.srvPoller=r.srvPoller||new nV({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:r.srvHost,logger:r.logger,loggerLevel:r.loggerLevel}),this.s.detectTopologyDescriptionChange=a=>{let u=a.previousDescription.type,c=a.newDescription.type;u!==_n.Sharded&&c===_n.Sharded&&(this.s.handleSrvPolling=bV(this),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return qt.native?"c++":"js"}connect(t,r){if(typeof t=="function"&&(r=t,t={}),t=t||{},this.s.state===so){typeof r=="function"&&r();return}Sl(this,wl),this.emit("topologyOpening",new di.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new di.TopologyDescriptionChangedEvent(this.s.id,new ZA(_n.Unknown),this.s.description)),NV(this,Array.from(this.s.description.servers.values())),Pr.translate(t);let n=t.readPreference||Pr.primary,i=o(s=>{if(s){this.close(),typeof r=="function"?r(s):this.emit("error",s);return}Sl(this,so),this.emit("open",s,this),this.emit("connect",this),typeof r=="function"&&r(s,this)},"connectHandler");if(this.s.credentials){this.command("admin.$cmd",{ping:1},{readPreference:n},i);return}this.selectServer(gl(n),t,i)}close(t,r){if(typeof t=="function"&&(r=t,t={}),typeof t=="boolean"&&(t={force:t}),t=t||{},this.s.state===Kr||this.s.state===io){typeof r=="function"&&r();return}Sl(this,io),oI(this[Gr],new vl("Topology closed")),dV(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(n=>n.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{oV(Array.from(this.s.servers.values()),(n,i)=>rI(n,this,t,i),n=>{this.s.servers.clear(),this.emit("topologyClosed",new di.TopologyClosedEvent(this.s.id)),Sl(this,Kr),typeof r=="function"&&r(n)})})}selectServer(t,r,n){if(typeof r=="function")if(n=r,typeof t!="function"){r=t;let h;t instanceof Pr?h=t:typeof t=="string"?h=new Pr(t):(Pr.translate(r),h=r.readPreference||Pr.primary),t=gl(h)}else r={};r=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},r);let i=this.description.type===_n.Sharded,s=r.session,a=s&&s.transaction;if(i&&a&&a.server){n(void 0,a.server);return}let u=t;if(typeof t=="object"){let h=t.readPreference?t.readPreference:Pr.primary;u=gl(h)}let c={serverSelector:u,transaction:a,callback:n},f=r.serverSelectionTimeoutMS;f&&(c.timer=setTimeout(()=>{c[qS]=!0,c.timer=void 0;let h=new tV(`Server selection timed out after ${f} ms`,this.description);c.callback(h)},f)),this[Gr].push(c),QA(this)}shouldCheckForSessionSupport(){return this.description.type===_n.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return this.description.logicalSessionTimeoutMinutes!=null}startSession(t,r){let n=new eV(this,this.s.sessionPool,t,r);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(t,r){Array.isArray(t)||(t=[t]),this.command("admin.$cmd",{endSessions:t},{readPreference:Pr.primaryPreferred,noResponse:!0,serverApi:this.serverApi},()=>{typeof r=="function"&&r()})}serverUpdateHandler(t){if(!this.s.description.hasServer(t.address)||vV(this.s.description,t))return;let r=this.s.description,n=this.s.description.servers.get(t.address),i=t.$clusterTime;i&&rV(this,i);let s=n&&n.equals(t);if(this.s.description=this.s.description.update(t),this.s.description.compatibilityError){this.emit("error",new vl(this.s.description.compatibilityError));return}s||this.emit("serverDescriptionChanged",new di.ServerDescriptionChangedEvent(this.s.id,t.address,n,this.s.description.servers.get(t.address))),iI(this,t),this[Gr].length>0&&QA(this),s||this.emit("topologyDescriptionChanged",new di.TopologyDescriptionChangedEvent(this.s.id,r,this.s.description))}auth(t,r){typeof t=="function"&&(r=t,t=null),typeof r=="function"&&r(null,!0)}logout(t){typeof t=="function"&&t(null,!0)}insert(t,r,n,i){Ol({topology:this,op:"insert",ns:t,ops:r},n,i)}update(t,r,n,i){Ol({topology:this,op:"update",ns:t,ops:r},n,i)}remove(t,r,n,i){Ol({topology:this,op:"remove",ns:t,ops:r},n,i)}command(t,r,n,i){typeof n=="function"&&(i=n,n={},n=n||{}),Pr.translate(n);let s=n.readPreference||Pr.primary;this.selectServer(gl(s),n,(a,u)=>{if(a){i(a);return}let c=!n.retrying,f=!!n.retryWrites,h=!!n.session,l=u.supportsRetryableWrites,d=!h||!n.session.inTransaction(),m=c&&f&&h&&l&&d&&OV(r),S=o((E,O)=>{if(!E)return i(null,O);if(!sI(E))return i(E);if(m){let T=Object.assign({},n,{retrying:!0});return this.command(t,r,T,i)}return i(E)},"cb");m&&(n.session.incrementTransactionNumber(),n.willRetryWrite=m),u.command(t,r,n,S)})}cursor(t,r,n){n=n||{};let i=n.topology||this,s=n.cursorFactory||this.s.Cursor;return Pr.translate(n),new s(i,t,r,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===so}isDestroyed(){return this.s.state===Kr}unref(){hV("`unref` is a noop and will be removed in the next major version")}lastIsMaster(){let t=Array.from(this.description.servers.values());return t.length===0?{}:t.filter(i=>i.type!==Gz.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}};o(DS,"Topology");var oo=DS;Object.defineProperty(oo.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}});oo.prototype.destroy=Zz(oo.prototype.close,"destroy() is deprecated, please use close() instead");var wV=["findAndModify","insert","update","delete"];function OV(e){return wV.some(t=>e[t])}o(OV,"isWriteCommand");function vV(e,t){let n=e.servers.get(t.address).topologyVersion;return lV(n,t.topologyVersion)>0}o(vV,"isStaleServerDescription");function rI(e,t,r,n){r=r||{},gV.forEach(i=>e.removeAllListeners(i)),e.destroy(r,()=>{t.emit("serverClosed",new di.ServerClosedEvent(t.s.id,e.description.address)),tI.forEach(i=>e.removeAllListeners(i)),typeof n=="function"&&n()})}o(rI,"destroyServer");function EV(e){return e.split(",").map(t=>({host:t.split(":")[0],port:t.split(":")[1]||27017}))}o(EV,"parseStringSeedlist");function _V(e,t){return t.directConnection?_n.Single:(t.replicaSet||t.setName||t.rs_name)==null?_n.Unknown:_n.ReplicaSetNoPrimary}o(_V,"topologyTypeFromSeedlist");function TV(e){return e[Math.floor(Math.random()*e.length)]}o(TV,"randomSelection");function nI(e,t,r){e.emit("serverOpening",new di.ServerOpeningEvent(e.s.id,t.address));let n=new Kz(t,e.s.options,e);if(Xz(n,e,tI),n.on("descriptionReceived",e.serverUpdateHandler.bind(e)),r){let i=setTimeout(()=>{pV(i,e.s.connectionTimers),n.connect()},r);return e.s.connectionTimers.add(i),n}return n.connect(),n}o(nI,"createAndConnectServer");function NV(e,t){e.s.servers=t.reduce((r,n)=>{let i=nI(e,n);return r.set(n.address,i),r},new Map)}o(NV,"connectServers");function iI(e,t){if(t&&e.s.servers.has(t.address)){let r=e.s.servers.get(t.address);r.s.description=t}for(let r of e.description.servers.values())if(!e.s.servers.has(r.address)){let n=nI(e,r);e.s.servers.set(r.address,n)}for(let r of e.s.servers){let n=r[0];if(e.description.hasServer(n))continue;let i=e.s.servers.get(n);e.s.servers.delete(n),rI(i,e)}}o(iI,"updateServers");function Ol(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=e.topology,i=e.op,s=e.ns,a=e.ops;n.selectServer(mV(),t,(u,c)=>{if(u){r(u,null);return}let f=!e.retrying,h=!!t.retryWrites,l=!!t.session,d=c.supportsRetryableWrites,m=!l||!t.session.inTransaction(),S=t.explain===void 0,E=f&&h&&l&&d&&m&&S,O=o((T,R)=>{if(!T)return r(null,R);if(!sI(T))return T=iV(T),r(T);if(E){let _=Object.assign({},e,{retrying:!0});return Ol(_,t,r)}return r(T)},"handler");r.operationId&&(O.operationId=r.operationId),E&&(t.session.incrementTransactionNumber(),t.willRetryWrite=E),c[i](s,a,t,O)})}o(Ol,"executeWriteOperation");function sI(e){return e instanceof vl&&e.hasErrorLabel("RetryableWriteError")}o(sI,"shouldRetryOperation");function bV(e){return o(function(r){let n=e.s.description;e.s.description=e.s.description.updateFromSrvPollingEvent(r),e.s.description!==n&&(iI(e),e.emit("topologyDescriptionChanged",new di.TopologyDescriptionChangedEvent(e.s.id,n,e.s.description)))},"handleSrvPolling")}o(bV,"srvPollingHandler");function oI(e,t){for(;e.length;){let r=e.shift();clearTimeout(r.timer),r[qS]||r.callback(t)}}o(oI,"drainWaitQueue");function QA(e){if(e.s.state===Kr){oI(e[Gr],new vl("Topology is closed, please connect"));return}let t=Array.from(e.description.servers.values()),r=e[Gr].length;for(let n=0;n0&&e.s.servers.forEach(n=>process.nextTick(()=>n.requestCheck()))}o(QA,"processWaitQueue");aI.exports={Topology:oo}});var mI=w((Use,pI)=>{"use strict";var El=require("url"),es=require("querystring"),cI=require("dns"),Se=V().MongoParseError,CV=wt(),AV=b().emitWarningOnce,IV=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/,BV=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map(e=>e.toLowerCase()));function RV(e,t){let r=/^.*?\./,n=`.${e.replace(r,"")}`,i=`.${t.replace(r,"")}`;return n.endsWith(i)}o(RV,"matchesParentDomain");function MV(e,t,r){let n=El.parse(e,!0);if(t.directConnection||t.directconnection)return r(new Se("directConnection not supported with SRV URI"));if(n.hostname.split(".").length<3)return r(new Se("URI does not have hostname, domain name and tld"));if(n.domainLength=n.hostname.split(".").length,e.substring(14).split("/")[0].match(","))return r(new Se("Invalid URI, cannot contain multiple hostnames"));if(n.port)return r(new Se(`Ports not accepted with '${LS}' URIs`));let s=n.host;cI.resolveSrv(`_mongodb._tcp.${s}`,(a,u)=>{if(a)return r(a);if(u.length===0)return r(new Se("No addresses found at host"));for(let c=0;c`${c.name}:${c.port}`).join(","),!("ssl"in t)&&(!n.search||!("ssl"in n.query)||n.query.ssl===null)&&(n.query.ssl=!0),cI.resolveTxt(s,(c,f)=>{if(c){if(c.code!=="ENODATA"&&c.code!=="ENOTFOUND")return r(c);f=null}if(f){if(f.length>1)return r(new Se("Multiple text records not allowed"));if(f=es.parse(f[0].join("")),Object.keys(f).some(l=>l.toLowerCase()==="loadbalanced"))return r(new Se("Load balancer mode requires driver version 4+"));if(Object.keys(f).some(l=>l!=="authSource"&&l!=="replicaSet"))return r(new Se("Text record must only set `authSource` or `replicaSet`"));n.query=Object.assign({},f,n.query)}n.search=es.stringify(n.query);let h=El.format(n);dI(h,t,(l,d)=>{if(l){r(l);return}r(null,Object.assign({},d,{srvHost:s}))})})})}o(MV,"parseSrvConnectionString");function PS(e,t){if(Array.isArray(t))t=t.filter((r,n)=>t.indexOf(r)===n),t.length===1&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((r,n)=>{let i=n.split(":");return r[i[0]]=PS(e,i[1]),r},{});else if(t.indexOf(",")>0)t=t.split(",").map(r=>PS(e,r));else if(t.toLowerCase()==="true"||t.toLowerCase()==="false")t=t.toLowerCase()==="true";else if(!Number.isNaN(t)&&!qV.has(e)){let r=parseFloat(t);Number.isNaN(r)||(t=parseFloat(t))}return t}o(PS,"parseQueryStringItemValue");var xV=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),qV=new Set(["authsource","replicaset"]),fI=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),lI={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function DV(e,t,r,n){if(t==="journal"?t="j":t==="wtimeoutms"&&(t="wtimeout"),xV.has(t)?r=r==="true"||r===!0:t==="appname"?r=decodeURIComponent(r):t==="readconcernlevel"&&(e.readConcernLevel=r,t="readconcern",r={level:r}),t==="compressors"&&(r=Array.isArray(r)?r:[r],!r.every(i=>i==="snappy"||i==="zlib")))throw new Se("Value for `compressors` must be at least one of: `snappy`, `zlib`");if(t==="authmechanism"&&!fI.has(r))throw new Se(`Value for authMechanism must be one of: ${Array.from(fI).join(", ")}, found: ${r}`);if(t==="readpreference"&&!CV.isValid(r))throw new Se("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if(t==="zlibcompressionlevel"&&(r<-1||r>9))throw new Se("zlibCompressionLevel must be an integer between -1 and 9");if((t==="compressors"||t==="zlibcompressionlevel")&&(e.compression=e.compression||{},e=e.compression),t==="authmechanismproperties"&&(typeof r.SERVICE_NAME=="string"&&(e.gssapiServiceName=r.SERVICE_NAME),typeof r.SERVICE_REALM=="string"&&(e.gssapiServiceRealm=r.SERVICE_REALM),typeof r.CANONICALIZE_HOST_NAME<"u"&&(e.gssapiCanonicalizeHostName=r.CANONICALIZE_HOST_NAME)),t==="readpreferencetags"&&(r=Array.isArray(r)?LV(r):[r]),n.caseTranslate&&lI[t]){e[lI[t]]=r;return}e[t]=r}o(DV,"applyConnectionStringOption");var PV=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function LV(e){let t=[];for(let r=0;r{let i=n.split(":");t[r][i[0]]=i[1]});return t}o(LV,"splitArrayOfMultipleReadPreferenceTags");function jV(e){if(e.options==null)return;let t=e.options,r=t.authsource||t.authSource;r!=null&&(e.auth=Object.assign({},e.auth,{db:r}));let n=t.authmechanism||t.authMechanism;if(n!=null){if(PV.has(n)&&(!e.auth||e.auth.username==null))throw new Se(`Username required for mechanism \`${n}\``);if(n==="GSSAPI"){if(r!=null&&r!=="$external")throw new Se(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-AWS"){if(r!=null&&r!=="$external")throw new Se(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-X509"){if(e.auth&&e.auth.password!=null)throw new Se(`Password not allowed for mechanism \`${n}\``);if(r!=null&&r!=="$external")throw new Se(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}n==="PLAIN"&&e.auth&&e.auth.db==null&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}return e.auth&&e.auth.db==null&&(e.auth=Object.assign({},e.auth,{db:"admin"})),e}o(jV,"applyAuthExpectations");function UV(e,t){let r={},n=es.parse(e);FV(n);for(let i in n){let s=n[i];if(s===""||s==null)throw new Se("Incomplete key value pair for option");let a=i.toLowerCase();if(a==="serverapi")throw new Se("URI cannot contain `serverApi`, it can only be passed to the client");let u=BV.has(a)?s:PS(a,s);DV(r,a,u,t)}return r.wtimeout&&r.wtimeoutms&&(delete r.wtimeout,AV("Unsupported option `wtimeout` specified")),Object.keys(r).length?r:null}o(UV,"parseQueryString");function WV(e){return e.tls&&(e.ssl=e.tls),e.tlsInsecure?(e.checkServerIdentity=!1,e.sslValidate=!1):Object.assign(e,{checkServerIdentity:!e.tlsAllowInvalidHostnames,sslValidate:!e.tlsAllowInvalidCertificates}),e.tlsCAFile&&(e.ssl=!0,e.sslCA=e.tlsCAFile),e.tlsCertificateKeyFile&&(e.ssl=!0,e.tlsCertificateFile?(e.sslCert=e.tlsCertificateFile,e.sslKey=e.tlsCertificateKeyFile):(e.sslKey=e.tlsCertificateKeyFile,e.sslCert=e.tlsCertificateKeyFile)),e.tlsCertificateKeyFilePassword&&(e.ssl=!0,e.sslPass=e.tlsCertificateKeyFilePassword),e}o(WV,"translateTLSOptions");function FV(e){let t=Object.keys(e);if(t.indexOf("tlsInsecure")!==-1&&(t.indexOf("tlsAllowInvalidCertificates")!==-1||t.indexOf("tlsAllowInvalidHostnames")!==-1))throw new Se("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");let r=hI("tls",e,t),n=hI("ssl",e,t);if(r!=null&&n!=null&&r!==n)throw new Se("All values of `tls` and `ssl` must be the same.")}o(FV,"checkTLSOptions");function hI(e,t,r){let n=r.indexOf(e)!==-1,i;if(Array.isArray(t[e])?i=t[e][0]:i=t[e],n&&Array.isArray(t[e])){let s=t[e][0];t[e].forEach(a=>{if(a!==s)throw new Se(`All values of ${e} must be the same.`)})}return i}o(hI,"assertTlsOptionsAreEqual");var $V="mongodb",LS="mongodb+srv",zV=[$V,LS];function dI(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{El.parse(e)}catch{return r(new Se("URI malformed, cannot be parsed"))}let n=e.match(IV);if(!n)return r(new Se("Invalid connection string"));let i=n[1];if(zV.indexOf(i)===-1)return r(new Se("Invalid protocol provided"));let s=n[4].split("?"),a=s.length>0?s[0]:null,u=s.length>1?s[1]:null,c;try{c=UV(u,t)}catch(E){return r(E)}if(c=Object.assign({},c,t),Object.keys(c).some(E=>E.toLowerCase()==="loadbalanced"))return r(new Se("Load balancer mode requires driver version 4+"));if(i===LS)return MV(e,c,r);let f={username:null,password:null,db:a&&a!==""?es.unescape(a):null};if(c.auth?(c.auth.username&&(f.username=c.auth.username),c.auth.user&&(f.username=c.auth.user),c.auth.password&&(f.password=c.auth.password)):(c.username&&(f.username=c.username),c.user&&(f.username=c.user),c.password&&(f.password=c.password)),n[4].split("?")[0].indexOf("@")!==-1)return r(new Se("Unescaped slash in userinfo section"));let h=n[3].split("@");if(h.length>2)return r(new Se("Unescaped at-sign in authority section"));if(h[0]==null||h[0]==="")return r(new Se("No username provided in authority section"));if(h.length>1){let E=h.shift().split(":");if(E.length>2)return r(new Se("Unescaped colon in authority section"));if(E[0]==="")return r(new Se("Invalid empty username provided"));f.username||(f.username=es.unescape(E[0])),f.password||(f.password=E[1]?es.unescape(E[1]):null)}let l=null,d=h.shift().split(",").map(E=>{let O=El.parse(`mongodb://${E}`);if(O.path==="/:")return l=new Se("Double colon in host identifier"),null;if(E.match(/\.sock/)&&(O.hostname=es.unescape(E),O.port=null),Number.isNaN(O.port)){l=new Se("Invalid port (non-numeric string)");return}let T={host:O.hostname,port:O.port?parseInt(O.port):27017};if(T.port===0){l=new Se("Invalid port (zero) with hostname");return}if(T.port>65535){l=new Se("Invalid port (larger than 65535) with hostname");return}if(T.port<0){l=new Se("Invalid port (negative number)");return}return T}).filter(E=>!!E);if(l)return r(l);if(d.length===0||d[0].host===""||d[0].host===null)return r(new Se("No hostname or hostnames provided in connection string"));if(!!c.directConnection&&d.length!==1)return r(new Se("directConnection option requires exactly one host"));c.directConnection==null&&d.length===1&&c.replicaSet==null&&(c.directConnection=!0);let S={hosts:d,auth:f.db||f.username?f:null,options:Object.keys(c).length?c:null};S.auth&&S.auth.db?S.defaultDatabase=S.auth.db:S.defaultDatabase="test",S.options=WV(S.options);try{jV(S)}catch(E){return r(E)}r(null,S)}o(dI,"parseConnectionString");pI.exports=dI});var $=w((Fse,gI)=>{"use strict";var yI=Wc(),VV=Fc()(require),HV=re().retrieveEJSON();try{let e=VV("bson-ext");e&&(yI=e)}catch{}var jS=Object.freeze({v1:"1"}),kV=Object.keys(jS).map(e=>jS[e]);gI.exports={ServerApiVersion:jS,ValidServerApiVersions:kV,MongoError:V().MongoError,MongoNetworkError:V().MongoNetworkError,MongoParseError:V().MongoParseError,MongoTimeoutError:V().MongoTimeoutError,MongoServerSelectionError:V().MongoServerSelectionError,MongoWriteConcernError:V().MongoWriteConcernError,Connection:Sm(),Server:xf(),ReplSet:Vb(),Mongos:Qb(),Logger:yr(),Cursor:Sr().CoreCursor,ReadPreference:wt(),Sessions:Kn(),BSON:yI,EJSON:HV,Topology:uI().Topology,Query:sr().Query,MongoCredentials:ty().MongoCredentials,defaultAuthProviders:oy().defaultAuthProviders,MongoCR:Dm(),X509:jm(),Plain:Fm(),GSSAPI:Hm(),ScramSHA1:xa().ScramSHA1,ScramSHA256:xa().ScramSHA256,parseConnectionString:mI()}});var wI=w(($se,SI)=>{"use strict";var YV=require("events").EventEmitter,WS=class WS extends YV{constructor(){super()}instrument(t,r){this.$MongoClient=t;let n=this.$prototypeConnect=t.prototype.connect,i=this;t.prototype.connect=function(s){return this.s.options.monitorCommands=!0,this.on("commandStarted",a=>i.emit("started",a)),this.on("commandSucceeded",a=>i.emit("succeeded",a)),this.on("commandFailed",a=>i.emit("failed",a)),n.call(this,s)},typeof r=="function"&&r(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}};o(WS,"Instrumentation");var US=WS;SI.exports=US});var lu=w((Vse,vI)=>{"use strict";var GV=$().MongoNetworkError,dt=Ii().MONGODB_ERROR_CODES,OI=new Set([dt.HostUnreachable,dt.HostNotFound,dt.NetworkTimeout,dt.ShutdownInProgress,dt.PrimarySteppedDown,dt.ExceededTimeLimit,dt.SocketException,dt.NotMaster,dt.InterruptedAtShutdown,dt.InterruptedDueToReplStateChange,dt.NotMasterNoSlaveOk,dt.NotMasterOrSecondary,dt.StaleShardVersion,dt.StaleEpoch,dt.StaleConfig,dt.RetryChangeStream,dt.FailedToSatisfyReadPreference,dt.CursorNotFound]);function KV(e,t){return e instanceof GV?!0:t>=9?e.code===dt.CursorNotFound?!0:e.hasErrorLabel("ResumableChangeStreamError"):OI.has(e.code)}o(KV,"isResumableError");vI.exports={GET_MORE_RESUMABLE_CODES:OI,isResumableError:KV,MONGODB_ERROR_CODES:dt}});var _l=w((kse,EI)=>{"use strict";EI.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}});var _t=w((Yse,AI)=>{"use strict";var ts=Ii().MONGODB_ERROR_CODES,FS=b().applyWriteConcern,XV=$().BSON.Code,JV=b().debugOptions,Qe=b().handleCallback,ur=$().MongoError,_I=b().parseIndexOptions,ao=$().ReadPreference,TI=b().toError,ZV=Di().extractCommand,QV=_l(),eH=b().MongoDBNamespace,tH=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function NI(e,t,r,n,i){let s=Object.assign({},{readPreference:ao.PRIMARY},n);if(s=FS(s,{db:e},n),s.writeConcern&&typeof i!="function")throw ur.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new ur("topology was destroyed"));uH(e,t,r,s,(a,u)=>{if(a==null||a.code===ts.CannotCreateIndex||a.code===ts.DuplicateKey||a.code===ts.IndexOptionsConflict||a.code===ts.IndexKeySpecsConflict||a.code===ts.InterruptedAtShutdown||a.code===ts.InvalidIndexSpecificationOption)return Qe(i,a,u);let c=CI(e,t,r,n);s.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(QV.SYSTEM_INDEX_COLLECTION),c,s,(f,h)=>{if(i!=null){if(f)return Qe(i,f);if(h==null)return Qe(i,null,null);if(h.result.writeErrors)return Qe(i,ur.create(h.result.writeErrors[0]),null);Qe(i,null,c.name)}})})}o(NI,"createIndex");function rH(e,t,r){function n(i){if(r.listeners(t).length>0){r.emit(t,i,e);for(let s=0;s{if(c!=null&&c.code!==ts.NamespaceNotFound)return Qe(i,c,null);if(f==null||!f[u])NI(e,t,r,n,i);else if(typeof i=="function")return Qe(i,null,u)})}o(nH,"ensureIndex");function iH(e,t,r,n,i){let s=t,a=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new ur("topology was destroyed"));s&&s._bsontype==="Code"||(s=new XV(s)),r!=null&&!Array.isArray(r)&&typeof r!="function"?a=[r]:r!=null&&Array.isArray(r)&&typeof r!="function"&&(a=r);let u={$eval:s,args:a};n.nolock&&(u.nolock=n.nolock),n.readPreference=new ao(ao.PRIMARY),$S(e,u,n,(c,f)=>{if(c)return Qe(i,c,null);if(f&&f.ok===1)return Qe(i,null,f.retval);if(f)return Qe(i,ur.create({message:`eval failed: ${f.errmsg}`,driver:!0}),null);Qe(i,c,f)})}o(iH,"evaluate");function $S(e,t,r,n){if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new ur("topology was destroyed"));let i=r.dbName||r.authdb||e.databaseName;if(r.readPreference=ao.resolve(e,r),e.s.logger.isDebug()){let s=ZV(t);e.s.logger.debug(`executing command ${JSON.stringify(s.shouldRedact?`${s.name} details REDACTED`:t)} against ${i}.$cmd with options [${JSON.stringify(JV(tH,r))}]`)}e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,r,(s,a)=>{if(s)return Qe(n,s);if(r.full)return Qe(n,null,a);Qe(n,null,a.result)})}o($S,"executeCommand");function sH(e,t,r,n){let i=new eH("admin","$cmd");e.s.topology.command(i,t,r,(s,a)=>{if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new ur("topology was destroyed"));if(s)return Qe(n,s);Qe(n,null,a.result)})}o(sH,"executeDbAdminCommand");function bI(e,t,r,n){let i=r.full==null?!1:r.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new ur("topology was destroyed"));function s(a){let u={};for(let c=0;c{if(a)return n(TI(a));if(!Array.isArray(u))return Qe(n,null,[]);if(i)return Qe(n,null,u);Qe(n,null,s(u))})}o(bI,"indexInformation");function oH(e,t,r){try{e.collection("system.profile").find({},t).toArray(r)}catch(n){return r(n,null)}}o(oH,"profilingInfo");function aH(e){if(typeof e!="string")throw ur.create({message:"database name must be a string",driver:!0});if(e.length===0)throw ur.create({message:"database name cannot be the empty string",driver:!0});if(e==="$external")return;let t=[" ",".","$","/","\\"];for(let r=0;r{if(l)return Qe(i,l,null);if(d.ok===0)return Qe(i,TI(d),null);Qe(i,null,a)})}o(uH,"createIndexUsingCreateIndexes");AI.exports={createListener:rH,createIndex:NI,ensureIndex:nH,evaluate:iH,executeCommand:$S,executeDbAdminCommand:sH,indexInformation:bI,profilingInfo:oH,validateDatabaseName:aH}});var $t=w((Kse,MI)=>{"use strict";var Tl=b().applyRetryableWrites,Nl=b().applyWriteConcern,hu=b().decorateWithCollation,cH=b().decorateWithReadConcern,fH=_t().executeCommand,II=b().formattedOrderClause,Ze=b().handleCallback,bl=$().MongoError,lH=$().ReadPreference,Tn=b().toError,zS=Sr().CursorState,BI=re().maxWireVersion;function hH(e,t,r){let n=r.skip,i=r.limit,s=r.hint,a=r.maxTimeMS;t=t||{};let u={count:r.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?s=e.options.hint:e.cmd.hint&&(s=e.cmd.hint),hu(u,e,e.cmd)):hu(u,e,r),typeof n=="number"&&(u.skip=n),typeof i=="number"&&(u.limit=i),typeof a=="number"&&(u.maxTimeMS=a),s&&(u.hint=s),cH(u,e),u}o(hH,"buildCountCommand");function dH(e,t,r,n,i,s){let a={findAndModify:e.collectionName,query:t};r=II(r),r&&(a.sort=r),a.new=!!i.new,a.remove=!!i.remove,a.upsert=!!i.upsert;let u=i.projection||i.fields;u&&(a.fields=u),i.arrayFilters&&(a.arrayFilters=i.arrayFilters,delete i.arrayFilters),n&&!i.remove&&(a.update=n),i.maxTimeMS&&(a.maxTimeMS=i.maxTimeMS),i.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions,i.checkKeys=!1;let c=Object.assign({},i);c=Tl(c,e.s.db),c=Nl(c,{db:e.s.db,collection:e},i),c.writeConcern&&(a.writeConcern=c.writeConcern),c.bypassDocumentValidation===!0&&(a.bypassDocumentValidation=c.bypassDocumentValidation),c.readPreference=lH.primary;try{hu(a,e,c)}catch(f){return s(f,null)}fH(e.s.db,a,c,(f,h)=>f?Ze(s,f,null):Ze(s,null,h))}o(dH,"findAndModify");function pH(e,t,r,n){let i=r.full==null?!1:r.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new bl("topology was destroyed"));function s(a){let u={};for(let c=0;c{if(a)return n(Tn(a));if(!Array.isArray(u))return Ze(n,null,[]);if(i)return Ze(n,null,u);Ze(n,null,s(u))})}o(pH,"indexInformation");function RI(e,t,r){let n=typeof r.forceServerObjectId=="boolean"?r.forceServerObjectId:e.s.db.options.forceServerObjectId;return n===!0?t:t.map(i=>(n!==!0&&i._id==null&&(i._id=e.s.pkFactory.createPk()),i))}o(RI,"prepareDocs");function mH(e,t){if(e.s.state===zS.CLOSED||e.isDead&&e.isDead())return Ze(t,bl.create({message:"Cursor is closed",driver:!0}));if(e.s.state===zS.INIT&&e.cmd&&e.cmd.sort)try{e.cmd.sort=II(e.cmd.sort)}catch(r){return Ze(t,r)}e._next((r,n)=>{if(e.s.state=zS.OPEN,r)return Ze(t,r);Ze(t,null,n)})}o(mH,"nextObject");function yH(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=r||{},t=Array.isArray(t)?t:[t];let i=Object.assign({},r);i=Tl(i,e.s.db),i=Nl(i,{db:e.s.db,collection:e},r),i.keepGoing===!0&&(i.ordered=!1),i.serializeFunctions=r.serializeFunctions||e.s.serializeFunctions,t=RI(e,t,r),e.s.topology.insert(e.s.namespace,t,i,(s,a)=>{if(n!=null){if(s)return Ze(n,s);if(a==null)return Ze(n,null,null);if(a.result.code)return Ze(n,Tn(a.result));if(a.result.writeErrors)return Ze(n,Tn(a.result.writeErrors[0]));a.ops=t,Ze(n,null,a)}})}o(yH,"insertDocuments");function gH(e,t,r,n){typeof r=="function"?(n=r,r={}):typeof t=="function"&&(n=t,r={},t={}),r=r||{};let i=Object.assign({},r);i=Tl(i,e.s.db),i=Nl(i,{db:e.s.db,collection:e},r),t==null&&(t={});let s={q:t,limit:0};r.single?s.limit=1:i.retryWrites&&(i.retryWrites=!1),r.hint&&(s.hint=r.hint);try{hu(i,e,r)}catch(a){return n(a,null)}if(r.explain!==void 0&&BI(e.s.topology)<3)return n?n(new bl("server does not support explain on remove")):void 0;e.s.topology.remove(e.s.namespace,[s],i,(a,u)=>{if(n!=null){if(a)return Ze(n,a,null);if(u==null)return Ze(n,null,null);if(u.result.code)return Ze(n,Tn(u.result));if(u.result.writeErrors)return Ze(n,Tn(u.result.writeErrors[0]));Ze(n,null,u)}})}o(gH,"removeDocuments");function SH(e,t,r,n,i){if(typeof n=="function"&&(i=n,n=null),n==null&&(n={}),typeof i!="function"&&(i=null),t==null||typeof t!="object")return i(Tn("selector must be a valid JavaScript object"));if(r==null||typeof r!="object")return i(Tn("document must be a valid JavaScript object"));let s=Object.assign({},n);s=Tl(s,e.s.db),s=Nl(s,{db:e.s.db,collection:e},n),s.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions;let a={q:t,u:r};a.upsert=n.upsert!==void 0?!!n.upsert:!1,a.multi=n.multi!==void 0?!!n.multi:!1,n.hint&&(a.hint=n.hint),s.arrayFilters&&(a.arrayFilters=s.arrayFilters,delete s.arrayFilters),s.retryWrites&&a.multi&&(s.retryWrites=!1);try{hu(s,e,n)}catch(u){return i(u,null)}if(n.explain!==void 0&&BI(e.s.topology)<3)return i?i(new bl("server does not support explain on update")):void 0;e.s.topology.update(e.s.namespace,[a],s,(u,c)=>{if(i!=null){if(u)return Ze(i,u,null);if(c==null)return Ze(i,null,null);if(c.result.code)return Ze(i,Tn(c.result));if(c.result.writeErrors)return Ze(i,Tn(c.result.writeErrors[0]));Ze(i,null,c)}})}o(SH,"updateDocuments");MI.exports={buildCountCommand:hH,findAndModify:dH,indexInformation:pH,nextObject:mH,prepareDocs:RI,insertDocuments:yH,removeDocuments:gH,updateDocuments:SH}});var uo=w((Jse,LI)=>{"use strict";var wH=b().applyWriteConcern,VS=$().BSON.Code,OH=_t().createIndex,vH=b().decorateWithCollation,xI=b().decorateWithReadConcern,EH=_t().ensureIndex,_H=_t().evaluate,HS=_t().executeCommand,Jt=b().handleCallback,qI=_t().indexInformation,TH=$().BSON.Long,NH=$().MongoError,DI=$().ReadPreference,bH=$t().insertDocuments,CH=$t().updateDocuments,AH=`function () { +var c = db[ns].find(condition); +var map = new Map(); +var reduce_function = reduce; + +while (c.hasNext()) { +var obj = c.next(); +var key = {}; + +for (var i = 0, len = keys.length; i < len; ++i) { +var k = keys[i]; +key[k] = obj[k]; } -function filterSystemCollections(collections) { - return collections.filter(collectionName => { - return collectionName?.length < 8 || collectionName?.substring(0, 7) !== 'system.'; - }); -} - -const getSampleDocSize = (count, recordSamplingSettings) => { - if (recordSamplingSettings.active === 'absolute') { - return Number(recordSamplingSettings.absolute.value); - } - - const limit = Math.ceil((count * recordSamplingSettings.relative.value) / 100); - - return Math.min(limit, recordSamplingSettings.maxValue); -}; +var aggObj = map.get(key); -function getJsonSchema(doc) { - if (doc instanceof bson.ObjectID || doc instanceof bson.DBRef) { - return; - } else if (Array.isArray(doc)) { - const items = getJsonSchema(doc[0]); - if (items) { - return { - items, - }; - } - } else if (doc instanceof bson.Long) { - return { - type: 'numeric', - mode: 'int64', - }; - } else if (typeof doc === 'number' && doc % 1 !== 0) { - return { - type: 'numeric', - mode: 'double', - }; - } else if (typeof doc === 'number' && Math.abs(doc) < 2 ** 32) { - return { - type: 'numeric', - mode: 'int32', - }; - } else if (doc && typeof doc === 'object') { - const properties = Object.keys(doc).reduce((schema, key) => { - const data = getJsonSchema(doc[key]); - - if (!data) { - return schema; - } - - return { - ...schema, - [key]: data, - }; - }, {}); - - if (Object.keys(properties).length === 0) { - return; - } - - return { - properties, - }; - } +if (aggObj == null) { +var newObj = Object.extend({}, key); +aggObj = Object.extend(newObj, initial); +map.put(key, aggObj); } -function getIndexes(indexes) { - return indexes - .filter(ind => { - return ind.name !== '_id_'; - }) - .map(ind => ({ - name: ind.name, - key: Object.keys(ind.key).map(key => { - return { - name: key, - type: getIndexType(ind.key[key]), - }; - }), - sparse: ind.sparse, - unique: ind.unique, - expireAfterSeconds: ind.expireAfterSeconds, - '2dsphere': ind['2dsphereIndexVersion'] ? getGeoIndexVersion(ind['2dsphereIndexVersion']) : {}, - })); +reduce_function(obj, aggObj); } -const getIndexType = indexType => { - switch (indexType) { - case 1: - return 'ascending'; - case -1: - return 'descending'; - case '2dsphere': - return '2DSphere'; - } - - return 'ascending'; -}; - -const getGeoIndexVersion = version => { - let indexVersion = 'default'; - - if (version === 1) { - indexVersion = 'Version 1'; - } - - if (version === 2) { - indexVersion = 'Version 2'; - } - - return { - '2dsphereIndexVersion': indexVersion, - }; -}; - -const getClusterData = cluster => { - return { - dbInstances: cluster['DBClusterMembers']?.map(instance => ({ - dbInstanceIdentifier: instance['DBInstanceIdentifier'], - dbInstanceRole: instance['IsClusterWriter'] ? 'Primary' : 'Replica', - })), - DBClusterIdentifier: cluster['DBClusterIdentifier'], - DBClusterArn: cluster['DBClusterArn'], - Endpoint: cluster['Endpoint'], - ReaderEndpoint: cluster['ReaderEndpoint'], - MultiAZ: cluster['MultiAZ'], - Port: cluster['Port'] ?? 27017, - DBClusterParameterGroup: cluster['DBClusterParameterGroup'], - DbClusterResourceId: cluster['DbClusterResourceId'], - StorageEncrypted: cluster['StorageEncrypted'], - BackupRetentionPeriod: String(cluster['BackupRetentionPeriod'] ?? ''), - auditLog: false, - maintenance: Boolean(cluster['PreferredMaintenanceWindow']), - ...(cluster['PreferredMaintenanceWindow'] ? parseMaintenance(cluster['PreferredMaintenanceWindow']) : {}), - }; -}; - -const parseMaintenance = period => { - const getDay = d => { - const day = d.slice(0, 3); - - return ( - { - sun: 'Sunday', - mon: 'Monday', - tue: 'Tuesday', - wed: 'Wednesday', - thu: 'Thursday', - fri: 'Friday', - sat: 'Saturday', - }[day] || 'Sunday' - ); - }; - const getTime = d => { - const time = d.slice(4); - const [hours, minutes] = time.split(':'); - const date = new Date(0); - - date.setHours(+hours); - date.setMinutes(+minutes); - - return date; - }; - - const [from, to] = period.split('-'); - - return { - startDay: getDay(from), - startHour: String(getTime(from).getHours()).padStart(2, '0'), - startMinute: String(getTime(from).getMinutes()).padStart(2, '0'), - duration: String((getTime(to) - getTime(from)) / (1000 * 60 * 60)), - }; -}; - -const parseHost = (host, logger) => { - try { - const [dbClusterIdentifier, , region] = host.split('.'); - - return { - dbClusterIdentifier, - region, - }; - } catch (e) { - logger.error(e); - } -}; +return { "result": map.values() }; +}`;function IH(e,t,r,n){OH(e.s.db,e.collectionName,t,r,n)}o(IH,"createIndex");function BH(e,t,r,n){let i=e.s.topology.capabilities();for(let s=0;s{l[d]=1}),h.group.key=l}u=Object.assign({},u),u.readPreference=DI.resolve(e,u),xI(h,e,u);try{vH(h,e,u)}catch(l){return c(l,null)}HS(e.s.db,h,u,(l,d)=>{if(l)return Jt(c,l,null);Jt(c,null,d.retval)})}else{let f=i!=null&&i._bsontype==="Code"?i.scope:{};f.ns=e.collectionName,f.keys=t,f.condition=r,f.initial=n;let h=AH.replace(/ reduce;/,i.toString()+";");_H(e.s.db,new VS(h,f),null,u,(l,d)=>{if(l)return Jt(c,l,null);Jt(c,null,d.result||d)})}}o(MH,"group");function xH(e,t,r){t=Object.assign({},{full:!0},t),qI(e.s.db,e.collectionName,t,r)}o(xH,"indexes");function qH(e,t,r,n){PI(e,r,(i,s)=>{if(i!=null)return Jt(n,i,null);if(!Array.isArray(t))return Jt(n,null,s[t]!=null);for(let a=0;a{if(s)return Jt(r,s,null);if(a==null)return Jt(r,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);let u=[];i&&(t.raw=i);for(let c=0;c{if(n!=null){if(t==null)return Jt(n,null,null);if(s)return Jt(n,s,null);Jt(n,null,a)}})}o(PH,"save");LI.exports={createIndex:IH,createIndexes:BH,ensureIndex:RH,group:MH,indexes:xH,indexExists:qH,indexInformation:PI,parallelCollectionScan:DH,save:PH}});var FI=w((Qse,WI)=>{"use strict";var LH=uo().buildCountCommand,co=b().handleCallback,jI=$().MongoError,jH=Array.prototype.push,Cl=Sr().CursorState;function UH(e,t,r,n){t&&(typeof e.cursorSkip()=="number"&&(r.skip=e.cursorSkip()),typeof e.cursorLimit()=="number"&&(r.limit=e.cursorLimit())),r.readPreference&&e.setReadPreference(r.readPreference),typeof r.maxTimeMS!="number"&&e.cmd&&typeof e.cmd.maxTimeMS=="number"&&(r.maxTimeMS=e.cmd.maxTimeMS);let i={};i.skip=r.skip,i.limit=r.limit,i.hint=r.hint,i.maxTimeMS=r.maxTimeMS,i.collectionName=e.namespace.collection;let s;try{s=LH(e,e.cmd.query,i)}catch(a){return n(a)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),s,e.options,(a,u)=>{n(a,u?u.result.n:null)})}o(UH,"count");function kS(e,t){if(!t)throw jI.create({message:"callback is mandatory",driver:!0});if(e.isNotified())return;if(e.s.state===Cl.CLOSED||e.isDead())return co(t,jI.create({message:"Cursor is closed",driver:!0}));e.s.state===Cl.INIT&&(e.s.state=Cl.OPEN);let r=null;if(e.bufferedCount()>0){for(;r=UI(e,t);)r(e,t);kS(e,t)}else e.next((n,i)=>{if(n)return co(t,n);if(i==null)return e.close({skipKillCursors:!0},()=>co(t,null,null));co(t,null,i)!==!1&&kS(e,t)})}o(kS,"each");function UI(e,t){if(e.bufferedCount()!==0)return e._next(t),UI}o(UI,"loop");function WH(e,t){let r=[];e.rewind(),e.s.state=Cl.INIT;let n=o(()=>{e._next((i,s)=>{if(i)return co(t,i);if(s==null)return e.close({skipKillCursors:!0},()=>co(t,null,r));if(r.push(s),e.bufferedCount()>0){let a=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&typeof e.s.transforms.doc=="function"&&(a=a.map(e.s.transforms.doc)),jH.apply(r,a)}n()})},"fetchDocs");n()}o(WH,"toArray");WI.exports={count:UH,each:kS,toArray:WH}});var zI=w((toe,$I)=>{"use strict";var FH=$t().buildCountCommand,$H=F().OperationBase,GS=class GS extends $H{constructor(t,r,n){super(n),this.cursor=t,this.applySkipLimit=r}execute(t){let r=this.cursor,n=this.applySkipLimit,i=this.options;n&&(typeof r.cursorSkip()=="number"&&(i.skip=r.cursorSkip()),typeof r.cursorLimit()=="number"&&(i.limit=r.cursorLimit())),i.readPreference&&r.setReadPreference(i.readPreference),typeof i.maxTimeMS!="number"&&r.cmd&&typeof r.cmd.maxTimeMS=="number"&&(i.maxTimeMS=r.cmd.maxTimeMS);let s={};s.skip=i.skip,s.limit=i.limit,s.hint=i.hint,s.maxTimeMS=i.maxTimeMS,s.collectionName=r.namespace.collection;let a;try{a=FH(r,r.cmd.query,s)}catch(u){return t(u)}r.server=r.topology.s.coreTopology,r.topology.command(r.namespace.withCollection("$cmd"),a,r.options,(u,c)=>{t(u,c?c.result.n:null)})}};o(GS,"CountOperation");var YS=GS;$I.exports=YS});var Xr=w((noe,KI)=>{"use strict";var zH=require("stream").Transform,VH=require("stream").PassThrough,XS=require("util").deprecate,VI=b().handleCallback,HI=$().ReadPreference,we=$().MongoError,kI=Sr().CoreCursor,se=Sr().CursorState,HH=$().BSON.Map,du=b().maybePromise,kH=zs(),YH=b().formattedOrderClause,GH=La().Explain,KH=F().Aspect,KS=FI().each,XH=zI(),YI=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],GI=["numberOfRetries","tailableRetryInterval"],Al=class Al extends kI{constructor(t,r,n,i){super(t,r,n,i),this.operation&&(i=this.operation.options);let s=i.numberOfRetries||5,a=i.tailableRetryInterval||500,u=s,c=i.promiseLibrary||Promise;this.s={numberOfRetries:s,tailableRetryInterval:a,currentNumberOfRetries:u,state:se.INIT,promiseLibrary:c,explicitlyIgnoreSession:!!i.explicitlyIgnoreSession},!i.explicitlyIgnoreSession&&i.session&&(this.cursorState.session=i.session),this.options.noCursorTimeout===!0&&this.addCursorFlag("noCursorTimeout",!0);let f=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?f=this.cmd.cursor.batchSize:i.cursor&&i.cursor.batchSize?f=i.cursor.batchSize:typeof i.batchSize=="number"&&(f=i.batchSize),this.setCursorBatchSize(f)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}set session(t){this.cursorState.session=t}_initializeCursor(t){this.operation&&this.operation.session!=null?this.cursorState.session=this.operation.session:!this.s.explicitlyIgnoreSession&&!this.cursorState.session&&this.topology.hasSessionSupport()&&(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(t)}hasNext(t){if(this.s.state===se.CLOSED||this.isDead&&this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return du(this,t,r=>{let n=this;if(n.isNotified())return r(null,!1);n._next((i,s)=>{if(i)return r(i);if(s==null||n.s.state===Al.CLOSED||n.isDead())return r(null,!1);n.s.state=se.OPEN,n.cursorState.cursorIndex--,n.cursorState.limit>0&&n.cursorState.currentLimit--,r(null,!0)})})}next(t){return du(this,t,r=>{let n=this;if(n.s.state===se.CLOSED||n.isDead&&n.isDead()){r(we.create({message:"Cursor is closed",driver:!0}));return}if(n.s.state===se.INIT&&n.cmd.sort)try{n.cmd.sort=YH(n.cmd.sort)}catch(i){return r(i)}n._next((i,s)=>{if(i)return r(i);n.s.state=se.OPEN,r(null,s)})})}filter(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.query=t,this}maxScan(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=t,this}hint(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=t,this}min(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.min=t,this}max(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.max=t,this}returnKey(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=t,this}showRecordId(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=t,this}snapshot(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=t,this}setCursorOption(t,r){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});if(GI.indexOf(t)===-1)throw we.create({message:`option ${t} is not a supported option ${GI}`,driver:!0});return this.s[t]=r,t==="numberOfRetries"&&(this.s.currentNumberOfRetries=r),this}addCursorFlag(t,r){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});if(YI.indexOf(t)===-1)throw we.create({message:`flag ${t} is not a supported flag ${YI}`,driver:!0});if(typeof r!="boolean")throw we.create({message:`flag ${t} must be a boolean value`,driver:!0});return this.cmd[t]=r,this}addQueryModifier(t,r){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});if(t[0]!=="$")throw we.create({message:`${t} is not a valid query modifier`,driver:!0});let n=t.substr(1);return this.cmd[n]=r,n==="orderby"&&(this.cmd.sort=this.cmd[n]),this}comment(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=t,this}maxAwaitTimeMS(t){if(typeof t!="number")throw we.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=t,this}maxTimeMS(t){if(typeof t!="number")throw we.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=t,this}project(t){if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=t,this}sort(t,r){if(this.options.tailable)throw we.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===se.CLOSED||this.s.state===se.OPEN||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});let n=t;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new HH(n.map(i=>{let s=[i[0],null];if(i[1]==="asc")s[1]=1;else if(i[1]==="desc")s[1]=-1;else if(i[1]===1||i[1]===-1||i[1].$meta)s[1]=i[1];else throw new we("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");return s}))),r!=null&&(n=[[t,r]]),this.cmd.sort=n,this}batchSize(t){if(this.options.tailable)throw we.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===se.CLOSED||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw we.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=t,this.setCursorBatchSize(t),this}collation(t){return this.cmd.collation=t,this}limit(t){if(this.options.tailable)throw we.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===se.OPEN||this.s.state===se.CLOSED||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw we.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=t,this.setCursorLimit(t),this}skip(t){if(this.options.tailable)throw we.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===se.OPEN||this.s.state===se.CLOSED||this.isDead())throw we.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw we.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=t,this.setCursorSkip(t),this}each(t){this.rewind(),this.s.state=se.INIT,KS(this,t)}forEach(t,r){if(this.rewind(),this.s.state=se.INIT,typeof r=="function")KS(this,(n,i)=>{if(n)return r(n),!1;if(i!=null){try{t(i)}catch(s){return r(s),!1}return!0}if(i==null&&r){let s=r;return r=null,s(null),!1}});else return new this.s.promiseLibrary((n,i)=>{KS(this,(s,a)=>{if(s)return i(s),!1;if(a==null)return n(null),!1;try{t(a)}catch(u){return i(u),!1}return!0})})}setReadPreference(t){if(this.s.state!==se.INIT)throw we.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(t instanceof HI)this.options.readPreference=t;else if(typeof t=="string")this.options.readPreference=new HI(t);else throw new TypeError("Invalid read preference: "+t);return this}toArray(t){if(this.options.tailable)throw we.create({message:"Tailable cursor cannot be converted to array",driver:!0});return du(this,t,r=>{let n=this,i=[];n.rewind(),n.s.state=se.INIT;let s=o(()=>{n._next((a,u)=>{if(a)return VI(r,a);if(u==null)return n.close({skipKillCursors:!0},()=>VI(r,null,i));if(i.push(u),n.bufferedCount()>0){let c=n.readBufferedDocuments(n.bufferedCount());Array.prototype.push.apply(i,c)}s()})},"fetchDocs");s()})}count(t,r,n){if(this.cmd.query==null)throw we.create({message:"count can only be used with find command",driver:!0});typeof r=="function"&&(n=r,r={}),r=r||{},typeof t=="function"&&(n=t,t=!0),this.cursorState.session&&(r=Object.assign({},r,{session:this.cursorState.session}));let i=new XH(this,t,r);return kH(this.topology,i,n)}close(t,r){return typeof t=="function"&&(r=t,t={}),t=Object.assign({},{skipKillCursors:!1},t),du(this,r,n=>{this.s.state=se.CLOSED,t.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),n(null,this)})})}map(t){if(this.cursorState.transforms&&this.cursorState.transforms.doc){let r=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>t(r(n))}else this.cursorState.transforms={doc:t};return this}isClosed(){return this.isDead()}destroy(t){t&&this.emit("error",t),this.pause(),this.close()}stream(t){return this.cursorState.streamOptions=t||{},this}transformStream(t){let r=t||{};if(typeof r.transform=="function"){let n=new zH({objectMode:!0,transform:function(i,s,a){this.push(r.transform(i)),a()}});return this.pipe(n)}return this.pipe(new VH({objectMode:!0}))}explain(t,r){if(typeof t=="function"&&(r=t,t=!0),t===void 0&&(t=!0),!this.operation||!this.operation.hasAspect(KH.EXPLAINABLE))throw new we("This command cannot be explained");return this.operation.explain=new GH(t),du(this,r,n=>{kI.prototype._next.apply(this,[n])})}getLogger(){return this.logger}};o(Al,"Cursor");var pi=Al;pi.prototype.maxTimeMs=pi.prototype.maxTimeMS;XS(pi.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead.");XS(pi.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version");XS(pi.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version");KI.exports=pi});var Jr=w((soe,ZI)=>{"use strict";var Il=F().Aspect,JH=F().OperationBase,XI=$().ReadPreference,ZH=Ui(),QH=an(),ek=re().maxWireVersion,tk=b().decorateWithExplain,rk=Kn().commandSupportsReadConcern,nk=V().MongoError,ik=Di().extractCommand,JI=5,ZS=class ZS extends JH{constructor(t,r,n){super(r),this.ns=t.s.namespace.withCollection("$cmd");let i=this.hasAspect(Il.NO_INHERIT_OPTIONS)?void 0:t;this.readPreference=this.hasAspect(Il.WRITE_OPERATION)?XI.primary:XI.resolve(i,this.options),this.readConcern=ok(i,this.options),this.writeConcern=sk(i,this.options),n&&typeof n.fullResponse=="boolean"&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,t.s.logger?this.logger=t.s.logger:t.s.db&&t.s.db.logger&&(this.logger=t.s.db.logger)}executeCommand(t,r,n){this.server=t;let i=this.options,s=ek(t),a=this.session&&this.session.inTransaction();if(this.readConcern&&rk(r)&&!a&&Object.assign(r,{readConcern:this.readConcern}),i.collation&&s=JI&&(this.writeConcern&&this.hasAspect(Il.WRITE_OPERATION)&&Object.assign(r,{writeConcern:this.writeConcern}),i.collation&&typeof i.collation=="object"&&Object.assign(r,{collation:i.collation})),typeof i.maxTimeMS=="number"&&(r.maxTimeMS=i.maxTimeMS),typeof i.comment=="string"&&(r.comment=i.comment),this.hasAspect(Il.EXPLAINABLE)&&this.explain&&(s<6&&r.aggregate?r.explain=!0:r=tk(r,this.explain)),this.logger&&this.logger.isDebug()){let u=ik(r);this.logger.debug(`executing command ${JSON.stringify(u.shouldRedact?`${u.name} details REDACTED`:r)} against ${this.ns}`)}t.command(this.ns.toString(),r,this.options,(u,c)=>{if(u){n(u,null);return}if(this.fullResponse){n(null,c);return}n(null,c.result)})}};o(ZS,"CommandOperationV2");var JS=ZS;function sk(e,t){return QH.fromOptions(t)||e&&e.writeConcern}o(sk,"resolveWriteConcern");function ok(e,t){return ZH.fromOptions(t)||e&&e.readConcern}o(ok,"resolveReadConcern");ZI.exports=JS});var pu=w((aoe,e1)=>{"use strict";var ak=Jr(),QI=$().MongoError,uk=re().maxWireVersion,ck=$().ReadPreference,Bl=F().Aspect,fk=F().defineAspects,lk=1,hk=8,QS=class QS extends ak{constructor(t,r,n){if(super(t,n,{fullResponse:!0}),this.target=t.s.namespace&&t.s.namespace.collection?t.s.namespace.collection:lk,this.pipeline=r,this.hasWriteStage=!1,typeof n.out=="string")this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(r.length>0){let i=r[r.length-1];(i.$out||i.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=ck.primary),this.explain&&this.writeConcern)throw new QI('"explain" cannot be used on an aggregate call with writeConcern');if(n.cursor!=null&&typeof n.cursor!="object")throw new QI("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(t){this.pipeline.push(t)}execute(t,r){let n=this.options,i=uk(t),s={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&i=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(s,{writeConcern:this.writeConcern}),n.bypassDocumentValidation===!0&&(s.bypassDocumentValidation=n.bypassDocumentValidation),typeof n.allowDiskUse=="boolean"&&(s.allowDiskUse=n.allowDiskUse),n.hint&&(s.hint=n.hint),this.explain&&(n.full=!1),s.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(s.cursor.batchSize=n.batchSize),super.executeCommand(t,s,r)}};o(QS,"AggregateOperation");var Rl=QS;fk(Rl,[Bl.READ_OPERATION,Bl.RETRYABLE,Bl.EXECUTE_WITH_SELECTION,Bl.EXPLAINABLE]);e1.exports=Rl});var jl=w((coe,i1)=>{"use strict";var r1=$().BSON.Long,dk=$().MongoError,Ml=$().BSON.ObjectID,zt=$().BSON,t1=$().MongoWriteConcernError,e0=b().emitWarningOnce,rs=b().toError,is=b().handleCallback,pk=b().applyRetryableWrites,mk=b().applyWriteConcern,yk=b().executeLegacyOperation,gk=b().isPromiseLike,ql=b().hasAtomicOperators,Sk=re().maxWireVersion,wk=64,ns=1,Nn=2,mi=3,Ok=new zt([zt.Binary,zt.Code,zt.DBRef,zt.Decimal128,zt.Double,zt.Int32,zt.Long,zt.Map,zt.MaxKey,zt.MinKey,zt.ObjectId,zt.BSONRegExp,zt.Symbol,zt.Timestamp]),n0=class n0{constructor(t,r){this.originalZeroIndex=r,this.currentIndex=0,this.originalIndexes=[],this.batchType=t,this.operations=[],this.size=0,this.sizeBytes=0}};o(n0,"Batch");var t0=n0,fo=Symbol("upsertedIds"),lo=Symbol("insertedIds"),i0=class i0{constructor(t){this.result=t,this[fo]=void 0,this[lo]=void 0}get insertedCount(){return typeof this.result.nInserted!="number"?0:this.result.nInserted}get matchedCount(){return typeof this.result.nMatched!="number"?0:this.result.nMatched}get modifiedCount(){return typeof this.result.nModified!="number"?0:this.result.nModified}get deletedCount(){return typeof this.result.nRemoved!="number"?0:this.result.nRemoved}get upsertedCount(){return this.result.upserted?this.result.upserted.length:0}get upsertedIds(){if(this[fo])return this[fo];this[fo]={};for(let t of this.result.upserted||[])this[fo][t.index]=t._id;return this[fo]}get insertedIds(){if(this[lo])return this[lo];this[lo]={};for(let t of this.result.insertedIds||[])this[lo][t.index]=t._id;return this[lo]}get n(){return this.result.insertedCount}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(t){return this.result.upserted[t]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(t){return ti.multi)),t.batch.batchType===mi&&(n.retryWrites=n.retryWrites&&!t.batch.operations.some(i=>i.limit===0)));try{t.batch.batchType===ns?this.s.topology.insert(this.s.namespace,t.batch.operations,n,t.resultHandler):t.batch.batchType===Nn?this.s.topology.update(this.s.namespace,t.batch.operations,n,t.resultHandler):t.batch.batchType===mi&&this.s.topology.remove(this.s.namespace,t.batch.operations,n,t.resultHandler)}catch(i){i.ok=0,is(r,null,Ll(t.batch,this.s.bulkResult,i,null))}}handleWriteError(t,r){if(this.s.bulkResult.writeErrors.length>0){let n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return is(t,new po(rs({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),r),null),!0}if(r.getWriteConcernError())return is(t,new po(rs(r.getWriteConcernError()),r),null),!0}};o(c0,"BulkOperationBase");var Pl=c0;Object.defineProperty(Pl.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}});i1.exports={Batch:t0,BulkOperationBase:Pl,mergeBatchResults:Ll,bson:Ok,INSERT:ns,UPDATE:Nn,REMOVE:mi,BulkWriteError:po,BulkWriteResult:ho}});var u1=w((loe,f0)=>{"use strict";var bn=jl(),Ek=bn.BulkOperationBase,s1=bn.Batch,_k=bn.bson,Tk=b(),o1=Tk.toError;function Nk(e,t,r){let n=_k.calculateObjectSize(r,{checkKeys:!1,ignoreUndefined:!1});if(n>=e.s.maxBsonObjectSize)throw o1("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===bn.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===bn.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===bn.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);let i=e.s.maxKeySize;if(e.s.currentBatch==null&&(e.s.currentBatch=new s1(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+i+n>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s1(t,e.s.currentIndex)),Array.isArray(r))throw o1("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(r),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===bn.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:r._id})):t===bn.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===bn.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=i+n,e}o(Nk,"addToOperationsList");var l0=class l0 extends Ek{constructor(t,r,n){n=n||{},n=Object.assign(n,{addToOperationsList:Nk}),super(t,r,n,!1)}handleWriteError(t,r){return this.s.batches.length?!1:super.handleWriteError(t,r)}};o(l0,"UnorderedBulkOperation");var yu=l0;function a1(e,t,r){return new yu(e,t,r)}o(a1,"initializeUnorderedBulkOp");a1.UnorderedBulkOperation=yu;f0.exports=a1;f0.exports.Bulk=yu});var h1=w((doe,h0)=>{"use strict";var Ul=jl(),bk=Ul.BulkOperationBase,c1=Ul.Batch,Ck=Ul.bson,Ak=b(),f1=Ak.toError;function Ik(e,t,r){let n=Ck.calculateObjectSize(r,{checkKeys:!1,ignoreUndefined:!1});if(n>=e.s.maxBsonObjectSize)throw f1("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch==null&&(e.s.currentBatch=new c1(t,e.s.currentIndex));let i=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+i+n>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new c1(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===Ul.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:r._id}),Array.isArray(r))throw f1("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(r),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=i+n,e.s.currentIndex+=1,e}o(Ik,"addToOperationsList");var d0=class d0 extends bk{constructor(t,r,n){n=n||{},n=Object.assign(n,{addToOperationsList:Ik}),super(t,r,n,!0)}};o(d0,"OrderedBulkOperation");var gu=d0;function l1(e,t,r){return new gu(e,t,r)}o(l1,"initializeOrderedBulkOp");l1.OrderedBulkOperation=gu;h0.exports=l1;h0.exports.Bulk=gu});var Wl=w((moe,p1)=>{"use strict";var d1=$().MongoError,Bk=Xr(),Rk=Sr().CursorState,p0=class p0 extends Bk{constructor(t,r,n){super(t,r,n)}batchSize(t){if(this.s.state===Rk.CLOSED||this.isDead())throw d1.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw d1.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=t,this.setCursorBatchSize(t),this}geoNear(t){return this.operation.addToPipeline({$geoNear:t}),this}group(t){return this.operation.addToPipeline({$group:t}),this}limit(t){return this.operation.addToPipeline({$limit:t}),this}match(t){return this.operation.addToPipeline({$match:t}),this}maxTimeMS(t){return this.operation.options.maxTimeMS=t,this}out(t){return this.operation.addToPipeline({$out:t}),this}project(t){return this.operation.addToPipeline({$project:t}),this}lookup(t){return this.operation.addToPipeline({$lookup:t}),this}redact(t){return this.operation.addToPipeline({$redact:t}),this}skip(t){return this.operation.addToPipeline({$skip:t}),this}sort(t){return this.operation.addToPipeline({$sort:t}),this}unwind(t){return this.operation.addToPipeline({$unwind:t}),this}getLogger(){return this.logger}};o(p0,"AggregationCursor");var Su=p0;Su.prototype.get=Su.prototype.toArray;p1.exports=Su});var $l=w((goe,y1)=>{"use strict";var m1=$().ReadPreference,Fl=$().MongoError,Mk=Xr(),m0=Sr().CursorState,y0=class y0 extends Mk{constructor(t,r,n,i){super(t,r,n,i)}setReadPreference(t){if(this.s.state===m0.CLOSED||this.isDead())throw Fl.create({message:"Cursor is closed",driver:!0});if(this.s.state!==m0.INIT)throw Fl.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(t instanceof m1)this.options.readPreference=t;else if(typeof t=="string")this.options.readPreference=new m1(t);else throw new TypeError("Invalid read preference: "+t);return this}batchSize(t){if(this.s.state===m0.CLOSED||this.isDead())throw Fl.create({message:"Cursor is closed",driver:!0});if(typeof t!="number")throw Fl.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=t),this.setCursorBatchSize(t),this}maxTimeMS(t){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=t),this}getLogger(){return this.logger}};o(y0,"CommandCursor");var wu=y0;wu.prototype.get=wu.prototype.toArray;y1.exports=wu});var w0=w((woe,g1)=>{"use strict";var xk=b().applyRetryableWrites,qk=b().applyWriteConcern,Dk=$().MongoError,Pk=F().OperationBase,S0=class S0 extends Pk{constructor(t,r,n){super(n),this.collection=t,this.operations=r}execute(t){let r=this.collection,n=this.operations,i=this.options;r.s.options.ignoreUndefined&&(i=Object.assign({},i),i.ignoreUndefined=r.s.options.ignoreUndefined);let s=i.ordered===!0||i.ordered==null?r.initializeOrderedBulkOp(i):r.initializeUnorderedBulkOp(i),a=!1;try{for(let h=0;h{if(!l&&h)return t(h,null);t(null,l)})}};o(S0,"BulkWriteOperation");var g0=S0;g1.exports=g0});var E0=w((voe,S1)=>{"use strict";var Lk=pu(),v0=class v0 extends Lk{constructor(t,r,n){let i=[{$match:r}];typeof n.skip=="number"&&i.push({$skip:n.skip}),typeof n.limit=="number"&&i.push({$limit:n.limit}),i.push({$group:{_id:1,n:{$sum:1}}}),super(t,i,n)}execute(t,r){super.execute(t,(n,i)=>{if(n){r(n,null);return}let s=i.result;if(s.cursor==null||s.cursor.firstBatch==null){r(null,0);return}let a=s.cursor.firstBatch;r(null,a.length?a[0].n:0)})}};o(v0,"CountDocumentsOperation");var O0=v0;S1.exports=O0});var T0=w((_oe,v1)=>{"use strict";var w1=F().Aspect,jk=F().defineAspects,Uk=Jr(),O1=$().MongoError,Wk=b().parseIndexOptions,Fk=re().maxWireVersion,$k=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]),_0=class _0 extends Uk{constructor(t,r,n,i){if(super(t,i),this.collection=r,!Array.isArray(n)||Array.isArray(n[0])){this.onlyReturnNameOfCreatedIndex=!0;let s=Wk(n),u={name:typeof i.name=="string"?i.name:s.name,key:s.fieldHash};for(let c in i)$k.has(c)&&(u[c]=i[c]);this.indexes=[u];return}this.indexes=n}execute(t,r){let n=this.options,i=this.indexes,s=Fk(t);for(let u=0;u{if(u){r(u);return}r(null,this.onlyReturnNameOfCreatedIndex?i[0].name:c)})}};o(_0,"CreateIndexesOperation");var zl=_0;jk(zl,[w1.WRITE_OPERATION,w1.EXECUTE_WITH_SELECTION]);v1.exports=zl});var _1=w((Noe,E1)=>{"use strict";var zk=F().OperationBase,Vk=$t().removeDocuments,Hk=F().Aspect,kk=F().defineAspects,N0=class N0 extends zk{constructor(t,r,n){super(n),this.collection=t,this.filter=r}execute(t){let r=this.collection,n=this.filter,i=this.options;i.single=!1,Vk(r,n,i,(s,a)=>{if(t!=null){if(s&&t)return t(s);if(a==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,a.result);a.deletedCount=a.result.n,t(null,a)}})}};o(N0,"DeleteManyOperation");var Vl=N0;kk(Vl,[Hk.EXPLAINABLE]);E1.exports=Vl});var N1=w((Coe,T1)=>{"use strict";var Yk=F().OperationBase,Gk=$t().removeDocuments,Kk=F().Aspect,Xk=F().defineAspects,b0=class b0 extends Yk{constructor(t,r,n){super(n),this.collection=t,this.filter=r}execute(t){let r=this.collection,n=this.filter,i=this.options;i.single=!0,Gk(r,n,i,(s,a)=>{if(t!=null){if(s&&t)return t(s);if(a==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,a.result);a.deletedCount=a.result.n,t(null,a)}})}};o(b0,"DeleteOneOperation");var Hl=b0;Xk(Hl,[Kk.EXPLAINABLE]);T1.exports=Hl});var C1=w((Ioe,b1)=>{"use strict";var kl=F().Aspect,Jk=F().defineAspects,Zk=Jr(),Qk=b().decorateWithCollation,eY=b().decorateWithReadConcern,tY=re().maxWireVersion,rY=lu().MongoError,C0=class C0 extends Zk{constructor(t,r,n,i){super(t,i),this.collection=t,this.key=r,this.query=n}execute(t,r){let n=this.collection,i=this.key,s=this.query,a=this.options,u={distinct:n.collectionName,key:i,query:s};typeof a.maxTimeMS=="number"&&(u.maxTimeMS=a.maxTimeMS),eY(u,n,a);try{Qk(u,n,a)}catch(c){return r(c,null)}if(this.explain&&tY(t)<4){r(new rY("server does not support explain on distinct"));return}super.executeCommand(t,u,(c,f)=>{if(c){r(c);return}r(null,this.options.full||this.explain?f:f.values)})}};o(C0,"DistinctOperation");var Yl=C0;Jk(Yl,[kl.READ_OPERATION,kl.RETRYABLE,kl.EXECUTE_WITH_SELECTION,kl.EXPLAINABLE]);b1.exports=Yl});var Lr=w((Roe,B1)=>{"use strict";var A1=F().Aspect,nY=F().OperationBase,I1=b().applyWriteConcern,iY=b().debugOptions,A0=b().handleCallback,sY=$().MongoError,I0=$().ReadPreference,oY=b().MongoDBNamespace,aY=Di().extractCommand,uY=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"],R0=class R0 extends nY{constructor(t,r,n,i){super(r),this.hasAspect(A1.WRITE_OPERATION)?(n!=null?I1(this.options,{db:t,coll:n},this.options):I1(this.options,{db:t},this.options),this.options.readPreference=I0.primary):n!=null?this.options.readPreference=I0.resolve(n,r):this.options.readPreference=I0.resolve(t,r),this.db=t,i!=null&&(this.command=i),n!=null&&(this.collection=n)}_buildCommand(){if(this.command!=null)return this.command}execute(t){let r=this.db,n=Object.assign({},this.options);if(r.serverConfig&&r.serverConfig.isDestroyed())return t(new sY("topology was destroyed"));let i;try{i=this._buildCommand()}catch(u){return t(u)}let s=n.dbName||n.authdb||r.databaseName;if(this.hasAspect(A1.WRITE_OPERATION)&&n.writeConcern&&(!n.session||!n.session.inTransaction())&&(i.writeConcern=n.writeConcern),r.s.logger.isDebug()){let u=aY(i);r.s.logger.debug(`executing command ${JSON.stringify(u.shouldRedact?`${u.name} details REDACTED`:i)} against ${s}.$cmd with options [${JSON.stringify(iY(uY,n))}]`)}let a=this.namespace!=null?this.namespace:new oY(s,"$cmd");r.s.topology.command(a,i,n,(u,c)=>{if(u)return A0(t,u);if(n.full)return A0(t,null,c);A0(t,null,c.result)})}};o(R0,"CommandOperation");var B0=R0;B1.exports=B0});var Gl=w((xoe,R1)=>{"use strict";var cY=F().Aspect,fY=Lr(),lY=F().defineAspects,M0=b().handleCallback,D0=class D0 extends fY{constructor(t,r){let n=Object.assign({},r,t.s.options);r.session&&(n.session=r.session),super(t,n)}execute(t){super.execute((r,n)=>{if(r)return M0(t,r);if(n.ok)return M0(t,null,!0);M0(t,null,!1)})}};o(D0,"DropOperation");var mo=D0;lY(mo,cY.WRITE_OPERATION);var P0=class P0 extends mo{constructor(t,r,n){super(t,n),this.name=r,this.namespace=`${t.namespace}.${r}`}_buildCommand(){return{drop:this.name}}};o(P0,"DropCollectionOperation");var x0=P0,L0=class L0 extends mo{_buildCommand(){return{dropDatabase:1}}};o(L0,"DropDatabaseOperation");var q0=L0;R1.exports={DropOperation:mo,DropCollectionOperation:x0,DropDatabaseOperation:q0}});var U0=w((Doe,x1)=>{"use strict";var hY=F().Aspect,dY=F().defineAspects,pY=Lr(),mY=b().applyWriteConcern,M1=b().handleCallback,j0=class j0 extends pY{constructor(t,r,n){super(t.s.db,n,t),this.collection=t,this.indexName=r}_buildCommand(){let t=this.collection,r=this.indexName,n=this.options,i={dropIndexes:t.collectionName,index:r};return i=mY(i,{db:t.s.db,collection:t},n),i}execute(t){super.execute((r,n)=>{if(typeof t=="function"){if(r)return M1(t,r,null);M1(t,null,n)}})}};o(j0,"DropIndexOperation");var Kl=j0;dY(Kl,hY.WRITE_OPERATION);x1.exports=Kl});var P1=w((Loe,D1)=>{"use strict";var yY=F().Aspect,gY=F().defineAspects,SY=U0(),q1=b().handleCallback,W0=class W0 extends SY{constructor(t,r){super(t,"*",r)}execute(t){super.execute(r=>{if(r)return q1(t,r,!1);q1(t,null,!0)})}};o(W0,"DropIndexesOperation");var Xl=W0;gY(Xl,yY.WRITE_OPERATION);D1.exports=Xl});var j1=w((Uoe,L1)=>{"use strict";var wY=Ii().MONGODB_ERROR_CODES,F0=F().Aspect,OY=F().defineAspects,vY=Jr(),EY=re().maxWireVersion,_Y=E0(),$0=class $0 extends vY{constructor(t,r){super(t,r),this.collection=t,this.collectionName=t.s.namespace.collection}execute(t,r){if(EY(t)<12)return this.executeLegacy(t,r);if(this.options.query)return new _Y(this.collection,this.options.query,this.options).execute(t,r);let n=[{$collStats:{count:{}}},{$group:{_id:1,n:{$sum:"$count"}}}],i={aggregate:this.collectionName,pipeline:n,cursor:{}};typeof this.options.maxTimeMS=="number"&&(i.maxTimeMS=this.options.maxTimeMS),super.executeCommand(t,i,(s,a)=>{if(s&&s.code!==wY.NamespaceNotFound){r(s);return}r(void 0,a&&a.cursor&&a.cursor.firstBatch&&a.cursor.firstBatch[0].n||0)})}executeLegacy(t,r){let n={count:this.collectionName},i=this.options;i.query&&(n.query=i.query),i.hint&&(n.hint=i.hint),typeof i.maxTimeMS=="number"&&(n.maxTimeMS=i.maxTimeMS),typeof i.skip=="number"&&(n.skip=i.skip),typeof i.limit=="number"&&(n.limit=i.limit),super.executeCommand(t,n,(s,a)=>{if(s){r(s);return}r(null,a.n)})}};o($0,"EstimatedDocumentCountOperation");var Jl=$0;OY(Jl,[F0.READ_OPERATION,F0.RETRYABLE,F0.EXECUTE_WITH_SELECTION]);L1.exports=Jl});var F1=w((Foe,W1)=>{"use strict";var TY=F().OperationBase,Zl=F().Aspect,NY=F().defineAspects,U1=$().ReadPreference,bY=re().maxWireVersion,CY=V().MongoError,z0=class z0 extends TY{constructor(t,r,n,i){super(i),this.ns=r,this.cmd=n,this.readPreference=U1.resolve(t,this.options)}execute(t,r){if(this.server=t,this.readPreference=U1.resolve(this,this.options),typeof this.cmd.allowDiskUse<"u"&&bY(t)<4){r(new CY("The `allowDiskUse` option is not supported on MongoDB < 3.2"));return}this.explain&&(this.options.explain=this.explain.verbosity);let n=this.cursorState||{};t.query(this.ns.toString(),this.cmd,n,this.options,r)}};o(z0,"FindOperation");var Ql=z0;NY(Ql,[Zl.READ_OPERATION,Zl.RETRYABLE,Zl.EXECUTE_WITH_SELECTION,Zl.EXPLAINABLE]);W1.exports=Ql});var V1=w((zoe,z1)=>{"use strict";var $1=b().handleCallback,AY=F().OperationBase,IY=b().toError,BY=F().Aspect,RY=F().defineAspects,V0=class V0 extends AY{constructor(t,r,n){super(n),this.collection=t,this.query=r}execute(t){let r=this.collection,n=this.query,i=this.options;try{r.find(n,i).limit(-1).batchSize(1).next((a,u)=>{if(a!=null)return $1(t,IY(a),null);$1(t,null,u)})}catch(s){t(s)}}};o(V0,"FindOneOperation");var eh=V0;RY(eh,[BY.EXPLAINABLE]);z1.exports=eh});var Ou=w((Hoe,G1)=>{"use strict";var MY=F().OperationBase,xY=b().applyRetryableWrites,qY=b().applyWriteConcern,DY=b().decorateWithCollation,PY=_t().executeCommand,LY=b().formattedOrderClause,H1=b().handleCallback,jY=$().ReadPreference,k1=re().maxWireVersion,Y1=lu().MongoError,UY=F().Aspect,WY=F().defineAspects,FY=b().decorateWithExplain,H0=class H0 extends MY{constructor(t,r,n,i,s){super(s),this.collection=t,this.query=r,this.sort=n,this.doc=i}execute(t){let r=this.collection,n=this.query,i=LY(this.sort),s=this.doc,a=this.options,u={findAndModify:r.collectionName,query:n};i&&(u.sort=i),u.new=!!a.new,u.remove=!!a.remove,u.upsert=!!a.upsert;let c=a.projection||a.fields;c&&(u.fields=c),a.arrayFilters&&(u.arrayFilters=a.arrayFilters),s&&!a.remove&&(u.update=s),a.maxTimeMS&&(u.maxTimeMS=a.maxTimeMS),a.serializeFunctions=a.serializeFunctions||r.s.serializeFunctions,a.checkKeys=!1,a=xY(a,r.s.db),a=qY(a,{db:r.s.db,collection:r},a),a.writeConcern&&(u.writeConcern=a.writeConcern),a.bypassDocumentValidation===!0&&(u.bypassDocumentValidation=a.bypassDocumentValidation),a.readPreference=jY.primary;try{DY(u,r,a)}catch(f){return t(f,null)}if(a.hint){if(a.writeConcern&&a.writeConcern.w===0||k1(r.s.topology)<8){t(new Y1("The current topology does not support a hint on findAndModify commands"));return}u.hint=a.hint}if(this.explain){if(k1(r.s.topology)<4){t(new Y1("server does not support explain on findAndModify"));return}u=FY(u,this.explain)}PY(r.s.db,u,a,(f,h)=>f?H1(t,f,null):H1(t,null,h))}};o(H0,"FindAndModifyOperation");var th=H0;WY(th,[UY.EXPLAINABLE]);G1.exports=th});var X1=w((Yoe,K1)=>{"use strict";var $Y=Ou(),Y0=class Y0 extends $Y{constructor(t,r,n){let i=Object.assign({},n);if(i.fields=n.projection,i.remove=!0,r==null||typeof r!="object")throw new TypeError("Filter parameter must be an object");super(t,r,i.sort,null,i)}};o(Y0,"FindOneAndDeleteOperation");var k0=Y0;K1.exports=k0});var Z1=w((Koe,J1)=>{"use strict";var zY=$().MongoError,VY=Ou(),HY=b().hasAtomicOperators,K0=class K0 extends VY{constructor(t,r,n,i){if("returnDocument"in i&&"returnOriginal"in i)throw new zY("findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined");let s=Object.assign({},i);if(s.fields=i.projection,s.update=!0,s.new=i.returnDocument==="after"||i.returnOriginal===!1,s.upsert=i.upsert===!0,r==null||typeof r!="object")throw new TypeError("Filter parameter must be an object");if(n==null||typeof n!="object")throw new TypeError("Replacement parameter must be an object");if(HY(n))throw new TypeError("Replacement document must not contain atomic operators");super(t,r,s.sort,n,s)}};o(K0,"FindOneAndReplaceOperation");var G0=K0;J1.exports=G0});var eB=w((Joe,Q1)=>{"use strict";var kY=$().MongoError,YY=Ou(),GY=b().hasAtomicOperators,J0=class J0 extends YY{constructor(t,r,n,i){if("returnDocument"in i&&"returnOriginal"in i)throw new kY("findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined");let s=Object.assign({},i);if(s.fields=i.projection,s.update=!0,s.new=i.returnDocument==="after"||i.returnOriginal===!1,s.upsert=i.upsert===!0,r==null||typeof r!="object")throw new TypeError("Filter parameter must be an object");if(n==null||typeof n!="object")throw new TypeError("Update parameter must be an object");if(!GY(n))throw new TypeError("Update document requires atomic operators");super(t,r,s.sort,n,s)}};o(J0,"FindOneAndUpdateOperation");var X0=J0;Q1.exports=X0});var rB=w((Qoe,tB)=>{"use strict";var KY=F().Aspect,XY=F().defineAspects,JY=F().OperationBase,ZY=b().decorateCommand,QY=b().decorateWithReadConcern,eG=_t().executeCommand,Z0=b().handleCallback,tG=$().ReadPreference,rG=b().toError,Q0=class Q0 extends JY{constructor(t,r,n,i){super(i),this.collection=t,this.x=r,this.y=n}execute(t){let r=this.collection,n=this.x,i=this.y,s=this.options,a={geoSearch:r.collectionName,near:[n,i]};a=ZY(a,s,["readPreference","session"]),s=Object.assign({},s),s.readPreference=tG.resolve(r,s),QY(a,r,s),eG(r.s.db,a,s,(u,c)=>{if(u)return Z0(t,u);(c.err||c.errmsg)&&Z0(t,rG(c)),Z0(t,null,c)})}};o(Q0,"GeoHaystackSearchOperation");var rh=Q0;XY(rh,KY.READ_OPERATION);tB.exports=rh});var iB=w((tae,nB)=>{"use strict";var nG=F().OperationBase,iG=$t().indexInformation,tw=class tw extends nG{constructor(t,r){super(r),this.collection=t}execute(t){let r=this.collection,n=this.options;n=Object.assign({},{full:!0},n),iG(r.s.db,r.collectionName,n,t)}};o(tw,"IndexesOperation");var ew=tw;nB.exports=ew});var oB=w((nae,sB)=>{"use strict";var sG=F().OperationBase,nh=b().handleCallback,oG=_t().indexInformation,nw=class nw extends sG{constructor(t,r,n){super(n),this.collection=t,this.indexes=r}execute(t){let r=this.collection,n=this.indexes,i=this.options;oG(r.s.db,r.collectionName,i,(s,a)=>{if(s!=null)return nh(t,s,null);if(!Array.isArray(n))return nh(t,null,a[n]!=null);for(let u=0;u{"use strict";var aG=F().OperationBase,uG=$t().indexInformation,sw=class sw extends aG{constructor(t,r,n){super(n),this.db=t,this.name=r}execute(t){let r=this.db,n=this.name,i=this.options;uG(r,n,i,t)}};o(sw,"IndexInformationOperation");var iw=sw;aB.exports=iw});var cB=w((aae,uB)=>{"use strict";var cG=F().OperationBase,fG=w0(),lG=$().MongoError,hG=$t().prepareDocs,uw=class uw extends cG{constructor(t,r,n){super(n),this.collection=t,this.docs=r}execute(t){let r=this.collection,n=this.docs,i=this.options;if(!Array.isArray(n))return t(lG.create({message:"docs parameter must be an array of documents",driver:!0}));i.serializeFunctions=i.serializeFunctions||r.s.serializeFunctions,n=hG(r,n,i);let s=n.map(u=>({insertOne:{document:u}}));new fG(r,s,i).execute((u,c)=>{if(u)return t(u,null);t(null,dG(n,c))})}};o(uw,"InsertManyOperation");var aw=uw;function dG(e,t){let r={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};return t.getLastOp()&&(r.result.opTime=t.getLastOp()),r}o(dG,"mapInsertManyResults");uB.exports=aw});var lB=w((cae,fB)=>{"use strict";var pG=$().MongoError,mG=F().OperationBase,yG=$t().insertDocuments,fw=class fw extends mG{constructor(t,r,n){super(n),this.collection=t,this.doc=r}execute(t){let r=this.collection,n=this.doc,i=this.options;if(Array.isArray(n))return t(pG.create({message:"doc parameter must be an object",driver:!0}));yG(r,[n],i,(s,a)=>{if(t!=null){if(s&&t)return t(s);if(a==null)return t(null,{result:{ok:1}});a.insertedCount=a.result.n,a.insertedId=n._id,t&&t(null,a)}})}};o(fw,"InsertOneOperation");var cw=fw;fB.exports=cw});var pw=w((lae,hB)=>{"use strict";var gG=F().OperationBase,lw=b().handleCallback,SG=$().MongoError,dw=class dw extends gG{constructor(t,r){super(r),this.collection=t}execute(t){let r=this.collection,n=this.options;r.s.db.listCollections({name:r.collectionName},n).toArray((i,s)=>{if(i)return lw(t,i);if(s.length===0)return lw(t,SG.create({message:`collection ${r.namespace} not found`,driver:!0}));lw(t,i,s[0].options||null)})}};o(dw,"OptionsOperation");var hw=dw;hB.exports=hw});var mB=w((dae,pB)=>{"use strict";var wG=pw(),dB=b().handleCallback,yw=class yw extends wG{constructor(t,r){super(t,r)}execute(t){super.execute((r,n)=>{if(r)return dB(t,r);dB(t,null,!!(n&&n.capped))})}};o(yw,"IsCappedOperation");var mw=yw;pB.exports=mw});var gB=w((mae,yB)=>{"use strict";var OG=Jr(),gw=F().Aspect,vG=F().defineAspects,EG=re().maxWireVersion,_G=3,Sw=class Sw extends OG{constructor(t,r){super(t,r,{fullResponse:!0}),this.collectionNamespace=t.s.namespace}execute(t,r){if(EG(t)<_G){let s=this.collectionNamespace.withCollection("system.indexes").toString(),a=this.collectionNamespace.toString();t.query(s,{query:{ns:a}},{},this.options,r);return}let i=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(t,{listIndexes:this.collectionNamespace.collection,cursor:i},r)}};o(Sw,"ListIndexesOperation");var ih=Sw;vG(ih,[gw.READ_OPERATION,gw.RETRYABLE,gw.EXECUTE_WITH_SELECTION]);yB.exports=ih});var Ow=w((gae,wB)=>{"use strict";var TG=F().Aspect,NG=Lr(),bG=F().defineAspects,CG=require("crypto"),SB=b().handleCallback,AG=b().toError,IG=b().emitWarning,ww=class ww extends NG{constructor(t,r,n,i){super(t,i),this.username=r,this.password=n}_buildCommand(){let t=this.db,r=this.username,n=this.password,i=this.options,s=[];Array.isArray(i.roles)&&(s=i.roles),typeof i.roles=="string"&&(s=[i.roles]),s.length===0&&IG("Creating a user without roles is deprecated in MongoDB >= 2.6"),(t.databaseName.toLowerCase()==="admin"||i.dbName==="admin")&&!Array.isArray(i.roles)?s=["root"]:Array.isArray(i.roles)||(s=["dbOwner"]);let a=t.s.topology.lastIsMaster().maxWireVersion>=7,u=n;if(!a){let f=CG.createHash("md5");f.update(r+":mongo:"+n),u=f.digest("hex")}let c={createUser:r,customData:i.customData||{},roles:s,digestPassword:a};return typeof n=="string"&&(c.pwd=u),c}execute(t){if(this.options.digestPassword!=null)return t(AG("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((n,i)=>n?SB(t,n,null):SB(t,n,i))}};o(ww,"AddUserOperation");var sh=ww;bG(sh,TG.WRITE_OPERATION);wB.exports=sh});var EB=w((wae,vB)=>{"use strict";var BG=F().OperationBase,OB=b().handleCallback,vw;function RG(){return vw||(vw=yo()),vw}o(RG,"loadCollection");var _w=class _w extends BG{constructor(t,r){super(r),this.db=t}execute(t){let r=this.db,n=this.options,i=RG();n=Object.assign({},n,{nameOnly:!0}),r.listCollections({},n).toArray((s,a)=>{if(s!=null)return OB(t,s,null);a=a.filter(u=>u.name.indexOf("$")===-1),OB(t,null,a.map(u=>new i(r,r.s.topology,r.databaseName,u.name,r.s.pkFactory,r.s.options)))})}};o(_w,"CollectionsOperation");var Ew=_w;vB.exports=Ew});var NB=w((vae,TB)=>{"use strict";var MG=Jr(),xG=F().defineAspects,_B=F().Aspect,Tw=class Tw extends MG{constructor(t,r,n){super(t,n),this.command=r}execute(t,r){let n=this.command;this.executeCommand(t,n,r)}};o(Tw,"RunCommandOperation");var oh=Tw;xG(oh,[_B.EXECUTE_WITH_SELECTION,_B.NO_INHERIT_OPTIONS]);TB.exports=oh});var CB=w((_ae,bB)=>{"use strict";var qG=F().Aspect,DG=F().defineAspects,PG=Lr(),LG=b().applyWriteConcern,jG=uh().loadCollection,UG=$().MongoError,WG=$().ReadPreference,FG=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]),Nw=class Nw extends PG{constructor(t,r,n){super(t,n),this.name=r}_buildCommand(){let t=this.name,r=this.options,n={create:t};for(let i in r)r[i]!=null&&typeof r[i]!="function"&&!FG.has(i)&&(n[i]=r[i]);return n}execute(t){let r=this.db,n=this.name,i=this.options,s=jG(),a=Object.assign({nameOnly:!0,strict:!1},i);a=LG(a,{db:r},a);function u(f){if(f)return t(f);try{t(null,new s(r,r.s.topology,r.databaseName,n,r.s.pkFactory,i))}catch(h){t(h)}}if(o(u,"done"),a.strict){r.listCollections({name:n},a).setReadPreference(WG.PRIMARY).toArray((f,h)=>{if(f)return t(f);if(h.length>0)return t(new UG(`Collection ${n} already exists. Currently in strict mode.`));super.execute(u)});return}super.execute(u)}};o(Nw,"CreateCollectionOperation");var ah=Nw;DG(ah,qG.WRITE_OPERATION);bB.exports=ah});var Aw=w((Nae,IB)=>{"use strict";var $G=F().OperationBase,AB=b().handleCallback,zG=$().MongoError,VG=b().MongoDBNamespace,Cw=class Cw extends $G{constructor(t,r,n){super(n),this.db=t,this.selector=r}execute(t){let r=this.db,n=this.selector,i=this.options,s=new VG("admin","$cmd");r.s.topology.command(s,n,i,(a,u)=>{if(r.serverConfig&&r.serverConfig.isDestroyed())return t(new zG("topology was destroyed"));if(a)return AB(t,a);AB(t,null,u.result)})}};o(Cw,"ExecuteDbAdminCommandOperation");var bw=Cw;IB.exports=bw});var RB=w((Cae,BB)=>{"use strict";var HG=Jr(),Iw=F().Aspect,kG=F().defineAspects,YG=re().maxWireVersion,GG=_l(),KG=3;function XG(e){let t=`${e}.`;return{doc:r=>{let n=r.name.indexOf(t);return r.name&&n===0&&(r.name=r.name.substr(n+t.length)),r}}}o(XG,"listCollectionsTransforms");var Bw=class Bw extends HG{constructor(t,r,n){super(t,n,{fullResponse:!0}),this.db=t,this.filter=r,this.nameOnly=!!this.options.nameOnly,typeof this.options.batchSize=="number"&&(this.batchSize=this.options.batchSize)}execute(t,r){if(YG(t){c&&c.message&&c.message.documents&&Array.isArray(c.message.documents)&&(c.message.documents=c.message.documents.map(a.doc)),r(u,c)});return}let n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(t,n,r)}};o(Bw,"ListCollectionsOperation");var ch=Bw;kG(ch,[Iw.READ_OPERATION,Iw.RETRYABLE,Iw.EXECUTE_WITH_SELECTION]);BB.exports=ch});var xB=w((Iae,MB)=>{"use strict";var JG=Lr(),Mw=class Mw extends JG{constructor(t,r,n){super(t,n)}_buildCommand(){return{profile:-1}}execute(t){super.execute((r,n)=>{if(r==null&&n.ok===1){let i=n.was;return i===0?t(null,"off"):i===1?t(null,"slow_only"):i===2?t(null,"all"):t(new Error("Error: illegal profiling level value "+i),null)}else r!=null?t(r,null):t(new Error("Error with profile command"),null)})}};o(Mw,"ProfilingLevelOperation");var Rw=Mw;MB.exports=Rw});var qw=w((Rae,DB)=>{"use strict";var ZG=F().Aspect,QG=Lr(),eK=F().defineAspects,qB=b().handleCallback,tK=an(),xw=class xw extends QG{constructor(t,r,n){let i={},s=tK.fromOptions(n);s!=null&&(i.writeConcern=s),n.dbName&&(i.dbName=n.dbName),typeof n.maxTimeMS=="number"&&(i.maxTimeMS=n.maxTimeMS),super(t,i),this.username=r}_buildCommand(){return{dropUser:this.username}}execute(t){super.execute((r,n)=>{if(r)return qB(t,r,null);qB(t,r,!!n.ok)})}};o(xw,"RemoveUserOperation");var fh=xw;eK(fh,ZG.WRITE_OPERATION);DB.exports=fh});var Lw=w((xae,LB)=>{"use strict";var rK=F().OperationBase,nK=b().applyWriteConcern,iK=b().checkCollectionName,sK=_t().executeDbAdminCommand,lh=b().handleCallback,oK=uh().loadCollection,PB=b().toError,Pw=class Pw extends rK{constructor(t,r,n){super(n),this.collection=t,this.newName=r}execute(t){let r=this.collection,n=this.newName,i=this.options,s=oK();iK(n);let a=r.namespace,u=r.s.namespace.withCollection(n).toString(),c=typeof i.dropTarget=="boolean"?i.dropTarget:!1,f={renameCollection:a,to:u,dropTarget:c};nK(f,{db:r.s.db,collection:r},i),sK(r.s.db.admin().s.db,f,i,(h,l)=>{if(h)return lh(t,h,null);if(l.errmsg)return lh(t,PB(l),null);try{return lh(t,null,new s(r.s.db,r.s.topology,r.s.namespace.db,n,r.s.pkFactory,r.s.options))}catch(d){return lh(t,PB(d),null)}})}};o(Pw,"RenameOperation");var Dw=Pw;LB.exports=Dw});var UB=w((Dae,jB)=>{"use strict";var aK=Lr(),uK=new Set(["off","slow_only","all"]),Uw=class Uw extends aK{constructor(t,r,n){let i=0;r==="off"?i=0:r==="slow_only"?i=1:r==="all"&&(i=2),super(t,n),this.level=r,this.profile=i}_buildCommand(){return{profile:this.profile}}execute(t){let r=this.level;if(!uK.has(r))return t(new Error("Error: illegal profiling level value "+r));super.execute((n,i)=>n==null&&i.ok===1?t(null,r):n!=null?t(n,null):t(new Error("Error with profile command"),null))}};o(Uw,"SetProfilingLevelOperation");var jw=Uw;jB.exports=jw});var FB=w((Lae,WB)=>{"use strict";var cK=Lr(),Fw=class Fw extends cK{constructor(t,r,n){let i={validate:r},s=Object.keys(n);for(let a=0;an!=null?t(n,null):i.ok===0?t(new Error("Error with validate command"),null):i.result!=null&&i.result.constructor!==String?t(new Error("Error with validation data"),null):i.result!=null&&i.result.match(/exception|corrupt/)!=null?t(new Error("Error: invalid collection "+r),null):i.valid!=null&&!i.valid?t(new Error("Error: invalid collection "+r),null):t(null,i))}};o(Fw,"ValidateCollectionOperation");var Ww=Fw;WB.exports=Ww});var zB=w((Uae,$B)=>{"use strict";var fK=Jr(),$w=F().Aspect,lK=F().defineAspects,hK=b().MongoDBNamespace,zw=class zw extends fK{constructor(t,r){super(t,r),this.ns=new hK("admin","$cmd")}execute(t,r){let n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),typeof this.options.authorizedDatabases=="boolean"&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(t,n,r)}};o(zw,"ListDatabasesOperation");var hh=zw;lK(hh,[$w.READ_OPERATION,$w.RETRYABLE,$w.EXECUTE_WITH_SELECTION]);$B.exports=hh});var Vw=w((Fae,HB)=>{"use strict";var VB=b().applyWriteConcern,dK=Ow(),go=Aw(),pK=qw(),mK=FB(),yK=zB(),Zr=zs();function cr(e,t,r){if(!(this instanceof cr))return new cr(e,t);this.s={db:e,topology:t,promiseLibrary:r}}o(cr,"Admin");cr.prototype.command=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift():{};let i=new go(this.s.db,e,t);return Zr(this.s.db.s.topology,i,r)};cr.prototype.buildInfo=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={buildinfo:1},n=new go(this.s.db,r,e);return Zr(this.s.db.s.topology,n,t)};cr.prototype.serverInfo=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={buildinfo:1},n=new go(this.s.db,r,e);return Zr(this.s.db.s.topology,n,t)};cr.prototype.serverStatus=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new go(this.s.db,{serverStatus:1},e);return Zr(this.s.db.s.topology,r,t)};cr.prototype.ping=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={ping:1},n=new go(this.s.db,r,e);return Zr(this.s.db.s.topology,n,t)};cr.prototype.addUser=function(e,t,r,n){let i=Array.prototype.slice.call(arguments,2);n=typeof i[i.length-1]=="function"?i.pop():void 0,typeof e=="string"&&t!=null&&typeof t=="object"&&(r=t,t=null),r=i.length?i.shift():{},r=Object.assign({},r),r=VB(r,{db:this.s.db}),r.dbName="admin";let s=new dK(this.s.db,e,t,r);return Zr(this.s.db.s.topology,s,n)};cr.prototype.removeUser=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift():{},t=Object.assign({},t),t=VB(t,{db:this.s.db}),t.dbName="admin";let i=new pK(this.s.db,e,t);return Zr(this.s.db.s.topology,i,r)};cr.prototype.validateCollection=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new mK(this,e,t);return Zr(this.s.db.s.topology,n,r)};cr.prototype.listDatabases=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},Zr(this.s.db.s.topology,new yK(this.s.db,e),t)};cr.prototype.replSetGetStatus=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new go(this.s.db,{replSetGetStatus:1},e);return Zr(this.s.db.s.topology,r,t)};HB.exports=cr});var Eu=w((zae,JB)=>{"use strict";var KB=require("events").EventEmitter,gK=require("util").inherits,Hw=b().getSingleProperty,SK=$l(),dh=b().handleCallback,wK=b().filterOptions,kB=b().toError,ph=$().ReadPreference,YB=$().MongoError,OK=$().ObjectID,vK=$().Logger,GB=yo(),EK=b().conditionallyMergeWriteConcern,kw=b().executeLegacyOperation,_K=mh(),vu=require("util").deprecate,XB=b().deprecateOptions,TK=b().MongoDBNamespace,So=_l(),NK=an(),Yw=Ui(),bK=Wl(),yi=_t().createListener,CK=_t().ensureIndex,AK=_t().evaluate,IK=_t().profilingInfo,BK=_t().validateDatabaseName,RK=pu(),MK=Ow(),xK=EB(),qK=Lr(),DK=NB(),PK=CB(),LK=T0(),jK=Gl().DropCollectionOperation,UK=Gl().DropDatabaseOperation,WK=Aw(),FK=ow(),$K=RB(),zK=xB(),VK=qw(),HK=Lw(),kK=UB(),Zt=zs(),YK=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","bsonRegExp","compression","retryWrites"];function ae(e,t,r){if(r=r||{},!(this instanceof ae))return new ae(e,t,r);KB.call(this);let n=r.promiseLibrary||Promise;r=wK(r,YK),r.promiseLibrary=n,this.s={dbCache:{},children:[],topology:t,options:r,logger:vK("Db",r),bson:t?t.bson:null,readPreference:ph.fromOptions(r),bufferMaxEntries:typeof r.bufferMaxEntries=="number"?r.bufferMaxEntries:-1,parentDb:r.parentDb||null,pkFactory:r.pkFactory||OK,nativeParser:r.nativeParser||r.native_parser,promiseLibrary:n,noListener:typeof r.noListener=="boolean"?r.noListener:!1,readConcern:Yw.fromOptions(r),writeConcern:NK.fromOptions(r),namespace:new TK(e)},BK(e),Hw(this,"serverConfig",this.s.topology),Hw(this,"bufferMaxEntries",this.s.bufferMaxEntries),Hw(this,"databaseName",this.s.namespace.db),!r.parentDb&&(this.s.noListener||(t.on("error",yi(this,"error",this)),t.on("timeout",yi(this,"timeout",this)),t.on("close",yi(this,"close",this)),t.on("parseError",yi(this,"parseError",this)),t.once("open",yi(this,"open",this)),t.once("fullsetup",yi(this,"fullsetup",this)),t.once("all",yi(this,"all",this)),t.on("reconnect",yi(this,"reconnect",this))))}o(ae,"Db");gK(ae,KB);ae.prototype.on=vu(function(){return ae.super_.prototype.on.apply(this,arguments)},"Listening to events on the Db class has been deprecated and will be removed in the next major version.");ae.prototype.once=vu(function(){return ae.super_.prototype.once.apply(this,arguments)},"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Object.defineProperty(ae.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}});Object.defineProperty(ae.prototype,"options",{enumerable:!0,get:function(){return this.s.options}});Object.defineProperty(ae.prototype,"slaveOk",{enumerable:!0,get:function(){return this.s.options.readPreference!=null&&(this.s.options.readPreference!=="primary"||this.s.options.readPreference.mode!=="primary")}});Object.defineProperty(ae.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}});Object.defineProperty(ae.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference==null?ph.primary:this.s.readPreference}});Object.defineProperty(ae.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}});Object.defineProperty(ae.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}});ae.prototype.command=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t);let n=new DK(this,e,t);return Zt(this.s.topology,n,r)};ae.prototype.aggregate=function(e,t,r){typeof t=="function"&&(r=t,t={}),t==null&&r==null&&(t={});let n=new bK(this.s.topology,new RK(this,e,t),t);if(typeof r=="function"){r(null,n);return}return n};ae.prototype.admin=function(){let e=Vw();return new e(this,this.s.topology,this.s.promiseLibrary)};var GK=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs","bsonRegExp"];ae.prototype.collection=XB({name:"Db.collection",deprecatedOptions:["strict"],optionsIndex:1},function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},t=Object.assign({},t),t.promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new Yw(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined);for(let i of GK)!(i in t)&&this.s.options[i]!==void 0&&(t[i]=this.s.options[i]);if(t=EK(t,this.s.options),t==null||!t.strict)try{let i=new GB(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return r&&r(null,i),i}catch(i){if(i instanceof YB&&r)return r(i);throw i}if(typeof r!="function")throw kB(`A callback is required in strict mode. While getting collection ${e}`);if(this.serverConfig&&this.serverConfig.isDestroyed())return r(new YB("topology was destroyed"));let n=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},n).toArray((i,s)=>{if(i!=null)return dh(r,i,null);if(s.length===0)return dh(r,kB(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return dh(r,null,new GB(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(a){return dh(r,a,null)}})});ae.prototype.createCollection=XB({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},t.promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new Yw(t.readConcern.level):this.readConcern;let n=new PK(this,e,t);return Zt(this.s.topology,n,r)});ae.prototype.stats=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r={dbStats:!0};e.scale!=null&&(r.scale=e.scale),e.readPreference==null&&this.s.readPreference&&(e.readPreference=this.s.readPreference);let n=new qK(this,e,null,r);return Zt(this.s.topology,n,t)};ae.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new SK(this.s.topology,new $K(this,e,t),t)};ae.prototype.eval=vu(function(e,t,r,n){let i=Array.prototype.slice.call(arguments,1);return n=typeof i[i.length-1]=="function"?i.pop():void 0,t=i.length?i.shift():t,r=i.length?i.shift()||{}:{},kw(this.s.topology,AK,[this,e,t,r,n])},"Db.eval is deprecated as of MongoDB version 3.2");ae.prototype.renameCollection=function(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=Object.assign({},r,{readPreference:ph.PRIMARY}),r.new_collection=!0;let i=new HK(this.collection(e),t,r);return Zt(this.s.topology,i,n)};ae.prototype.dropCollection=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new jK(this,e,t);return Zt(this.s.topology,n,r)};ae.prototype.dropDatabase=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new UK(this,e);return Zt(this.s.topology,r,t)};ae.prototype.collections=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new xK(this,e);return Zt(this.s.topology,r,t)};ae.prototype.executeDbAdminCommand=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},t.readPreference=ph.resolve(this,t);let n=new WK(this,e,t);return Zt(this.s.topology,n,r)};ae.prototype.createIndex=function(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=r?Object.assign({},r):{};let i=new LK(this,e,t,r);return Zt(this.s.topology,i,n)};ae.prototype.ensureIndex=vu(function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},kw(this.s.topology,CK,[this,e,t,r,n])},"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0");ae.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)};ae.prototype.addUser=function(e,t,r,n){typeof r=="function"&&(n=r,r={}),r=r||{},typeof e=="string"&&t!=null&&typeof t=="object"&&(r=t,t=null);let i=new MK(this,e,t,r);return Zt(this.s.topology,i,n)};ae.prototype.removeUser=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new VK(this,e,t);return Zt(this.s.topology,n,r)};ae.prototype.setProfilingLevel=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new kK(this,e,t);return Zt(this.s.topology,n,r)};ae.prototype.profilingInfo=vu(function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},kw(this.s.topology,IK,[this,e,t])},"Db.profilingInfo is deprecated. Query the system.profile collection directly.");ae.prototype.profilingLevel=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new zK(this,e);return Zt(this.s.topology,r,t)};ae.prototype.indexInformation=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new FK(this,e,t);return Zt(this.s.topology,n,r)};ae.prototype.unref=function(){this.s.topology.unref()};ae.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new _K(this,e,t)};ae.prototype.getLogger=function(){return this.s.logger};ae.SYSTEM_NAMESPACE_COLLECTION=So.SYSTEM_NAMESPACE_COLLECTION;ae.SYSTEM_INDEX_COLLECTION=So.SYSTEM_INDEX_COLLECTION;ae.SYSTEM_PROFILE_COLLECTION=So.SYSTEM_PROFILE_COLLECTION;ae.SYSTEM_USER_COLLECTION=So.SYSTEM_USER_COLLECTION;ae.SYSTEM_COMMAND_COLLECTION=So.SYSTEM_COMMAND_COLLECTION;ae.SYSTEM_JS_COLLECTION=So.SYSTEM_JS_COLLECTION;JB.exports=ae});var uh=w((Hae,ZB)=>{"use strict";var Gw,Kw,Xw;function KK(){return Gw||(Gw=yo()),Gw}o(KK,"loadCollection");function XK(){return Kw||(Kw=Xr()),Kw}o(XK,"loadCursor");function JK(){return Xw||(Xw=Eu()),Xw}o(JK,"loadDb");ZB.exports={loadCollection:KK,loadCursor:XK,loadDb:JK}});var tR=w((Yae,eR)=>{"use strict";var ZK=b().applyWriteConcern,QK=$().BSON.Code,e5=b().decorateWithCollation,t5=b().decorateWithReadConcern,r5=_t().executeCommand,wo=b().handleCallback,n5=b().isObject,i5=uh().loadDb,s5=F().OperationBase,o5=$().ReadPreference,a5=b().toError,u5=F().Aspect,c5=F().defineAspects,f5=b().decorateWithExplain,l5=re().maxWireVersion,h5=lu().MongoError,d5=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"],Jw=class Jw extends s5{constructor(t,r,n,i){super(i),this.collection=t,this.map=r,this.reduce=n}execute(t){let r=this.collection,n=this.map,i=this.reduce,s=this.options,a={mapReduce:r.collectionName,map:n,reduce:i};for(let u in s)u==="scope"?a[u]=QB(s[u]):d5.indexOf(u)===-1&&(a[u]=s[u]);s=Object.assign({},s),s.readPreference=o5.resolve(r,s),s.readPreference!==!1&&s.readPreference!=="primary"&&s.out&&s.out.inline!==1&&s.out!=="inline"?(s.readPreference="primary",ZK(a,{db:r.s.db,collection:r},s)):t5(a,r,s),s.bypassDocumentValidation===!0&&(a.bypassDocumentValidation=s.bypassDocumentValidation);try{e5(a,r,s)}catch(u){return t(u,null)}if(this.explain){if(l5(r.s.topology)<9){t(new h5("server does not support explain on mapReduce"));return}a=f5(a,this.explain)}r5(r.s.db,a,s,(u,c)=>{if(u)return wo(t,u);if(c.ok!==1||c.err||c.errmsg)return wo(t,a5(c));if(this.explain)return t(void 0,c);let f={};if(c.timeMillis&&(f.processtime=c.timeMillis),c.counts&&(f.counts=c.counts),c.timing&&(f.timing=c.timing),c.results)return s.verbose==null||!s.verbose?wo(t,null,c.results):wo(t,null,{results:c.results,stats:f});let h=null;if(c.result!=null&&typeof c.result=="object"){let l=c.result,d=i5();h=new d(l.db,r.s.db.s.topology,r.s.db.s.options).collection(l.collection)}else h=r.s.db.collection(c.result);if(s.verbose==null||!s.verbose)return wo(t,u,h);wo(t,u,{collection:h,stats:f})})}};o(Jw,"MapReduceOperation");var yh=Jw;function QB(e){if(!n5(e)||e._bsontype==="ObjectID")return e;let t=Object.keys(e),r,n={};for(let i=t.length-1;i>=0;i--)r=t[i],typeof e[r]=="function"?n[r]=new QK(String(e[r])):n[r]=QB(e[r]);return n}o(QB,"processScope");c5(yh,[u5.EXPLAINABLE]);eR.exports=yh});var nR=w((Kae,rR)=>{"use strict";var p5=F().Aspect,m5=F().defineAspects,y5=Jr(),g5=bt().serverType,S5=bt().ServerType,w5=$().MongoError,Zw=class Zw extends y5{constructor(t,r){super(t,r),this.collectionName=t.collectionName}execute(t,r){if(g5(t)!==S5.Standalone){r(new w5("reIndex can only be executed on standalone servers."));return}super.executeCommand(t,{reIndex:this.collectionName},(n,i)=>{if(n){r(n);return}r(null,!!i.ok)})}};o(Zw,"ReIndexOperation");var gh=Zw;m5(gh,[p5.EXECUTE_WITH_SELECTION]);rR.exports=gh});var sR=w((Jae,iR)=>{"use strict";var O5=F().OperationBase,v5=$t().updateDocuments,E5=b().hasAtomicOperators,eO=class eO extends O5{constructor(t,r,n,i){if(super(i),E5(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=t,this.filter=r,this.replacement=n}execute(t){let r=this.collection,n=this.filter,i=this.replacement,s=this.options;s.multi=!1,v5(r,n,i,s,(a,u)=>_5(a,u,i,t))}};o(eO,"ReplaceOneOperation");var Qw=eO;function _5(e,t,r,n){if(n!=null){if(e&&n)return n(e);if(t==null)return n(null,{result:{ok:1}});t.modifiedCount=t.result.nModified!=null?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[r],n&&n(null,t)}}o(_5,"replaceCallback");iR.exports=Qw});var aR=w((Qae,oR)=>{"use strict";var T5=F().Aspect,N5=Lr(),b5=F().defineAspects,tO=class tO extends N5{constructor(t,r){super(t.s.db,r,t)}_buildCommand(){let t=this.collection,r=this.options,n={collStats:t.collectionName};return r.scale!=null&&(n.scale=r.scale),n}};o(tO,"StatsOperation");var Sh=tO;b5(Sh,T5.READ_OPERATION);oR.exports=Sh});var cR=w((tue,uR)=>{"use strict";var C5=F().OperationBase,A5=$t().updateDocuments,I5=b().hasAtomicOperators,B5=F().Aspect,R5=F().defineAspects,rO=class rO extends C5{constructor(t,r,n,i){if(super(i),!I5(n))throw new TypeError("Update document requires atomic operators");this.collection=t,this.filter=r,this.update=n}execute(t){let r=this.collection,n=this.filter,i=this.update,s=this.options;s.multi=!0,A5(r,n,i,s,(a,u)=>{if(t!=null){if(a)return t(a);if(u==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,u.result);u.modifiedCount=u.result.nModified!=null?u.result.nModified:u.result.n,u.upsertedId=Array.isArray(u.result.upserted)&&u.result.upserted.length>0?u.result.upserted[0]:null,u.upsertedCount=Array.isArray(u.result.upserted)&&u.result.upserted.length?u.result.upserted.length:0,u.matchedCount=Array.isArray(u.result.upserted)&&u.result.upserted.length>0?0:u.result.n,t(null,u)}})}};o(rO,"UpdateManyOperation");var wh=rO;R5(wh,[B5.EXPLAINABLE]);uR.exports=wh});var lR=w((nue,fR)=>{"use strict";var M5=F().OperationBase,x5=$t().updateDocuments,q5=b().hasAtomicOperators,D5=F().Aspect,P5=F().defineAspects,nO=class nO extends M5{constructor(t,r,n,i){if(super(i),!q5(n))throw new TypeError("Update document requires atomic operators");this.collection=t,this.filter=r,this.update=n}execute(t){let r=this.collection,n=this.filter,i=this.update,s=this.options;s.multi=!1,x5(r,n,i,s,(a,u)=>{if(t!=null){if(a)return t(a);if(u==null)return t(null,{result:{ok:1}});if(this.explain)return t(void 0,u.result);u.modifiedCount=u.result.nModified!=null?u.result.nModified:u.result.n,u.upsertedId=Array.isArray(u.result.upserted)&&u.result.upserted.length>0?u.result.upserted[0]:null,u.upsertedCount=Array.isArray(u.result.upserted)&&u.result.upserted.length?u.result.upserted.length:0,u.matchedCount=Array.isArray(u.result.upserted)&&u.result.upserted.length>0?0:u.result.n,t(null,u)}})}};o(nO,"UpdateOneOperation");var Oh=nO;P5(Oh,[D5.EXPLAINABLE]);fR.exports=Oh});var yo=w((sue,OR)=>{"use strict";var fr=require("util").deprecate,vh=b().deprecateOptions,hR=b().emitWarningOnce,L5=b().checkCollectionName,j5=$().BSON.ObjectID,dR=$().MongoError,pR=b().normalizeHintField,U5=b().decorateCommand,W5=b().decorateWithCollation,F5=b().decorateWithReadConcern,$5=b().formattedOrderClause,Oo=$().ReadPreference,z5=u1(),V5=h1(),H5=mh(),vo=b().executeLegacyOperation,k5=an(),Y5=Ui(),G5=b().MongoDBNamespace,K5=Wl(),X5=$l(),J5=uo().ensureIndex,Z5=uo().group,Q5=uo().parallelCollectionScan,e7=$t().removeDocuments,t7=uo().save,r7=$t().updateDocuments,n7=pu(),i7=w0(),s7=E0(),mR=T0(),o7=_1(),a7=N1(),u7=C1(),c7=Gl().DropCollectionOperation,f7=U0(),l7=P1(),yR=j1(),h7=F1(),d7=V1(),gR=Ou(),p7=X1(),m7=Z1(),y7=eB(),g7=rB(),S7=iB(),w7=oB(),O7=ow(),v7=cB(),E7=lB(),_7=mB(),T7=gB(),N7=tR(),b7=pw(),C7=Lw(),A7=nR(),I7=sR(),B7=aR(),R7=cR(),M7=lR(),Me=zs(),x7=["ignoreUndefined"];function X(e,t,r,n,i,s){L5(n);let a=null,u=s==null||s.slaveOk==null?e.slaveOk:s.slaveOk,c=s==null||s.serializeFunctions==null?e.s.options.serializeFunctions:s.serializeFunctions,f=s==null||s.raw==null?e.s.options.raw:s.raw,h=s==null||s.promoteLongs==null?e.s.options.promoteLongs:s.promoteLongs,l=s==null||s.promoteValues==null?e.s.options.promoteValues:s.promoteValues,d=s==null||s.promoteBuffers==null?e.s.options.promoteBuffers:s.promoteBuffers,m=s==null||s.bsonRegExp==null?e.s.options.bsonRegExp:s.bsonRegExp,S=null,E=new G5(r,n),O=s.promiseLibrary||Promise;i=i??j5,this.s={pkFactory:i,db:e,topology:t,options:s,namespace:E,readPreference:Oo.fromOptions(s),slaveOk:u,serializeFunctions:c,raw:f,promoteLongs:h,promoteValues:l,promoteBuffers:d,bsonRegExp:m,internalHint:a,collectionHint:S,promiseLibrary:O,readConcern:Y5.fromOptions(s),writeConcern:k5.fromOptions(s)}}o(X,"Collection");Object.defineProperty(X.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}});Object.defineProperty(X.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}});Object.defineProperty(X.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}});Object.defineProperty(X.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern==null?this.s.db.readConcern:this.s.readConcern}});Object.defineProperty(X.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference==null?this.s.db.readPreference:this.s.readPreference}});Object.defineProperty(X.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern==null?this.s.db.writeConcern:this.s.writeConcern}});Object.defineProperty(X.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=pR(e)}});var SR=["maxScan","fields","snapshot","oplogReplay"];X.prototype.find=vh({name:"collection.find",deprecatedOptions:SR,optionsIndex:1},function(e,t,r){typeof r=="object"&&hR("Third parameter to `find()` must be a callback or undefined");let n=e;typeof r!="function"&&(typeof t=="function"?(r=t,t=void 0):t==null&&(r=typeof n=="function"?n:void 0,n=typeof n=="object"?n:void 0)),n=n??{};let i=n;if(Buffer.isBuffer(i)){let f=i[0]|i[1]<<8|i[2]<<16|i[3]<<24;if(f!==i.length){let h=new Error("query selector raw message size does not match message header size ["+i.length+"] != ["+f+"]");throw h.name="MongoError",h}}n!=null&&n._bsontype==="ObjectID"&&(n={_id:n}),t||(t={});let s=t.projection||t.fields;s&&!Buffer.isBuffer(s)&&Array.isArray(s)&&(s=s.length?s.reduce((f,h)=>(f[h]=1,f),{}):{_id:1});let a=Object.assign({},t);for(let f in this.s.options)x7.indexOf(f)!==-1&&(a[f]=this.s.options[f]);if(a.skip=t.skip?t.skip:0,a.limit=t.limit?t.limit:0,a.raw=typeof t.raw=="boolean"?t.raw:this.s.raw,a.hint=t.hint!=null?pR(t.hint):this.s.collectionHint,a.timeout=typeof t.timeout>"u"?void 0:t.timeout,a.slaveOk=t.slaveOk!=null?t.slaveOk:this.s.db.slaveOk,a.readPreference=Oo.resolve(this,a),a.readPreference!=null&&(a.readPreference!=="primary"||a.readPreference.mode!=="primary")&&(a.slaveOk=!0),n!=null&&typeof n!="object")throw dR.create({message:"query selector must be an object",driver:!0});let u={find:this.s.namespace.toString(),limit:a.limit,skip:a.skip,query:n};typeof t.allowDiskUse=="boolean"&&(u.allowDiskUse=t.allowDiskUse),typeof a.awaitdata=="boolean"&&(a.awaitData=a.awaitdata),typeof a.timeout=="boolean"&&(a.noCursorTimeout=!a.timeout),U5(u,a,["session","collation"]),s&&(u.fields=s),a.db=this.s.db,a.promiseLibrary=this.s.promiseLibrary,a.raw==null&&typeof this.s.raw=="boolean"&&(a.raw=this.s.raw),a.promoteLongs==null&&typeof this.s.promoteLongs=="boolean"&&(a.promoteLongs=this.s.promoteLongs),a.promoteValues==null&&typeof this.s.promoteValues=="boolean"&&(a.promoteValues=this.s.promoteValues),a.promoteBuffers==null&&typeof this.s.promoteBuffers=="boolean"&&(a.promoteBuffers=this.s.promoteBuffers),a.bsonRegExp==null&&typeof this.s.bsonRegExp=="boolean"&&(a.bsonRegExp=this.s.bsonRegExp),u.sort&&(u.sort=$5(u.sort)),F5(u,this,t);try{W5(u,this,t)}catch(f){if(typeof r=="function")return r(f,null);throw f}let c=this.s.topology.cursor(new h7(this,this.s.namespace,u,a),a);if(typeof r=="function"){r(null,c);return}return c});X.prototype.insertOne=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined);let n=new E7(this,e,t);return Me(this.s.topology,n,r)};X.prototype.insertMany=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t?Object.assign({},t):{ordered:!0};let n=new v7(this,e,t);return Me(this.s.topology,n,r)};X.prototype.bulkWrite=function(e,t,r){if(typeof t=="function"&&(r=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw dR.create({message:"operations must be an array of documents",driver:!0});let n=new i7(this,e,t);return Me(this.s.topology,n,r)};X.prototype.insert=fr(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],t.keepGoing===!0&&(t.ordered=!1),this.insertMany(e,t,r)},"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.");X.prototype.updateOne=function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=Object.assign({},r),this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Me(this.s.topology,new M7(this,e,t,r),n)};X.prototype.replaceOne=function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=Object.assign({},r),this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Me(this.s.topology,new I7(this,e,t,r),n)};X.prototype.updateMany=function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=Object.assign({},r),this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Me(this.s.topology,new R7(this,e,t,r),n)};X.prototype.update=fr(function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),vo(this.s.topology,r7,[this,e,t,r,n])},"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.");X.prototype.deleteOne=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined);let n=new a7(this,e,t);return Me(this.s.topology,n,r)};X.prototype.removeOne=X.prototype.deleteOne;X.prototype.deleteMany=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined);let n=new o7(this,e,t);return Me(this.s.topology,n,r)};X.prototype.removeMany=X.prototype.deleteMany;X.prototype.remove=fr(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined),vo(this.s.topology,e7,[this,e,t,r])},"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.");X.prototype.save=fr(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined),vo(this.s.topology,t7,[this,e,t,r])},"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.");X.prototype.findOne=vh({name:"collection.find",deprecatedOptions:SR,optionsIndex:1},function(e,t,r){typeof r=="object"&&hR("Third parameter to `findOne()` must be a callback or undefined"),typeof e=="function"&&(r=e,e={},t={}),typeof t=="function"&&(r=t,t={}),e=e||{},t=t||{};let n=new d7(this,e,t);return Me(this.s.topology,n,r)});X.prototype.rename=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=Object.assign({},t,{readPreference:Oo.PRIMARY});let n=new C7(this,e,t);return Me(this.s.topology,n,r)};X.prototype.drop=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new c7(this.s.db,this.collectionName,e);return Me(this.s.topology,r,t)};X.prototype.options=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new b7(this,e);return Me(this.s.topology,r,t)};X.prototype.isCapped=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new _7(this,e);return Me(this.s.topology,r,t)};X.prototype.createIndex=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new mR(this,this.collectionName,e,t);return Me(this.s.topology,n,r)};X.prototype.createIndexes=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t?Object.assign({},t):{},typeof t.maxTimeMS!="number"&&delete t.maxTimeMS;let n=new mR(this,this.collectionName,e,t);return Me(this.s.topology,n,r)};X.prototype.dropIndex=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift()||{}:{},t.readPreference=Oo.PRIMARY;let i=new f7(this,e,t);return Me(this.s.topology,i,r)};X.prototype.dropIndexes=function(e,t){typeof e=="function"&&(t=e,e={}),e=e?Object.assign({},e):{},typeof e.maxTimeMS!="number"&&delete e.maxTimeMS;let r=new l7(this,e);return Me(this.s.topology,r,t)};X.prototype.dropAllIndexes=fr(X.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead.");X.prototype.reIndex=fr(function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new A7(this,e);return Me(this.s.topology,r,t)},"collection.reIndex is deprecated. Use db.command instead.");X.prototype.listIndexes=function(e){return new X5(this.s.topology,new T7(this,e),e)};X.prototype.ensureIndex=fr(function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},vo(this.s.topology,J5,[this,e,t,r])},"collection.ensureIndex is deprecated. Use createIndexes instead.");X.prototype.indexExists=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n=new w7(this,e,t);return Me(this.s.topology,n,r)};X.prototype.indexInformation=function(e,t){let r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]=="function"?r.pop():void 0,e=r.length?r.shift()||{}:{};let n=new O7(this.s.db,this.collectionName,e);return Me(this.s.topology,n,t)};X.prototype.count=fr(function(e,t,r){let n=Array.prototype.slice.call(arguments,0);return r=typeof n[n.length-1]=="function"?n.pop():void 0,e=n.length?n.shift()||{}:{},t=n.length?n.shift()||{}:{},typeof t=="function"&&(r=t,t={}),t=t||{},Me(this.s.topology,new yR(this,Object.assign({query:e},t)),r)},"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead");X.prototype.estimatedDocumentCount=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new yR(this,e);return Me(this.s.topology,r,t)};X.prototype.countDocuments=function(e,t,r){let n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]=="function"?n.pop():void 0,e=n.length?n.shift()||{}:{},t=n.length?n.shift()||{}:{};let i=new s7(this,e,t);return Me(this.s.topology,i,r)};X.prototype.distinct=function(e,t,r,n){let i=Array.prototype.slice.call(arguments,1);n=typeof i[i.length-1]=="function"?i.pop():void 0;let s=i.length?i.shift()||{}:{},a=i.length?i.shift()||{}:{},u=new u7(this,e,s,a);return Me(this.s.topology,u,n)};X.prototype.indexes=function(e,t){typeof e=="function"&&(t=e,e={}),e=e||{};let r=new S7(this,e);return Me(this.s.topology,r,t)};X.prototype.stats=function(e,t){let r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]=="function"?r.pop():void 0,e=r.length?r.shift()||{}:{};let n=new B7(this,e);return Me(this.s.topology,n,t)};X.prototype.findOneAndDelete=function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},this.s.options.ignoreUndefined&&(t=Object.assign({},t),t.ignoreUndefined=this.s.options.ignoreUndefined),Me(this.s.topology,new p7(this,e,t),r)};X.prototype.findOneAndReplace=vh({name:"collection.findOneAndReplace",deprecatedOptions:["returnOriginal"],optionsIndex:2},function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Me(this.s.topology,new m7(this,e,t,r),n)});X.prototype.findOneAndUpdate=vh({name:"collection.findOneAndUpdate",deprecatedOptions:["returnOriginal"],optionsIndex:2},function(e,t,r,n){return typeof r=="function"&&(n=r,r={}),r=r||{},this.s.options.ignoreUndefined&&(r=Object.assign({},r),r.ignoreUndefined=this.s.options.ignoreUndefined),Me(this.s.topology,new y7(this,e,t,r),n)});X.prototype.findAndModify=fr(wR,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.");X.prototype._findAndModify=wR;function wR(e,t,r,n,i){let s=Array.prototype.slice.call(arguments,1);return i=typeof s[s.length-1]=="function"?s.pop():void 0,t=s.length?s.shift()||[]:[],r=s.length?s.shift():null,n=s.length?s.shift()||{}:{},n=Object.assign({},n),n.readPreference=Oo.PRIMARY,Me(this.s.topology,new gR(this,e,t,r,n),i)}o(wR,"_findAndModify");X.prototype.findAndRemove=fr(function(e,t,r,n){let i=Array.prototype.slice.call(arguments,1);return n=typeof i[i.length-1]=="function"?i.pop():void 0,t=i.length?i.shift()||[]:[],r=i.length?i.shift()||{}:{},r.remove=!0,Me(this.s.topology,new gR(this,e,t,null,r),n)},"collection.findAndRemove is deprecated. Use findOneAndDelete instead.");X.prototype.aggregate=function(e,t,r){if(Array.isArray(e))typeof t=="function"&&(r=t,t={}),t==null&&r==null&&(t={});else{let i=Array.prototype.slice.call(arguments,0);r=i.pop();let s=i[i.length-1];t=s&&(s.readPreference||s.explain||s.cursor||s.out||s.maxTimeMS||s.hint||s.allowDiskUse)?i.pop():{},e=i}let n=new K5(this.s.topology,new n7(this,e,t),t);if(typeof r=="function"){r(null,n);return}return n};X.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new H5(this,e,t)};X.prototype.parallelCollectionScan=fr(function(e,t){return typeof e=="function"&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,e=Object.assign({},e),e.readPreference=Oo.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),vo(this.s.topology,Q5,[this,e,t],{skipSessions:!0})},"parallelCollectionScan is deprecated in MongoDB v4.1");X.prototype.geoHaystackSearch=fr(function(e,t,r,n){let i=Array.prototype.slice.call(arguments,2);n=typeof i[i.length-1]=="function"?i.pop():void 0,r=i.length?i.shift()||{}:{};let s=new g7(this,e,t,r);return Me(this.s.topology,s,n)},"geoHaystackSearch is deprecated, and will be removed in a future version.");X.prototype.group=fr(function(e,t,r,n,i,s,a,u){let c=Array.prototype.slice.call(arguments,3);return u=typeof c[c.length-1]=="function"?c.pop():void 0,n=c.length?c.shift():null,i=c.length?c.shift():null,s=c.length?c.shift():null,a=c.length?c.shift()||{}:{},typeof i!="function"&&(s=i,i=null),!Array.isArray(e)&&e instanceof Object&&typeof e!="function"&&e._bsontype!=="Code"&&(e=Object.keys(e)),typeof n=="function"&&(n=n.toString()),typeof i=="function"&&(i=i.toString()),s=s??!0,vo(this.s.topology,Z5,[this,e,t,r,n,i,s,a,u])},"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.");X.prototype.mapReduce=function(e,t,r,n){if(typeof r=="function"&&(n=r,r={}),r.out==null)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");typeof e=="function"&&(e=e.toString()),typeof t=="function"&&(t=t.toString()),typeof r.finalize=="function"&&(r.finalize=r.finalize.toString());let i=new N7(this,e,t,r);return Me(this.s.topology,i,n)};X.prototype.initializeUnorderedBulkOp=function(e){return e=e||{},e.ignoreUndefined==null&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,z5(this.s.topology,this,e)};X.prototype.initializeOrderedBulkOp=function(e){return e=e||{},e.ignoreUndefined==null&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,V5(this.s.topology,this,e)};X.prototype.getLogger=function(){return this.s.db.s.logger};OR.exports=X});var mh=w((aue,BR)=>{"use strict";var q7=Hf(),D7=require("events"),P7=lu().isResumableError,Tu=$().MongoError,L7=Xr(),j7=re().relayEvents,sO=re().maxWireVersion,iO=b().maybePromise,vR=b().now,U7=b().calculateDurationInMs,W7=pu(),_u=Symbol("resumeQueue"),NR=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],bR=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(NR),Eh={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")},cO=class cO extends D7{constructor(t,r,n){super();let i=yo(),s=Eu(),a=Eo();if(this.pipeline=r||[],this.options=n||{},this.parent=t,this.namespace=t.s.namespace,t instanceof i)this.type=Eh.COLLECTION,this.topology=t.s.db.serverConfig;else if(t instanceof s)this.type=Eh.DATABASE,this.topology=t.serverConfig;else if(t instanceof a)this.type=Eh.CLUSTER,this.topology=t.topology;else throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.promiseLibrary=t.s.promiseLibrary,!this.options.readPreference&&t.s.readPreference&&(this.options.readPreference=t.s.readPreference),this[_u]=new q7,this.cursor=CR(this,n),this.closed=!1,this.on("newListener",u=>{u==="change"&&this.cursor&&this.listenerCount("change")===0&&this.cursor.on("data",c=>uO(this,c))}),this.on("removeListener",u=>{u==="change"&&this.listenerCount("change")===0&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(t){return iO(this.parent,t,r=>{_R(this,(n,i)=>{if(n)return r(n);i.hasNext(r)})})}next(t){return iO(this.parent,t,r=>{_R(this,(n,i)=>{if(n)return r(n);i.next((s,a)=>{if(s){this[_u].push(()=>this.next(r)),IR(this,s,r);return}uO(this,a,r)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(t){return iO(this.parent,t,r=>{if(this.closed||(this.closed=!0,!this.cursor))return r();let n=this.cursor;return n.close(i=>(["data","close","end","error"].forEach(s=>n.removeAllListeners(s)),this.cursor=void 0,r(i)))})}pipe(t,r){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(t),this.cursor.pipe(t,r)}unpipe(t){return this.pipeDestinations&&this.pipeDestinations.indexOf(t)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(t),1),this.cursor.unpipe(t)}stream(t){return this.streamOptions=t,this.cursor.stream(t)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}};o(cO,"ChangeStream");var oO=cO,fO=class fO extends L7{constructor(t,r,n){super(t,r,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(t){this._resumeToken=t,this.emit("resumeTokenChanged",t)}get resumeToken(){return this._resumeToken}get resumeOptions(){let t={};for(let r of bR)this.options[r]&&(t[r]=this.options[r]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(r=>delete t[r]),this.resumeToken){let r=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";t[r]=this.resumeToken}else this.startAtOperationTime&&sO(this.server)>=7&&(t.startAtOperationTime=this.startAtOperationTime);return t}cacheResumeToken(t){this.bufferedCount()===0&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=t,this.hasReceived=!0}_processBatch(t,r){let n=r.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,n[t].length===0&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(t){super._initializeCursor((r,n)=>{if(r||n==null){t(r,n);return}let i=n.documents[0];this.startAtOperationTime==null&&this.resumeAfter==null&&this.startAfter==null&&sO(this.server)>=7&&(this.startAtOperationTime=i.operationTime),this._processBatch("firstBatch",i),this.emit("init",n),this.emit("response"),t(r,n)})}_getMore(t){super._getMore((r,n)=>{if(r){t(r);return}this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),t(r,n)})}};o(fO,"ChangeStreamCursor");var aO=fO;function CR(e,t){let r={fullDocument:t.fullDocument||"default"};ER(r,t,NR),e.type===Eh.CLUSTER&&(r.allChangesForCluster=!0);let n=[{$changeStream:r}].concat(e.pipeline),i=ER({},t,bR),s=new aO(e.topology,new W7(e.parent,n,t),i);if(j7(s,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&s.on("data",function(a){uO(e,a)}),s.on("error",function(a){IR(e,a)}),e.pipeDestinations){let a=s.stream(e.streamOptions);for(let u of e.pipeDestinations)a.pipe(u)}return s}o(CR,"createChangeStreamCursor");function ER(e,t,r){return r.forEach(n=>{t[n]&&(e[n]=t[n])}),e}o(ER,"applyKnownOptions");var F7=3e4;function AR(e,t,r){setTimeout(()=>{t&&t.start==null&&(t.start=vR());let n=t.start||vR(),i=t.timeout||F7,s=t.readPreference;if(e.isConnected({readPreference:s}))return r();if(U7(n)>i)return r(new Tu("Timed out waiting for connection"));AR(e,t,r)},500)}o(AR,"waitForTopologyConnected");function uO(e,t,r){let n=e.cursor;if(t==null&&(e.closed=!0),e.closed){r&&r(new Tu("ChangeStream is closed"));return}if(t&&!t._id){let i=new Error("A change stream document has been received that lacks a resume token (_id).");return r?r(i):e.emit("error",i)}return n.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,r?r(void 0,t):e.emit("change",t)}o(uO,"processNewChange");function IR(e,t,r){let n=e.topology,i=e.cursor;if(e.closed){r&&r(new Tu("ChangeStream is closed"));return}function s(u){e.cursor=u,TR(e)}o(s,"resumeWithCursor");function a(u){r||(e.emit("error",u),e.emit("close")),TR(e,u),e.closed=!0}if(o(a,"unresumableError"),i&&P7(t,sO(i.server))){e.cursor=void 0,["data","close","end","error"].forEach(u=>i.removeAllListeners(u)),i.close(),AR(n,{readPreference:i.options.readPreference},u=>{if(u)return a(u);let c=CR(e,i.resumeOptions);if(!r)return s(c);c.hasNext(f=>{if(f)return a(f);s(c)})});return}return r?r(t):e.emit("error",t)}o(IR,"processError");function _R(e,t){if(e.isClosed()){t(new Tu("ChangeStream is closed."));return}if(e.cursor){t(void 0,e.cursor);return}e[_u].push(t)}o(_R,"getCursor");function TR(e,t){for(;e[_u].length;){let r=e[_u].pop();if(e.isClosed()&&!t){r(new Tu("Change Stream is not open."));return}r(t,e.cursor)}}o(TR,"processResumeQueue");BR.exports=oO});var gi=w(_h=>{"use strict";var $7=require("events"),ss=$().MongoError,Nu=require("util").format,lO=$().ReadPreference,z7=$().Sessions.ClientSession,_o=o(function(e,t){var r=this,n=[];t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:n,storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return r.s.storedOps.length}})},"Store");_o.prototype.add=function(e,t,r,n,i){if(this.s.storeOptions.force)return i(ss.create({message:"db closed by application",driver:!0}));if(this.s.storeOptions.bufferMaxEntries===0)return i(ss.create({message:Nu("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){for(;this.s.storedOps.length>0;){var s=this.s.storedOps.shift();s.c(ss.create({message:Nu("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}return}this.s.storedOps.push({t:e,n:t,o:r,op:n,c:i})};_o.prototype.addObjectAndMethod=function(e,t,r,n,i){if(this.s.storeOptions.force)return i(ss.create({message:"db closed by application",driver:!0}));if(this.s.storeOptions.bufferMaxEntries===0)return i(ss.create({message:Nu("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){for(;this.s.storedOps.length>0;){var s=this.s.storedOps.shift();s.c(ss.create({message:Nu("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}return}this.s.storedOps.push({t:e,m:r,o:t,p:n,c:i})};_o.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||ss.create({message:Nu("no connection available for operation"),driver:!0}))};var RR=["primary","primaryPreferred","nearest","secondaryPreferred"],MR=["secondary","secondaryPreferred"];_o.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var r=typeof e.executePrimary=="boolean"?e.executePrimary:!0,n=typeof e.executeSecondary=="boolean"?e.executeSecondary:!0;t.length>0;){var i=t.shift();i.t==="cursor"?(r&&n||r&&i.o.options&&i.o.options.readPreference&&RR.indexOf(i.o.options.readPreference.mode)!==-1||!r&&n&&i.o.options&&i.o.options.readPreference&&MR.indexOf(i.o.options.readPreference.mode)!==-1)&&i.o[i.m].apply(i.o,i.p):i.t==="auth"?this.s.topology[i.t].apply(this.s.topology,i.o):r&&n?this.s.topology[i.t](i.n,i.o,i.op,i.c):r&&i.op&&i.op.readPreference&&RR.indexOf(i.op.readPreference.mode)!==-1?this.s.topology[i.t](i.n,i.o,i.op,i.c):!r&&n&&i.op&&i.op.readPreference&&MR.indexOf(i.op.readPreference.mode)!==-1&&this.s.topology[i.t](i.n,i.o,i.op,i.c)}};_o.prototype.all=function(){return this.s.storedOps};var xR=o(function(e){var t=o(function(l,d,m){Object.defineProperty(l,d,{enumerable:!0,get:function(){return m}})},"setup_get_property"),r=!1,n=!1,i=!1,s=!1,a=!1,u=!1,c=e.maxWriteBatchSize||1e3,f=!1,h=!1;e.minWireVersion>=0&&(i=!0),e.maxWireVersion>=1&&(r=!0,s=!0),e.maxWireVersion>=2&&(n=!0),e.maxWireVersion>=3&&(a=!0,u=!0),e.maxWireVersion>=5&&(f=!0,h=!0),e.minWireVersion==null&&(e.minWireVersion=0),e.maxWireVersion==null&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",r),t(this,"hasWriteCommands",n),t(this,"hasTextSearch",i),t(this,"hasAuthCommands",s),t(this,"hasListCollectionsCommand",a),t(this,"hasListIndexesCommand",u),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",c),t(this,"commandsTakeWriteConcern",f),t(this,"commandsTakeCollation",h)},"ServerCapabilities"),hO=class hO extends $7{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return this.logicalSessionTimeoutMinutes!=null}startSession(t,r){let n=new z7(this,this.s.sessionPool,t,r);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(t,r){return this.s.coreTopology.endSessions(t,r)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:this.s.coreTopology.lastIsMaster()==null?null:(this.s.sCapabilities=new xR(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(t,r,n,i){this.s.coreTopology.command(t.toString(),r,lO.translate(n),i)}insert(t,r,n,i){this.s.coreTopology.insert(t.toString(),r,n,i)}update(t,r,n,i){this.s.coreTopology.update(t.toString(),r,n,i)}remove(t,r,n,i){this.s.coreTopology.remove(t.toString(),r,n,i)}isConnected(t){return t=t||{},t=lO.translate(t),this.s.coreTopology.isConnected(t)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(t,r,n){return n=n||{},n=lO.translate(n),n.disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(t,r,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(t,r,n){return this.s.coreTopology.selectServer(t,r,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(t,r){this.s.sessions.forEach(n=>n.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),t===!0&&(this.s.storeOptions.force=t,this.s.store.flush()),this.s.coreTopology.destroy({force:typeof t=="boolean"?t:!1},r)}};o(hO,"TopologyBase");var os=hO;Object.defineProperty(os.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}});Object.defineProperty(os.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}});Object.defineProperty(os.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}});Object.defineProperty(os.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}});_h.Store=_o;_h.ServerCapabilities=xR;_h.TopologyBase=os});var mO=w((lue,DR)=>{"use strict";var V7=$().Topology,H7=gi().ServerCapabilities,k7=Xr(),qR=b().translateOptions,pO=class pO extends V7{constructor(t,r){r=r||{};let n=Object.assign({},{cursorFactory:k7,reconnect:!1,emitError:typeof r.emitError=="boolean"?r.emitError:!0,maxPoolSize:typeof r.maxPoolSize=="number"?r.maxPoolSize:typeof r.poolSize=="number"?r.poolSize:10,minPoolSize:typeof r.minPoolSize=="number"?r.minPoolSize:typeof r.minSize=="number"?r.minSize:0,monitorCommands:typeof r.monitorCommands=="boolean"?r.monitorCommands:!1});n=qR(n,r);var i=r.socketOptions&&Object.keys(r.socketOptions).length>0?r.socketOptions:r;n=qR(n,i),n.serverApi=r.serverApi,n.useUnifiedTopology=r.useUnifiedTopology,super(t,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:this.lastIsMaster()==null?null:(this.s.sCapabilities=new H7(this.lastIsMaster()),this.s.sCapabilities)}command(t,r,n,i){super.command(t.toString(),r,n,i)}insert(t,r,n,i){super.insert(t.toString(),r,n,i)}update(t,r,n,i){super.update(t.toString(),r,n,i)}remove(t,r,n,i){super.remove(t.toString(),r,n,i)}};o(pO,"NativeTopology");var dO=pO;DR.exports=dO});var bu=w((due,LR)=>{"use strict";var Y7=$().Server,G7=Xr(),K7=gi().TopologyBase,X7=gi().Store,J7=$().MongoError,Z7=b().MAX_JS_INT,PR=b().translateOptions,Q7=b().filterOptions,eX=b().mergeOptions,tX=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","compression","promiseLibrary","monitorCommands"],yO=class yO extends K7{constructor(t,r,n){super();var i=this;n=Q7(n,tX);let s=n.promiseLibrary;var a={force:!1,bufferMaxEntries:typeof n.bufferMaxEntries=="number"?n.bufferMaxEntries:Z7},u=n.store||new X7(i,a);if(t.indexOf("/")!==-1)r!=null&&typeof r=="object"&&(n=r,r=null);else if(r==null)throw J7.create({message:"port must be specified",driver:!0});var c=typeof n.auto_reconnect=="boolean"?n.auto_reconnect:!0;c=typeof n.autoReconnect=="boolean"?n.autoReconnect:c;var f=eX({},{host:t,port:r,disconnectHandler:u,cursorFactory:G7,reconnect:c,emitError:typeof n.emitError=="boolean"?n.emitError:!0,size:typeof n.poolSize=="number"?n.poolSize:5,monitorCommands:typeof n.monitorCommands=="boolean"?n.monitorCommands:!1});f=PR(f,n);var h=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;f=PR(f,h),this.s={coreTopology:new Y7(f),sCapabilities:null,clonedOptions:f,reconnect:f.reconnect,emitError:f.emitError,poolSize:f.size,storeOptions:a,store:u,host:t,port:r,options:n,sessionPool:null,sessions:new Set,promiseLibrary:s||Promise}}connect(t,r){var n=this;typeof t=="function"&&(r=t,t={}),t==null&&(t=this.s.clonedOptions),typeof r!="function"&&(r=null),t=Object.assign({},this.s.clonedOptions,t),n.s.options=t,n.s.storeOptions.bufferMaxEntries=typeof t.bufferMaxEntries=="number"?t.bufferMaxEntries:-1;var i=o(function(){return function(d){var m=["timeout","error","close"];m.forEach(function(S){n.s.coreTopology.removeListener(S,l[S])}),n.s.coreTopology.removeListener("connect",i);try{r(d)}catch(S){process.nextTick(function(){throw S})}}},"connectErrorHandler"),s=o(function(d){return function(m){d!=="error"&&n.emit(d,m)}},"errorHandler"),a=o(function(){n.emit("reconnect",n),n.s.store.execute()},"reconnectHandler"),u=o(function(d){n.emit("reconnectFailed",d),n.s.store.flush(d)},"reconnectFailedHandler"),c=o(function(){n.s.store.flush()},"destroyHandler"),f=o(function(d){return function(m,S){n.emit(d,m,S)}},"relay"),h=o(function(){["timeout","error","close","destroy"].forEach(function(d){n.s.coreTopology.removeAllListeners(d)}),n.s.coreTopology.on("timeout",s("timeout")),n.s.coreTopology.once("error",s("error")),n.s.coreTopology.on("close",s("close")),n.s.coreTopology.on("destroy",c),n.emit("open",null,n);try{r(null,n)}catch(d){process.nextTick(function(){throw d})}},"connectHandler"),l={timeout:i("timeout"),error:i("error"),close:i("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach(function(d){n.s.coreTopology.removeAllListeners(d)}),n.s.coreTopology.once("timeout",l.timeout),n.s.coreTopology.once("error",l.error),n.s.coreTopology.once("close",l.close),n.s.coreTopology.once("connect",h),n.s.coreTopology.on("reconnect",a),n.s.coreTopology.on("reconnectFailed",u),n.s.coreTopology.on("serverDescriptionChanged",f("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",f("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",f("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",f("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",f("serverOpening")),n.s.coreTopology.on("serverClosed",f("serverClosed")),n.s.coreTopology.on("topologyOpening",f("topologyOpening")),n.s.coreTopology.on("topologyClosed",f("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",f("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",f("commandStarted")),n.s.coreTopology.on("commandSucceeded",f("commandSucceeded")),n.s.coreTopology.on("commandFailed",f("commandFailed")),n.s.coreTopology.on("attemptReconnect",f("attemptReconnect")),n.s.coreTopology.on("monitoring",f("monitoring")),n.s.coreTopology.connect(t)}};o(yO,"Server");var as=yO;Object.defineProperty(as.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}});Object.defineProperty(as.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}});Object.defineProperty(as.prototype,"host",{enumerable:!0,get:function(){return this.s.host}});Object.defineProperty(as.prototype,"port",{enumerable:!0,get:function(){return this.s.port}});LR.exports=as});var SO=w((mue,UR)=>{"use strict";var rX=gi().TopologyBase,nX=$().MongoError,iX=$().Mongos,sX=Xr(),oX=bu(),aX=gi().Store,uX=b().MAX_JS_INT,jR=b().translateOptions,cX=b().filterOptions,fX=b().mergeOptions,lX=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","promiseLibrary","monitorCommands"],gO=class gO extends rX{constructor(t,r){super(),r=r||{};var n=this;r=cX(r,lX);for(var i=0;i0?r.socketOptions:r;f=jR(f,h),this.s={coreTopology:new iX(u,f),sCapabilities:null,debug:f.debug,storeOptions:s,clonedOptions:f,store:a,options:r,sessionPool:null,sessions:new Set,promiseLibrary:r.promiseLibrary||Promise}}connect(t,r){var n=this;typeof t=="function"&&(r=t,t={}),t==null&&(t={}),typeof r!="function"&&(r=null),t=Object.assign({},this.s.clonedOptions,t),n.s.options=t,n.s.storeOptions.bufferMaxEntries=typeof t.bufferMaxEntries=="number"?t.bufferMaxEntries:-1;var i=o(function(){return function(h){var l=["timeout","error","close"];l.forEach(function(d){n.removeListener(d,i)}),n.s.coreTopology.removeListener("connect",i),n.close(!0);try{r(h)}catch(d){process.nextTick(function(){throw d})}}},"connectErrorHandler"),s=o(function(h){return function(l){h!=="error"&&n.emit(h,l)}},"errorHandler"),a=o(function(){n.emit("reconnect"),n.s.store.execute()},"reconnectHandler"),u=o(function(h){return function(l,d){n.emit(h,l,d)}},"relay"),c=o(function(){var h=["timeout","error","close","fullsetup"];h.forEach(function(l){n.s.coreTopology.removeAllListeners(l)}),n.s.coreTopology.on("timeout",s("timeout")),n.s.coreTopology.on("error",s("error")),n.s.coreTopology.on("close",s("close")),n.s.coreTopology.on("fullsetup",function(){n.emit("fullsetup",n)}),n.emit("open",null,n);try{r(null,n)}catch(l){process.nextTick(function(){throw l})}},"connectHandler"),f=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"];f.forEach(function(h){n.s.coreTopology.removeAllListeners(h)}),n.s.coreTopology.on("serverDescriptionChanged",u("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",u("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",u("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",u("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",u("serverOpening")),n.s.coreTopology.on("serverClosed",u("serverClosed")),n.s.coreTopology.on("topologyOpening",u("topologyOpening")),n.s.coreTopology.on("topologyClosed",u("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",u("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",u("commandStarted")),n.s.coreTopology.on("commandSucceeded",u("commandSucceeded")),n.s.coreTopology.on("commandFailed",u("commandFailed")),n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.s.coreTopology.once("connect",c),n.s.coreTopology.on("joined",u("joined")),n.s.coreTopology.on("left",u("left")),n.s.coreTopology.on("reconnect",a),n.s.coreTopology.connect(t)}};o(gO,"Mongos");var Th=gO;Object.defineProperty(Th.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}});UR.exports=Th});var OO=w((gue,FR)=>{"use strict";var hX=bu(),dX=Xr(),pX=$().MongoError,mX=gi().TopologyBase,yX=gi().Store,gX=$().ReplSet,SX=b().MAX_JS_INT,WR=b().translateOptions,wX=b().filterOptions,OX=b().mergeOptions,vX=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"],wO=class wO extends mX{constructor(t,r){super(),r=r||{};var n=this;r=wX(r,vX);for(var i=0;i0?r.socketOptions:r;c=WR(c,f);var h=new gX(u,c);h.on("reconnect",function(){n.emit("reconnect"),a.execute()}),this.s={coreTopology:h,sCapabilities:null,tag:r.tag,storeOptions:s,clonedOptions:c,store:a,options:r,sessionPool:null,sessions:new Set,promiseLibrary:r.promiseLibrary||Promise},c.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return h}})}connect(t,r){var n=this;typeof t=="function"&&(r=t,t={}),t==null&&(t={}),typeof r!="function"&&(r=null),t=Object.assign({},this.s.clonedOptions,t),n.s.options=t,n.s.storeOptions.bufferMaxEntries=typeof t.bufferMaxEntries=="number"?t.bufferMaxEntries:-1;var i=o(function(l){return function(d){l!=="error"&&n.emit(l,d)}},"errorHandler"),s=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"];s.forEach(function(l){n.s.coreTopology.removeAllListeners(l)});var a=o(function(l){return function(d,m){n.emit(l,d,m)}},"relay"),u=o(function(l){return function(d,m){n.emit(l,d,m.lastIsMaster(),m)}},"replsetRelay"),c=o(function(l,d){n.emit("ha",l,d),l==="start"?n.emit("ha_connect",l,d):l==="end"&&n.emit("ha_ismaster",l,d)},"relayHa");n.s.coreTopology.on("joined",u("joined")),n.s.coreTopology.on("left",a("left")),n.s.coreTopology.on("ping",a("ping")),n.s.coreTopology.on("ha",c),n.s.coreTopology.on("serverDescriptionChanged",a("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",a("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",a("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",a("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",a("serverOpening")),n.s.coreTopology.on("serverClosed",a("serverClosed")),n.s.coreTopology.on("topologyOpening",a("topologyOpening")),n.s.coreTopology.on("topologyClosed",a("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",a("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",a("commandStarted")),n.s.coreTopology.on("commandSucceeded",a("commandSucceeded")),n.s.coreTopology.on("commandFailed",a("commandFailed")),n.s.coreTopology.on("fullsetup",function(){n.emit("fullsetup",n,n)}),n.s.coreTopology.on("all",function(){n.emit("all",null,n)});var f=o(function(){n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.emit("open",null,n);try{r(null,n)}catch(l){process.nextTick(function(){throw l})}},"connectHandler"),h=o(function(){return function(l){["timeout","error","close"].forEach(function(d){n.s.coreTopology.removeListener(d,h)}),n.s.coreTopology.removeListener("connect",h),n.s.coreTopology.destroy();try{r(l)}catch(d){n.s.coreTopology.isConnected()||process.nextTick(function(){throw d})}}},"connectErrorHandler");n.s.coreTopology.once("timeout",h("timeout")),n.s.coreTopology.once("error",h("error")),n.s.coreTopology.once("close",h("close")),n.s.coreTopology.once("connect",f),n.s.coreTopology.connect(t)}close(t,r){["timeout","error","close","joined","left"].forEach(n=>this.removeAllListeners(n)),super.close(t,r)}};o(wO,"ReplSet");var Nh=wO;Object.defineProperty(Nh.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}});FR.exports=Nh});var HR=w((wue,VR)=>{"use strict";var EX=$().ReadPreference,vO=require("url"),_X=require("util").format,TX=$().Logger,$R=require("dns"),NX=Ui(),bX=require("querystring"),bh=V().MongoParseError;VR.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};let n;try{n=vO.parse(e,!0)}catch{return r(new Error("URL malformed, cannot be parsed"))}if(n.protocol!=="mongodb:"&&n.protocol!=="mongodb+srv:")return r(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if(n.protocol==="mongodb:")return zR(e,t,r);if(n.hostname.split(".").length<3)return r(new Error("URI does not have hostname, domain name and tld"));if(n.domainLength=n.hostname.split(".").length,e.substring(14).split("/")[0].match(","))return r(new Error("Invalid URI, cannot contain multiple hostnames"));if(n.port)return r(new Error("Ports not accepted with `mongodb+srv` URIs"));let s=`_mongodb._tcp.${n.host}`;$R.resolveSrv(s,function(a,u){if(a)return r(a);if(u.length===0)return r(new Error("No addresses found at host"));for(let d=0;d1)return r(new bh("Multiple text records not allowed"));m=m[0].join("");let S=bX.parse(m),E=Object.keys(S);if(Object.keys(E).some(O=>O.toLowerCase()==="loadbalanced"))return r(new bh("Load balancer mode requires driver version 4+"));if(E.some(O=>O!=="authSource"&&O!=="replicaSet"))return r(new bh("Text record must only set `authSource` or `replicaSet`"));E.length>0&&l.push(m)}l.length&&(h+=`?${l.join("&")}`),zR(h,t,r)})})};function CX(e,t){let r=/^.*?\./,n=`.${e.replace(r,"")}`,i=`.${t.replace(r,"")}`;return!!n.endsWith(i)}o(CX,"matchesParentDomain");function zR(e,t,r){let n,i;try{n=AX(e,t)}catch(s){i=s}return i?r(i,null):r(null,n)}o(zR,"parseHandler");function AX(e,t){let r="",n="",i="",s="admin",a=vO.parse(e,!0);if((a.hostname==null||a.hostname==="")&&e.indexOf(".sock")===-1)throw new Error("No hostname or hostnames provided in connection string");if(a.port==="0")throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(a.port,10))&&parseInt(a.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(a.path&&a.path.length>0&&a.path[0]!=="/"&&e.indexOf(".sock")===-1)throw new Error("Missing delimiting slash between hosts and options");if(a.query)for(let q in a.query){if(q.indexOf("::")!==-1)throw new Error("Double colon in host identifier");if(a.query[q]==="")throw new Error("Query parameter "+q+" is an incomplete value pair")}if(a.auth){let q=a.auth.split(":");if(e.indexOf(a.auth)!==-1&&q.length>2)throw new Error("Username with password containing an unescaped colon");if(e.indexOf(a.auth)!==-1&&a.auth.indexOf("@")!==-1)throw new Error("Username containing an unescaped at-sign")}let c=e.split("?").shift().split(","),f=[];for(let q=0;q1&&H.path.indexOf("::")===-1?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}if(e.indexOf("?")!==-1?(i=e.substr(e.indexOf("?")+1),r=e.substring(10,e.indexOf("?"))):r=e.substring(10),r.indexOf("@")!==-1&&(n=r.split("@")[0],r=r.split("@")[1]),r.split("/").length>2)throw new Error("Unsupported host '"+r.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(r.indexOf(".sock")!==-1){if(r.indexOf(".sock/")!==-1){if(s=r.split(".sock/")[1],s.indexOf("/")!==-1)throw s.split("/").length===2&&s.split("/")[1].length===0?new Error("Illegal trailing backslash after database name"):new Error("More than 1 database name in URL");r=r.split("/",r.indexOf(".sock")+5)}}else if(r.indexOf("/")!==-1){if(r.split("/").length>2)throw r.split("/")[2].length===0?new Error("Illegal trailing backslash after database name"):new Error("More than 1 database name in URL");s=r.split("/")[1],r=r.split("/")[0]}r=decodeURIComponent(r);let h={},l=n||"",d=l.split(":",2),m=decodeURIComponent(d[0]);if(d[0]!==encodeURIComponent(m))throw new Error("Username contains an illegal unescaped character");if(d[0]=m,d[1]){let q=decodeURIComponent(d[1]);if(d[1]!==encodeURIComponent(q))throw new Error("Password contains an illegal unescaped character");d[1]=q}d.length===2&&(h.auth={user:d[0],password:d[1]}),t&&t.auth!=null&&(h.auth=t.auth);let S,E,O,T,R={socketOptions:{}},_={read_preference_tags:[]},N={socketOptions:{}},P={socketOptions:{}};if(h.server_options=R,h.db_options=_,h.rs_options=N,h.mongos_options=P,e.match(/\.sock/)){let q=e.substring(e.indexOf("mongodb://")+10,e.lastIndexOf(".sock")+5);q.indexOf("@")!==-1&&(q=q.split("@")[1]),q=decodeURIComponent(q),O=[{domain_socket:q}]}else{S=r;let q={};O=S.split(",").map(function(H){let ue,j,te;if(te=/\[([^\]]+)\](?::(.+))?/.exec(H))ue=te[1],j=parseInt(te[2],10)||27017;else{let K=H.split(":",2);ue=K[0]||"localhost",j=K[1]!=null?parseInt(K[1],10):27017,ue.indexOf("?")!==-1&&(ue=ue.split(/\?/)[0])}return q[ue+"_"+j]?null:(q[ue+"_"+j]=1,{host:ue,port:j})}).filter(function(H){return H!=null})}if(h.dbName=s||"admin",E=(i||"").split(/[&;]/),E.some(q=>q.toLowerCase()==="loadbalanced"))throw new bh("Load balancer mode requires driver version 4+");if(E.forEach(function(q){if(q){var H=q.split("="),ue=H[0],j=H[1];switch(ue){case"slaveOk":case"slave_ok":R.slave_ok=j==="true",_.slaveOk=j==="true";break;case"maxPoolSize":case"poolSize":R.poolSize=parseInt(j,10),N.poolSize=parseInt(j,10);break;case"appname":h.appname=decodeURIComponent(j);break;case"autoReconnect":case"auto_reconnect":R.auto_reconnect=j==="true";break;case"ssl":if(j==="prefer"){R.ssl=j,N.ssl=j,P.ssl=j;break}R.ssl=j==="true",N.ssl=j==="true",P.ssl=j==="true";break;case"sslValidate":R.sslValidate=j==="true",N.sslValidate=j==="true",P.sslValidate=j==="true";break;case"replicaSet":case"rs_name":N.rs_name=j;break;case"reconnectWait":N.reconnectWait=parseInt(j,10);break;case"retries":N.retries=parseInt(j,10);break;case"readSecondary":case"read_secondary":N.read_secondary=j==="true";break;case"fsync":_.fsync=j==="true";break;case"journal":_.j=j==="true";break;case"safe":_.safe=j==="true";break;case"nativeParser":case"native_parser":_.native_parser=j==="true";break;case"readConcernLevel":_.readConcern=new NX(j);break;case"connectTimeoutMS":R.socketOptions.connectTimeoutMS=parseInt(j,10),N.socketOptions.connectTimeoutMS=parseInt(j,10),P.socketOptions.connectTimeoutMS=parseInt(j,10);break;case"socketTimeoutMS":R.socketOptions.socketTimeoutMS=parseInt(j,10),N.socketOptions.socketTimeoutMS=parseInt(j,10),P.socketOptions.socketTimeoutMS=parseInt(j,10);break;case"w":_.w=parseInt(j,10),isNaN(_.w)&&(_.w=j);break;case"authSource":_.authSource=j;break;case"gssapiServiceName":_.gssapiServiceName=j;break;case"authMechanism":if(j==="GSSAPI")if(h.auth==null){let te=decodeURIComponent(l);if(te.indexOf("@")===-1)throw new Error("GSSAPI requires a provided principal");h.auth={user:te,password:null}}else h.auth.user=decodeURIComponent(h.auth.user);else j==="MONGODB-X509"&&(h.auth={user:decodeURIComponent(l)});if(j!=="GSSAPI"&&j!=="MONGODB-X509"&&j!=="MONGODB-CR"&&j!=="DEFAULT"&&j!=="SCRAM-SHA-1"&&j!=="SCRAM-SHA-256"&&j!=="PLAIN")throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");_.authMechanism=j;break;case"authMechanismProperties":{let te=j.split(","),K={};te.forEach(function(W){let z=W.split(":");K[z[0]]=z[1]}),_.authMechanismProperties=K,typeof K.SERVICE_NAME=="string"&&(_.gssapiServiceName=K.SERVICE_NAME),typeof K.SERVICE_REALM=="string"&&(_.gssapiServiceRealm=K.SERVICE_REALM),typeof K.CANONICALIZE_HOST_NAME=="string"&&(_.gssapiCanonicalizeHostName=K.CANONICALIZE_HOST_NAME==="true")}break;case"wtimeoutMS":_.wtimeout=parseInt(j,10);break;case"readPreference":if(!EX.isValid(j))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");_.readPreference=j;break;case"maxStalenessSeconds":_.maxStalenessSeconds=parseInt(j,10);break;case"readPreferenceTags":{j=decodeURIComponent(j);let te={};if(j==null||j===""){_.read_preference_tags.push(te);break}let K=j.split(/,/);for(let W=0;W9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");T.zlibCompressionLevel=te,R.compression=T}break;case"retryWrites":_.retryWrites=j==="true";break;case"minSize":_.minSize=parseInt(j,10);break;default:TX("URL Parser").warn(`${ue} is not supported as a connection string option`);break}}}),_.read_preference_tags.length===0&&(_.read_preference_tags=null),(_.w===-1||_.w===0)&&(_.journal===!0||_.fsync===!0||_.safe===!0))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");return _.readPreference||(_.readPreference="primary"),_=Object.assign(_,t),h.servers=O,h}o(AX,"parseConnectionString")});var _O=w((vue,YR)=>{"use strict";var IX=Eo(),Vt=mt().retrieveBSON(),kR=V().MongoError,Ch;try{Ch=require("mongodb-client-encryption")}catch{throw new kR("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project")}if(Ch===void 0||typeof Ch.extension!="function")throw new kR("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`");var BX=Ch.extension(TO()).AutoEncrypter,Cn=Symbol("internalClient"),Ah=class Ah{constructor(t,r){this.bypassAutoEncryption=!!r.autoEncryption.bypassAutoEncryption,this.needsConnecting=!1,r.maxPoolSize===0&&r.autoEncryption.keyVaultClient==null?r.autoEncryption.keyVaultClient=t:r.autoEncryption.keyVaultClient==null&&(r.autoEncryption.keyVaultClient=this.getInternalClient(t)),this.bypassAutoEncryption?r.autoEncryption.metadataClient=void 0:r.maxPoolSize===0?r.autoEncryption.metadataClient=t:r.autoEncryption.metadataClient=this.getInternalClient(t),r.autoEncryption.bson=Ah.makeBSON(r),this.autoEncrypter=new BX(t,r.autoEncryption)}getInternalClient(t){if(!this[Cn]){let r={};for(let i of Object.keys(t.s.options))["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(i)===-1&&(r[i]=t.s.options[i]);r.minPoolSize=0;let n=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[Cn]=new IX(t.s.url,r);for(let i of n)for(let s of t.listeners(i))this[Cn].on(i,s);t.on("newListener",(i,s)=>{this[Cn].on(i,s)}),this.needsConnecting=!0}return this[Cn]}connectInternalClient(t){return this.needsConnecting?(this.needsConnecting=!1,this[Cn].connect(t)):t()}close(t,r,n){this.autoEncrypter.teardown(i=>{if(this[Cn]&&t!==this[Cn])return this[Cn].close(r,n);n(i)})}static makeBSON(t){return(t||{}).bson||new Vt([Vt.Binary,Vt.Code,Vt.DBRef,Vt.Decimal128,Vt.Double,Vt.Int32,Vt.Long,Vt.Map,Vt.MaxKey,Vt.MinKey,Vt.ObjectId,Vt.BSONRegExp,Vt.Symbol,Vt.Timestamp])}};o(Ah,"Encrypter");var EO=Ah;YR.exports={Encrypter:EO}});var qO=w((_ue,nM)=>{"use strict";var RX=require("util").deprecate,MX=$().Logger,xX=$().MongoCredentials,IO=$().MongoError,KR=SO(),XR=mO(),qX=$().parseConnectionString,DX=Ui(),BO=$().ReadPreference,JR=OO(),bO=bu(),PX=$().Sessions.ServerSessionPool,LX=b().emitDeprecationWarning,CO=b().emitWarningOnce,jX=require("fs"),ZR=an(),UX=eu().CMAP_EVENT_NAMES,NO;function WX(){return NO||(NO=Eo()),NO}o(WX,"loadClient");var FX=RX(HR(),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),$X={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},QR=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],zX=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),AO=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","bsonRegExp","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","serverApi","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],VX=["native_parser"],GR=["server","replset","replSet","mongos","db"];function HX(e){let t=AO.concat(GR);for(let r in e)if(VX.indexOf(r)===-1){if(t.indexOf(r)===-1){if(e.validateOptions)return new IO(`option ${r} is not supported`);CO(`the options [${r}] is not supported`)}GR.indexOf(r)!==-1&&CO(`the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [${AO}]`)}}o(HX,"validOptions");var kX=AO.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function RO(e,t){t.on("authenticated",An(e,"authenticated")),t.on("error",An(e,"error")),t.on("timeout",An(e,"timeout")),t.on("close",An(e,"close")),t.on("parseError",An(e,"parseError")),t.once("open",An(e,"open")),t.once("fullsetup",An(e,"fullsetup")),t.once("all",An(e,"all")),t.on("reconnect",An(e,"reconnect"))}o(RO,"addListeners");function MO(e,t){e.topology=t,t instanceof XR||(t.s.sessionPool=new PX(t.s.coreTopology))}o(MO,"assignTopology");function YX(e){QR.forEach(t=>e.removeAllListeners(t))}o(YX,"clearAllEvents");function GX(e,t){let r=WX(),n=[];return e instanceof r&&QR.forEach(i=>{t.on(i,(s,a)=>{i==="open"?n.push({event:i,object1:e}):n.push({event:i,object1:s,object2:a})})}),n}o(GX,"collectEvents");function KX(e){e.tls!=null&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=jX.readFileSync(e[t]))})}o(KX,"resolveTLSOptions");function XX(e,t,r,n){if(r=Object.assign({},r),n==null)throw new Error("no callback function provided");let i=!1,s=MX("MongoClient",r);if(t instanceof bO||t instanceof JR||t instanceof KR)return JX(e,t,r,f);let a=r.useNewUrlParser!==!1,u=a?qX:FX,c=a?nJ:tJ;u(t,r,(h,l)=>{if(h)return n(h);let d=c(l),m=eM(d,r);if(m.socketTimeoutMS==null&&(m.socketTimeoutMS=0),m.connectTimeoutMS==null&&(m.connectTimeoutMS=1e4),m.retryWrites==null&&(m.retryWrites=!0),m.useRecoveryToken==null&&(m.useRecoveryToken=!0),m.readPreference==null&&(m.readPreference="primary"),m.db_options&&m.db_options.auth&&delete m.db_options.auth,KX(m),e.s.options=m,e.s.readPreference=BO.fromOptions(m),e.s.writeConcern=ZR.fromOptions(m),d.servers.length===0)return n(new Error("connection string must contain at least one seed host"));if(m.auth&&!m.credentials)try{i=!0,m.credentials=tM(e,m.auth.user,m.auth.password,m)}catch(S){return n(S)}return m.useUnifiedTopology?Ih(e,"unified",m,f):(CO("Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor."),m.replicaSet||m.rs_name?Ih(e,"replicaset",m,f):d.servers.length>1?Ih(e,"mongos",m,f):ZX(e,m,f))});function f(h,l){let d="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(h&&h.message==="no mongos proxies found in seed list")return s.isWarn()&&s.warn(d),n(new IO(d));i&&e.emit("authenticated",null,!0),n(h,l)}o(f,"connectCallback")}o(XX,"connect");function JX(e,t,r,n){MO(e,t),RO(e,t),xO(e,t);let i=Object.assign({},r);if((typeof r.readPreference=="string"||typeof r.read_preference=="string")&&(i.readPreference=new BO(r.readPreference||r.read_preference)),(i.user||i.password||i.authMechanism)&&!i.credentials)try{i.credentials=tM(e,i.user,i.password,i)}catch(a){return n(a,t)}return t.connect(i,n)}o(JX,"connectWithUrl");function An(e,t){let r=new Set(["all","fullsetup","open","reconnect"]);return(n,i)=>{if(r.has(t))return e.emit(t,e);e.emit(t,n,i)}}o(An,"createListener");function ZX(e,t,r){t.promiseLibrary=e.s.promiseLibrary;let i=rM(t)[0],s=GX(e,i);i.connect(t,(a,u)=>{if(a)return i.close(!0),r(a);YX(i),xO(e,i),RO(e,i);let c=u.lastIsMaster();if(MO(e,u),c&&c.msg==="isdbgrid")return u.close(),Ih(e,"mongos",t,r);rJ(e,s),r(a,u)})}o(ZX,"createServer");var QX=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function eJ(e){e.on("newListener",t=>{QX.has(t)&&LX(`The \`${t}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}o(eJ,"registerDeprecatedEventNotifiers");function Ih(e,t,r,n){r.promiseLibrary=e.s.promiseLibrary;let i={};t==="unified"&&(i.createServers=!1);let s=rM(r,i);if(r.autoEncryption!=null){let u=_O().Encrypter;r.encrypter=new u(e,r),r.autoEncrypter=r.encrypter.autoEncrypter}let a;if(t==="mongos"?a=new KR(s,r):t==="replicaset"?a=new JR(s,r):t==="unified"&&(a=new XR(r.servers,r),eJ(e)),RO(e,a),xO(e,a),MO(e,a),r.autoEncrypter){r.autoEncrypter.init(u=>{if(u){n(u);return}a.connect(r,c=>{if(c){a.close(!0),n(c);return}r.encrypter.connectInternalClient(f=>{if(f)return n(f);n(void 0,a)})})});return}a.connect(r,u=>{if(u)return a.close(!0),n(u);n(void 0,a)})}o(Ih,"createTopology");function eM(e,t){let r=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],n=["readconcern","compression","autoencryption"],i=["w","wtimeout","j","journal","fsync","writeconcern"];for(let a in t)i.indexOf(a.toLowerCase())===-1&&(n.indexOf(a.toLowerCase())!==-1?e[a]=t[a]:r.indexOf(a.toLowerCase())!==-1?e=Bh(e,t[a],!1):t[a]&&typeof t[a]=="object"&&!Buffer.isBuffer(t[a])&&!Array.isArray(t[a])?e=Bh(e,t[a],!0):e[a]=t[a]);let s=ZR.fromOptions(t);return s&&(e.writeConcern=Object.assign({},e.writeConcern,s)),e}o(eM,"createUnifiedOptions");function tM(e,t,r,n){n=Object.assign({},n);let i=n.authSource||n.authdb||n.dbName,s=n.authMechanism||"DEFAULT",a=s.toUpperCase(),u=n.authMechanismProperties;if(!zX.has(a))throw IO.create({message:`authentication mechanism ${s} not supported', options.authMechanism`,driver:!0});return new xX({mechanism:$X[a],mechanismProperties:u,source:i,username:t,password:r})}o(tM,"generateCredentials");function tJ(e){return Bh(eM({},e),e,!1)}o(tJ,"legacyTransformUrlOptions");function Bh(e,t,r){for(let n in t)t[n]&&typeof t[n]=="object"&&r?e=Bh(e,t[n],r):e[n]=t[n];return e}o(Bh,"mergeOptions");function xO(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(UX).forEach(n=>{t.on(n,(i,s)=>{e.emit(n,i,s)})})}o(xO,"relayEvents");function rJ(e,t){for(let r=0;rr.domain_socket?new bO(r.domain_socket,27017,e):new bO(r.host,r.port,e))}o(rM,"translateOptions");nM.exports={validOptions:HX,connect:XX}});var Eo=w((Nue,uM)=>{"use strict";var iJ=mh(),sJ=Eu(),sM=require("events").EventEmitter,oJ=require("util").inherits,Rh=$().MongoError,DO=$().ValidServerApiVersions,oM=require("util").deprecate,aJ=an(),uJ=b().MongoDBNamespace,iM=wt(),aM=b().maybePromise,cJ=mO(),fJ=qO().connect,lJ=qO().validOptions;function Tt(e,t){if(t=t||{},!(this instanceof Tt))return new Tt(e,t);if(sM.call(this),t.autoEncryption&&_O(),t.serverApi){let r=typeof t.serverApi=="string"?{version:t.serverApi}:t.serverApi,n=r&&r.version;if(!n)throw new Rh(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${DO.join('", "')}"]`);if(!DO.some(i=>i===n))throw new Rh(`Invalid server API version=${n}; must be in the following enum: ["${DO.join('", "')}"]`);t.serverApi=r}this.s={url:e,options:t,promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:aJ.fromOptions(t),readPreference:iM.fromOptions(t)||iM.primary,namespace:new uJ("admin")}}o(Tt,"MongoClient");oJ(Tt,sM);Object.defineProperty(Tt.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}});Object.defineProperty(Tt.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference}});Tt.prototype.connect=function(e){if(typeof e=="string")throw new TypeError("`connect` only accepts a callback");let t=this;return aM(this,e,r=>{let n=lJ(t.s.options);if(n)return r(n);fJ(t,t.s.url,t.s.options,i=>{if(i)return r(i);r(null,t)})})};Tt.prototype.logout=oM(function(e,t){typeof e=="function"&&(t=e,e={}),typeof t=="function"&&t(null,!0)},"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient");Tt.prototype.close=function(e,t){typeof e=="function"&&(t=e,e=!1);let r=this;return aM(this,t,n=>{let i=o(s=>{if(r.emit("close",r),!(r.topology instanceof cJ))for(let a of r.s.dbCache)a[1].emit("close",r);r.removeAllListeners("close"),n(s)},"completeClose");if(r.topology==null){i();return}r.topology.close(e,s=>{let a=r.topology.s.options.encrypter;if(a)return a.close(r,e,u=>{i(s||u)});i(s)})})};Tt.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);let r=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&r.returnNonCachedInstance!==!0)return this.s.dbCache.get(e);if(r.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new Rh("MongoClient must be connected before calling MongoClient.prototype.db");let n=new sJ(e,this.topology,r);return this.s.dbCache.set(e,n),n};Tt.prototype.isConnected=oM(function(e){return e=e||{},this.topology?this.topology.isConnected(e):!1},"isConnected is deprecated and will be removed in the next major version");Tt.connect=function(e,t,r){let n=Array.prototype.slice.call(arguments,1);return r=typeof n[n.length-1]=="function"?n.pop():void 0,t=n.length?n.shift():null,t=t||{},new Tt(e,t).connect(r)};Tt.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new Rh("Must connect to a server before calling this method");return this.topology.startSession(e,this.s.options)};Tt.prototype.withSession=function(e,t){typeof e=="function"&&(t=e,e=void 0);let r=this.startSession(e),n=o((i,s,a)=>{if(n=o(()=>{throw new ReferenceError("cleanupHandler was called too many times")},"cleanupHandler"),a=Object.assign({throw:!0},a),r.endSession(),i){if(a.throw)throw i;return Promise.reject(i)}},"cleanupHandler");try{let i=t(r);return Promise.resolve(i).then(s=>n(null,s)).catch(s=>n(s,null,{throw:!0}))}catch(i){return n(i,null,{throw:!1})}};Tt.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new iJ(this,e,t)};Tt.prototype.getLogger=function(){return this.s.options.logger};uM.exports=Tt});var PO=w((Cue,cM)=>{"use strict";var Mh=$().BSON.Binary,hJ=$().BSON.ObjectID,xh=qr().Buffer,Qt=o(function(e,t,r){if(!(this instanceof Qt))return new Qt(e,t);this.file=e;var n=t??{};if(this.writeConcern=r||{w:1},this.objectId=n._id==null?new hJ:n._id,this.chunkNumber=n.n==null?0:n.n,this.data=new Mh,typeof n.data=="string"){var i=xh.alloc(n.data.length);i.write(n.data,0,n.data.length,"binary"),this.data=new Mh(i)}else if(Array.isArray(n.data)){i=xh.alloc(n.data.length);var s=n.data.join("");i.write(s,0,s.length,"binary"),this.data=new Mh(i)}else if(n.data&&n.data._bsontype==="Binary")this.data=n.data;else if(!xh.isBuffer(n.data)&&n.data!=null)throw Error("Illegal chunk format");this.internalPosition=0},"Chunk");Qt.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),t!=null?t(null,this):this};Qt.prototype.read=function(e){if(e=e==null||e===0?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}else return""};Qt.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return this.data.buffer!=null?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=xh.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}else return null};Qt.prototype.eof=function(){return this.internalPosition===this.length()};Qt.prototype.getc=function(){return this.read(1)};Qt.prototype.rewind=function(){this.internalPosition=0,this.data=new Mh};Qt.prototype.save=function(e,t){var r=this;typeof e=="function"&&(t=e,e={}),r.file.chunkCollection(function(n,i){if(n)return t(n);var s={upsert:!0};for(var a in e)s[a]=e[a];for(a in r.writeConcern)s[a]=r.writeConcern[a];r.data.length()>0?r.buildMongoObject(function(u){var c={forceServerObjectId:!0};for(var f in r.writeConcern)c[f]=r.writeConcern[f];i.replaceOne({_id:r.objectId},u,s,function(h){t(h,r)})}):t(null,r)})};Qt.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};this.objectId!=null&&(t._id=this.objectId),e(t)};Qt.prototype.length=function(){return this.data.length()};Object.defineProperty(Qt.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}});Qt.DEFAULT_CHUNK_SIZE=1024*255;cM.exports=Qt});var mM=w((Iue,pM)=>{"use strict";var lr=PO(),jO=$().BSON.ObjectID,UO=$().ReadPreference,Ph=qr().Buffer,qh=require("fs"),WO=require("util").format,dJ=require("util"),In=$().MongoError,pJ=dJ.inherits,dM=require("stream").Duplex,mJ=b().shallowClone,Dt=b().executeLegacyOperation,yJ=require("util").deprecate,gJ=0,Cu=1,SJ=yJ(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead"),Oe=o(function e(t,r,n,i,s){if(SJ(),!(this instanceof e))return new e(t,r,n,i,s);this.db=t,typeof s>"u"&&(s={}),typeof i>"u"?(i=n,n=void 0):typeof i=="object"&&(s=i,i=n,n=void 0),r&&r._bsontype==="ObjectID"?(this.referenceBy=Cu,this.fileId=r,this.filename=n):typeof n>"u"?(this.referenceBy=gJ,this.filename=r,i.indexOf("w")!=null&&(this.fileId=new jO)):(this.referenceBy=Cu,this.fileId=r,this.filename=n),this.mode=i??"r",this.options=s||{},this.isOpen=!1,this.root=this.options.root==null?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||UO.primary,this.writeConcern=FO(t,this.options),this.internalChunkSize=this.options.chunkSize==null?lr.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var a=this.options.promiseLibrary||Promise;this.promiseLibrary=a,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(u){this.mode[0]==="w"&&this.position===0&&this.uploadDate==null?this.internalChunkSize=u:this.internalChunkSize=this.internalChunkSize}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})},"GridStore");Oe.prototype.open=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},this.mode!=="w"&&this.mode!=="w+"&&this.mode!=="r")throw In.create({message:"Illegal mode "+this.mode,driver:!0});return Dt(this.db.s.topology,wJ,[this,e,t],{skipSessions:!0})};var wJ=o(function(e,t,r){var n=FO(e.db,e.options);if(e.mode==="w"||e.mode==="w+"){var i=e.collection();i.ensureIndex([["filename",1]],n,function(){var s=e.chunkCollection(),a=mJ(n);a.unique=!0,s.ensureIndex([["files_id",1],["n",1]],a,function(){fM(e,n,function(u,c){if(u)return r(u);e.isOpen=!0,r(u,c)})})})}else fM(e,n,function(s,a){if(s)return r(s);e.isOpen=!0,r(s,a)})},"open");Oe.prototype.eof=function(){return this.position===this.length};Oe.prototype.getc=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},Dt(this.db.s.topology,OJ,[this,e,t],{skipSessions:!0})};var OJ=o(function(e,t,r){e.eof()?r(null,null):e.currentChunk.eof()?To(e,e.currentChunk.chunkNumber+1,function(n,i){e.currentChunk=i,e.position=e.position+1,r(n,e.currentChunk.getc())}):(e.position=e.position+1,r(null,e.currentChunk.getc()))},"getc");Oe.prototype.puts=function(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};var n=e.match(/\n$/)==null?e+` +`:e;return Dt(this.db.s.topology,this.write.bind(this),[n,t,r],{skipSessions:!0})};Oe.prototype.stream=function(){return new Bn(this)};Oe.prototype.write=o(function(t,r,n,i){return typeof n=="function"&&(i=n,n={}),n=n||{},Dt(this.db.s.topology,xJ,[this,t,r,n,i],{skipSessions:!0})},"write");Oe.prototype.destroy=o(function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},"destroy");Oe.prototype.writeFile=function(e,t,r){return typeof t=="function"&&(r=t,t={}),t=t||{},Dt(this.db.s.topology,vJ,[this,e,t,r],{skipSessions:!0})};var vJ=o(function(e,t,r,n){if(typeof t=="string"){qh.open(t,"r",function(i,s){if(i)return n(i);e.writeFile(s,n)});return}e.open(function(i,s){if(i)return n(i,s);qh.fstat(t,function(a,u){if(a)return n(a,s);var c=0,f=0,h=o(function(){var l=Ph.alloc(s.chunkSize);qh.read(t,l,0,l.length,c,function(d,m,S){if(d)return n(d,s);c=c+m;var E=new lr(s,{n:f++},s.writeConcern);E.write(S.slice(0,m),function(O,T){if(O)return n(O,s);T.save({},function(R){if(R)return n(R,s);if(s.position=s.position+m,s.currentChunk=T,c>=u.size)qh.close(t,function(_){if(_)return n(_);s.close(function(N){return n(N||null,s)})});else return process.nextTick(h)})})})},"writeChunk");process.nextTick(h)})})},"writeFile");Oe.prototype.close=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},Dt(this.db.s.topology,EJ,[this,e,t],{skipSessions:!0})};var EJ=o(function(e,t,r){e.mode[0]==="w"?(t=Object.assign({},e.writeConcern,t),e.currentChunk!=null&&e.currentChunk.position>0?e.currentChunk.save({},function(n){if(n&&typeof r=="function")return r(n);e.collection(function(i,s){if(i&&typeof r=="function")return r(i);e.uploadDate!=null?LO(e,function(a,u){if(a){if(typeof r=="function")return r(a);throw a}s.save(u,t,function(c){typeof r=="function"&&r(c,u)})}):(e.uploadDate=new Date,LO(e,function(a,u){if(a){if(typeof r=="function")return r(a);throw a}s.save(u,t,function(c){typeof r=="function"&&r(c,u)})}))})}):e.collection(function(n,i){if(n&&typeof r=="function")return r(n);e.uploadDate=new Date,LO(e,function(s,a){if(s){if(typeof r=="function")return r(s);throw s}i.save(a,t,function(u){typeof r=="function"&&r(u,a)})})})):e.mode[0]==="r"?typeof r=="function"&&r(null,null):typeof r=="function"&&r(In.create({message:WO("Illegal mode %s",e.mode),driver:!0}))},"close");Oe.prototype.chunkCollection=function(e){return typeof e=="function"?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")};Oe.prototype.unlink=function(e,t){return typeof e=="function"&&(t=e,e={}),e=e||{},Dt(this.db.s.topology,_J,[this,e,t],{skipSessions:!0})};var _J=o(function(e,t,r){Au(e,function(n){if(n!==null)return n.message="at deleteChunks: "+n.message,r(n);e.collection(function(i,s){if(i!==null)return i.message="at collection: "+i.message,r(i);s.remove({_id:e.fileId},e.writeConcern,function(a){r(a,e)})})})},"unlink");Oe.prototype.collection=function(e){return typeof e=="function"&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")};Oe.prototype.readlines=function(e,t,r){var n=Array.prototype.slice.call(arguments,0);return r=typeof n[n.length-1]=="function"?n.pop():void 0,e=n.length?n.shift():` +`,e=e||` +`,t=n.length?n.shift():{},Dt(this.db.s.topology,TJ,[this,e,t,r],{skipSessions:!0})};var TJ=o(function(e,t,r,n){e.read(function(i,s){if(i)return n(i);var a=s.toString().split(t);a=a.length>0?a.splice(0,a.length-1):[];for(var u=0;u=s){var u=e.currentChunk.readSlice(s-a._index);return u.copy(a,a._index),e.position=e.position+a.length,s===0&&a.length===0?i(In.create({message:"File does not exist",driver:!0}),null):i(null,a)}u=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position),u.copy(a,a._index),a._index+=u.length,To(e,e.currentChunk.chunkNumber+1,function(c,f){if(c)return i(c);f.length()>0?(e.currentChunk=f,e.read(t,a,i)):a._index>0?i(null,a):i(In.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)})},"read");Oe.prototype.tell=function(e){var t=this;return typeof e=="function"?e(null,this.position):new t.promiseLibrary(function(r){r(t.position)})};Oe.prototype.seek=function(e,t,r,n){var i=Array.prototype.slice.call(arguments,1);return n=typeof i[i.length-1]=="function"?i.pop():void 0,t=i.length?i.shift():null,r=i.length?i.shift():{},Dt(this.db.s.topology,CJ,[this,e,t,r,n],{skipSessions:!0})};var CJ=o(function(e,t,r,n,i){if(e.mode!=="r")return i(In.create({message:"seek is only supported for mode r",driver:!0}));var s=r??Oe.IO_SEEK_SET,a=t,u=0;s===Oe.IO_SEEK_CUR?u=e.position+a:s===Oe.IO_SEEK_END?u=e.length+a:u=a;var c=Math.floor(u/e.chunkSize),f=o(function(){To(e,c,function(h,l){if(h)return i(h,null);if(l==null)return i(new Error("no chunk found"));e.currentChunk=l,e.position=u,e.currentChunk.position=e.position%e.chunkSize,i(h,e)})},"seekChunk");f()},"seek"),fM=o(function(e,t,r){var n=e.collection(),i=e.referenceBy===Cu?{_id:e.fileId}:{filename:e.filename};i=e.fileId==null&&e.filename==null?null:i,t.readPreference=e.readPreference,i!=null?n.findOne(i,t,function(a,u){if(a)return s(a);if(u!=null)e.fileId=u._id,e.filename=e.mode==="r"||e.filename===void 0?u.filename:e.filename,e.contentType=u.contentType,e.internalChunkSize=u.chunkSize,e.uploadDate=u.uploadDate,e.aliases=u.aliases,e.length=u.length,e.metadata=u.metadata,e.internalMd5=u.md5;else if(e.mode!=="r")e.fileId=e.fileId==null?new jO:e.fileId,e.contentType=Oe.DEFAULT_CONTENT_TYPE,e.internalChunkSize=e.internalChunkSize==null?lr.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0;else{e.length=0;var c=e.fileId._bsontype==="ObjectID"?e.fileId.toHexString():e.fileId;return s(In.create({message:WO("file with id %s not opened for writing",e.referenceBy===Cu?c:e.filename),driver:!0}),e)}e.mode==="r"?To(e,0,t,function(f,h){if(f)return s(f);e.currentChunk=h,e.position=0,r(null,e)}):e.mode==="w"&&u?Au(e,t,function(f){if(f)return s(f);e.currentChunk=new lr(e,{n:0},e.writeConcern),e.contentType=e.options.content_type==null?e.contentType:e.options.content_type,e.internalChunkSize=e.options.chunk_size==null?e.internalChunkSize:e.options.chunk_size,e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=0,r(null,e)}):e.mode==="w"?(e.currentChunk=new lr(e,{n:0},e.writeConcern),e.contentType=e.options.content_type==null?e.contentType:e.options.content_type,e.internalChunkSize=e.options.chunk_size==null?e.internalChunkSize:e.options.chunk_size,e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=0,r(null,e)):e.mode==="w+"&&To(e,hM(e),t,function(f,h){if(f)return s(f);e.currentChunk=h??new lr(e,{n:0},e.writeConcern),e.currentChunk.position=e.currentChunk.data.length(),e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=e.length,r(null,e)})}):(e.fileId=e.fileId==null?new jO:e.fileId,e.contentType=Oe.DEFAULT_CONTENT_TYPE,e.internalChunkSize=e.internalChunkSize==null?lr.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,e.mode==="w"?Au(e,t,function(a){if(a)return s(a);e.currentChunk=new lr(e,{n:0},e.writeConcern),e.contentType=e.options.content_type==null?e.contentType:e.options.content_type,e.internalChunkSize=e.options.chunk_size==null?e.internalChunkSize:e.options.chunk_size,e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=0,r(null,e)}):e.mode==="w+"&&To(e,hM(e),t,function(a,u){if(a)return s(a);e.currentChunk=u??new lr(e,{n:0},e.writeConcern),e.currentChunk.position=e.currentChunk.data.length(),e.metadata=e.options.metadata==null?e.metadata:e.options.metadata,e.aliases=e.options.aliases==null?e.aliases:e.options.aliases,e.position=e.length,r(null,e)}));function s(a){s.err||r(s.err=a)}o(s,"error")},"_open"),lM=o(function(e,t,r,n){typeof r=="function"&&(n=r,r=null);var i=typeof r=="boolean"?r:!1;if(e.mode!=="w")n(In.create({message:WO("file with id %s not opened for writing",e.referenceBy===Cu?e.referenceBy:e.filename),driver:!0}),null);else if(e.currentChunk.position+t.length>=e.chunkSize){for(var s=e.currentChunk.chunkNumber,a=e.chunkSize-e.currentChunk.position,u=t.slice(0,a),c=t.slice(a),f=[e.currentChunk.write(u)];c.length>=e.chunkSize;){var h=new lr(e,{n:s+1},e.writeConcern);u=c.slice(0,e.chunkSize),c=c.slice(e.chunkSize),s=s+1,h.write(u),f.push(h)}e.currentChunk=new lr(e,{n:s+1},e.writeConcern),c.length>0&&e.currentChunk.write(c),e.position=e.position+t.length;for(var l=f.length,d=0;d=u.length)return s("offset larger than size of file",null);if(r&&r>u.length)return s("length is larger than the size of the file",null);if(n&&r&&n+r>u.length)return s("offset and length is larger than the size of the file",null);n!=null?u.seek(n,function(c,f){if(c)return s(c);f.read(r,s)}):u.read(r,s)})},"readStatic");Oe.readlines=function(e,t,r,n,i){var s=Array.prototype.slice.call(arguments,2);return i=typeof s[s.length-1]=="function"?s.pop():void 0,r=s.length?s.shift():null,n=s.length?s.shift():null,n=n||{},Dt(e.s.topology,RJ,[e,t,r,n,i],{skipSessions:!0})};var RJ=o(function(e,t,r,n,i){var s=r??` +`;new Oe(e,t,"r",n).open(function(a,u){if(a)return i(a);u.readlines(s,i)})},"readlinesStatic");Oe.unlink=function(e,t,r,n){var i=Array.prototype.slice.call(arguments,2);return n=typeof i[i.length-1]=="function"?i.pop():void 0,r=i.length?i.shift():{},r=r||{},Dt(e.s.topology,MJ,[this,e,t,r,n],{skipSessions:!0})};var MJ=o(function(e,t,r,n,i){var s=FO(t,n);if(r.constructor===Array)for(var a=0,u=0;ue.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-i._index,e.push(i.slice(0,i._index))),e.totalBytesToRead<=0&&(e.endCalled=!0)})},"read"),r=e.gs.length{"use strict";var yM=require("stream"),qJ=require("util");SM.exports=No;function No(e,t,r,n,i){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:n,init:!1,expectedEnd:0,file:null,options:i,readPreference:r},yM.Readable.call(this)}o(No,"GridFSBucketReadStream");qJ.inherits(No,yM.Readable);No.prototype._read=function(){var e=this;this.destroyed||LJ(e,function(){DJ(e)})};No.prototype.start=function(e){return gM(this),this.s.options.start=e,this};No.prototype.end=function(e){return gM(this),this.s.options.end=e,this};No.prototype.abort=function(e){var t=this;this.push(null),this.destroyed=!0,this.s.cursor?this.s.cursor.close(function(r){t.emit("close"),e&&e(r)}):(this.s.init||t.emit("close"),e&&e())};function gM(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}o(gM,"throwIfInitialized");function DJ(e){e.destroyed||e.s.cursor.next(function(t,r){if(e.destroyed)return;if(t)return Qr(e,t);if(!r){e.push(null),process.nextTick(()=>{e.s.cursor.close(function(d){if(d){Qr(e,d);return}e.emit("close")})});return}var n=e.s.file.length-e.s.bytesRead,i=e.s.expected++,s=Math.min(e.s.file.chunkSize,n);if(r.n>i){var a="ChunkIsMissing: Got unexpected n: "+r.n+", expected: "+i;return Qr(e,new Error(a))}if(r.n0&&(u.n={$gte:c})}e.s.cursor=e.s.chunks.find(u).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=UJ(e,n,e.s.cursor,e.s.options)}catch(f){return Qr(e,f)}e.emit("file",n)})}o(PJ,"init");function LJ(e,t){if(e.s.file)return t();e.s.init||(PJ(e),e.s.init=!0),e.once("file",function(){t()})}o(LJ,"waitForFile");function jJ(e,t,r){if(r&&r.start!=null){if(r.start>t.length)throw new Error("Stream start ("+r.start+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream start ("+r.start+") must not be negative");if(r.end!=null&&r.endt.length)throw new Error("Stream end ("+n.end+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream end ("+n.end+") must not be negative");var i=n.start!=null?Math.floor(n.start/t.chunkSize):0;return r.limit(Math.ceil(n.end/t.chunkSize)-i),e.s.expectedEnd=Math.ceil(n.end/t.chunkSize),Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}}o(UJ,"handleEndOption");function Qr(e,t){e.emit("error",t)}o(Qr,"__handleError")});var CM=w((xue,bM)=>{"use strict";var vM=Ii().MONGODB_ERROR_CODES,EM=$(),WJ=require("crypto"),_M=require("stream"),FJ=require("util"),Iu=qr().Buffer,$J=b().deprecateOptions,Ru=$J({name:"GridFSBucketWriteStream",deprecatedOptions:["disableMD5"],optionsIndex:2},function(e,t,r){if(r=r||{},_M.Writable.call(this,r),this.bucket=e,this.chunks=e.s._chunksCollection,this.filename=t,this.files=e.s._filesCollection,this.options=r,this.done=!1,this.id=r.id?r.id:EM.BSON.ObjectId(),this.chunkSizeBytes=this.options.chunkSizeBytes,this.bufToStore=Iu.alloc(this.chunkSizeBytes),this.length=0,this.md5=!r.disableMD5&&WJ.createHash("md5"),this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1,promiseLibrary:this.bucket.s.promiseLibrary},!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=!0;var n=this;zJ(this,function(){n.bucket.s.checkedIndexes=!0,n.bucket.emit("index")})}});FJ.inherits(Ru,_M.Writable);Ru.prototype.write=function(e,t,r){var n=this;return NM(this,function(){return HJ(n,e,t,r)})};Ru.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return typeof e=="function"?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),typeof e=="function"?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},function(r){typeof e=="function"&&e(r)})};Ru.prototype.end=function(e,t,r){var n=this;if(typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),!Bu(this,r)){if(this.state.streamEnd=!0,r&&this.once("finish",function(i){r(null,i)}),!e){NM(this,function(){OM(n)});return}this.write(e,t,function(){OM(n)})}};function VO(e,t,r){if(!e.state.errored){if(e.state.errored=!0,r)return r(t);e.emit("error",t)}}o(VO,"__handleError");function TM(e,t,r){return{_id:EM.BSON.ObjectId(),files_id:e,n:t,data:r}}o(TM,"createChunkDoc");function $O(e,t){e.chunks.listIndexes().toArray(function(r,n){if(r){if(r.code===vM.NamespaceNotFound){var i={files_id:1,n:1};e.chunks.createIndex(i,{background:!1,unique:!0},function(u){if(u)return t(u);t()});return}return t(r)}var s=!1;if(n.forEach(function(u){if(u.key){var c=Object.keys(u.key);c.length===2&&u.key.files_id===1&&u.key.n===1&&(s=!0)}}),s)t();else{i={files_id:1,n:1};var a=Mu(e);a.background=!1,a.unique=!0,e.chunks.createIndex(i,a,function(u){if(u)return t(u);t()})}})}o($O,"checkChunksIndex");function zO(e,t){if(e.done)return!0;if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=!0;var r=VJ(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);return Bu(e,t)?!1:(e.files.insertOne(r,Mu(e),function(n){if(n)return VO(e,n,t);e.emit("finish",r),e.emit("close")}),!0)}return!1}o(zO,"checkDone");function zJ(e,t){e.files.findOne({},{_id:1},function(r,n){if(r)return t(r);if(n)return t();e.files.listIndexes().toArray(function(i,s){if(i){if(i.code===vM.NamespaceNotFound){var a={filename:1,uploadDate:1};e.files.createIndex(a,{background:!1},function(f){if(f)return t(f);$O(e,t)});return}return t(i)}var u=!1;if(s.forEach(function(f){var h=Object.keys(f.key);h.length===2&&f.key.filename===1&&f.key.uploadDate===1&&(u=!0)}),u)$O(e,t);else{a={filename:1,uploadDate:1};var c=Mu(e);c.background=!1,e.files.createIndex(a,c,function(f){if(f)return t(f);$O(e,t)})}})})}o(zJ,"checkIndexes");function VJ(e,t,r,n,i,s,a,u){var c={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:i};return n&&(c.md5=n),s&&(c.contentType=s),a&&(c.aliases=a),u&&(c.metadata=u),c}o(VJ,"createFilesDoc");function HJ(e,t,r,n){if(Bu(e,n))return!1;var i=Iu.isBuffer(t)?t:Iu.from(t,r);if(e.length+=i.length,e.pos+i.length0;){var f=i.length-s;if(i.copy(e.bufToStore,e.pos,f,f+u),e.pos+=u,a-=u,a===0){e.md5&&e.md5.update(e.bufToStore);var h=TM(e.id,e.n,Iu.from(e.bufToStore));if(++e.state.outstandingRequests,++c,Bu(e,n))return!1;e.chunks.insertOne(h,Mu(e),function(l){if(l)return VO(e,l);--e.state.outstandingRequests,--c,c||(e.emit("drain",h),n&&n(),zO(e))}),a=e.chunkSizeBytes,e.pos=0,++e.n}s-=u,u=Math.min(a,s)}return!1}o(HJ,"doWrite");function Mu(e){var t={};return e.options.writeConcern&&(t.w=e.options.writeConcern.w,t.wtimeout=e.options.writeConcern.wtimeout,t.j=e.options.writeConcern.j),t}o(Mu,"getWriteOptions");function NM(e,t){return e.bucket.s.checkedIndexes?t(!1):(e.bucket.once("index",function(){t(!0)}),!0)}o(NM,"waitForIndexes");function OM(e,t){if(e.pos===0)return zO(e,t);++e.state.outstandingRequests;var r=Iu.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos),e.md5&&e.md5.update(r);var n=TM(e.id,e.n,r);if(Bu(e,t))return!1;e.chunks.insertOne(n,Mu(e),function(i){if(i)return VO(e,i);--e.state.outstandingRequests,zO(e)})}o(OM,"writeRemnant");function Bu(e,t){return e.state.aborted?(typeof t=="function"&&t(new Error("this stream has been aborted")),!0):!1}o(Bu,"checkAborted");bM.exports=Ru});var xM=w((Due,MM)=>{"use strict";var AM=require("events").EventEmitter,IM=wM(),BM=CM(),kO=b().shallowClone,kJ=b().toError,YJ=require("util"),YO=b().executeLegacyOperation,RM=b().deprecateOptions,HO={bucketName:"fs",chunkSizeBytes:255*1024};MM.exports=jr;function jr(e,t){if(AM.apply(this),this.setMaxListeners(0),t&&typeof t=="object"){t=kO(t);for(var r=Object.keys(HO),n=0;n=0?(r={uploadDate:1},n=t.revision):n=-t.revision-1);var i={filename:e};return t={sort:r,skip:n,start:t&&t.start,end:t&&t.end},new IM(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,i,t)};jr.prototype.rename=function(e,t,r){return YO(this.s.db.s.topology,KJ,[this,e,t,r],{skipSessions:!0})};function KJ(e,t,r,n){var i={_id:t},s={$set:{filename:r}};e.s._filesCollection.updateOne(i,s,function(a,u){if(a)return n(a);if(!u.result.n)return n(kJ("File with id "+t+" not found"));n()})}o(KJ,"_rename");jr.prototype.drop=function(e){return YO(this.s.db.s.topology,XJ,[this,e],{skipSessions:!0})};jr.prototype.getLogger=function(){return this.s.db.s.logger};function XJ(e,t){e.s._filesCollection.drop(function(r){if(r)return t(r);e.s._chunksCollection.drop(function(n){return n?t(n):t()})})}o(XJ,"_drop")});var TO=w((Lue,qM)=>{"use strict";var Ve=$(),JJ=wI(),oe=Eo().connect;oe.MongoError=Ve.MongoError;oe.MongoNetworkError=Ve.MongoNetworkError;oe.MongoTimeoutError=Ve.MongoTimeoutError;oe.MongoServerSelectionError=Ve.MongoServerSelectionError;oe.MongoParseError=Ve.MongoParseError;oe.MongoWriteConcernError=Ve.MongoWriteConcernError;oe.MongoBulkWriteError=jl().BulkWriteError;oe.BulkWriteError=oe.MongoBulkWriteError;oe.ServerApiVersion=Ve.ServerApiVersion;oe.Admin=Vw();oe.MongoClient=Eo();oe.Db=Eu();oe.Collection=yo();oe.Server=bu();oe.ReplSet=OO();oe.Mongos=SO();oe.ReadPreference=Ve.ReadPreference;oe.GridStore=mM();oe.Chunk=PO();oe.Logger=Ve.Logger;oe.AggregationCursor=Wl();oe.CommandCursor=$l();oe.Cursor=Xr();oe.GridFSBucket=xM();oe.CoreServer=Ve.Server;oe.CoreConnection=Ve.Connection;oe.Binary=Ve.BSON.Binary;oe.Code=Ve.BSON.Code;oe.Map=Ve.BSON.Map;oe.DBRef=Ve.BSON.DBRef;oe.Double=Ve.BSON.Double;oe.Int32=Ve.BSON.Int32;oe.Long=Ve.BSON.Long;oe.MinKey=Ve.BSON.MinKey;oe.MaxKey=Ve.BSON.MaxKey;oe.ObjectID=Ve.BSON.ObjectID;oe.ObjectId=Ve.BSON.ObjectID;oe.Symbol=Ve.BSON.Symbol;oe.Timestamp=Ve.BSON.Timestamp;oe.BSONRegExp=Ve.BSON.BSONRegExp;oe.Decimal128=Ve.BSON.Decimal128;oe.connect=oe;oe.instrument=function(e,t){typeof e=="function"&&(t=e,e={});let r=new JJ;return r.instrument(oe.MongoClient,t),r};qM.exports=oe});var xu=w((DM,PM)=>{var ZJ=require("stream");DM=PM.exports=GO;GO.through=GO;function GO(e,t,r){e=e||function(h){this.queue(h)},t=t||function(){this.queue(null)};var n=!1,i=!1,s=[],a=!1,u=new ZJ;u.readable=u.writable=!0,u.paused=!1,u.autoDestroy=!(r&&r.autoDestroy===!1),u.write=function(h){return e.call(this,h),!u.paused};function c(){for(;s.length&&!u.paused;){var h=s.shift();if(h===null)return u.emit("end");u.emit("data",h)}}o(c,"drain"),u.queue=u.push=function(h){return a||(h===null&&(a=!0),s.push(h),c()),u},u.on("end",function(){u.readable=!1,!u.writable&&u.autoDestroy&&process.nextTick(function(){u.destroy()})});function f(){u.writable=!1,t.call(u),!u.readable&&u.autoDestroy&&u.destroy()}return o(f,"_end"),u.end=function(h){if(!n)return n=!0,arguments.length&&u.write(h),f(),u},u.destroy=function(){if(!i)return i=!0,n=!0,s.length=0,u.writable=u.readable=!1,u.emit("close"),u},u.pause=function(){if(!u.paused)return u.paused=!0,u},u.resume=function(){return u.paused&&(u.paused=!1,u.emit("resume")),c(),u.paused||u.emit("drain"),u},u}o(GO,"through")});var jM=w((Uue,LM)=>{"use strict";var QJ=require("stream");LM.exports=o(function e(t){if(Array.isArray(t)){var r=0,n=t.length;return e(function(u){return r{var e9=require("stream"),t9=["write","end","destroy"],r9=["resume","pause"],n9=["data","close"],UM=Array.prototype.slice;WM.exports=i9;function KO(e,t){if(e.forEach)return e.forEach(t);for(var r=0;r{var s9=require("stream").Stream;FM.exports=function(e,t){var r=new s9,n=0,i=0,s=!1,a=!1,u=!1,c=0,f=!1;t=t||{};var h=t.failures?"failure":"error",l={};r.writable=!0,r.readable=!0;function d(O,T){var R=c+1;if(T===R?(O!==void 0&&r.emit.apply(r,["data",O]),c++,R++):l[T]=O,l.hasOwnProperty(R)){var _=l[R];return delete l[R],d(_,R)}i++,n===i&&(a&&(a=!1,r.emit("drain")),s&&E())}o(d,"queueData");function m(O,T,R){u||(f=!0,(!O||t.failures)&&d(T,R),O&&r.emit.apply(r,[h,O]),f=!1)}o(m,"next");function S(O,T,R){return e.call(null,O,function(_,N){R(_,N,T)})}o(S,"wrappedMapper"),r.write=function(O){if(s)throw new Error("map stream is not writable");f=!1,n++;try{var T=S(O,n,m);return a=T===!1,!a}catch(R){if(f)throw R;return m(R),!a}};function E(O){if(s=!0,r.writable=!1,O!==void 0)return d(O,n);n==i&&(r.readable=!1,r.emit("end"),r.destroy())}return o(E,"end"),r.end=function(O){s||E(O)},r.destroy=function(){s=u=!0,r.writable=r.readable=a=!1,process.nextTick(function(){r.emit("close")})},r.pause=function(){a=!0},r.resume=function(){a=!1},r}});var VM=w((Hue,zM)=>{zM.exports=xu()});var kM=w((kue,HM)=>{var o9=xu(),a9=require("string_decoder").StringDecoder;HM.exports=u9;function u9(e,t,r){var n=new a9,i="",s=r&&r.maxLength,a=!(r&&r.trailing===!1);typeof e=="function"&&(t=e,e=null),e||(e=/\r?\n/);function u(f,h){if(t){try{h=t(h)}catch(l){return f.emit("error",l)}typeof h<"u"&&f.queue(h)}else f.queue(h)}o(u,"emit");function c(f,h){var l=((i??"")+h).split(e);if(i=l.pop(),s&&i.length>s)return f.emit("error",new Error("maximum buffer reached"));for(var d=0;d{var c9=XO(),f9=xu();YM.exports=function(){var e;if(arguments.length==1&&Array.isArray(arguments[0])?e=arguments[0]:e=[].slice.call(arguments),e.length==0)return f9();if(e.length==1)return e[0];var t=e[0],r=e[e.length-1],n=c9(t,r);function i(u){u.length<2||(u[0].pipe(u[1]),i(u.slice(1)))}o(i,"recurse"),i(e);function s(){var u=[].slice.call(arguments);u.unshift("error"),n.emit.apply(n,u)}o(s,"onerror");for(var a=1;a{var qu=require("stream").Stream,me=KM,l9=xu(),h9=jM(),d9=XO(),p9=$M(),m9=VM(),y9=kM(),g9=GM(),S9=global.setImmediate||process.nextTick;me.Stream=qu;me.through=l9;me.from=h9;me.duplex=d9;me.map=p9;me.pause=m9;me.split=y9;me.pipeline=me.connect=me.pipe=g9;me.concat=me.merge=function(){var e=[].slice.call(arguments);e.length===1&&e[0]instanceof Array&&(e=e[0]);var t=new qu;t.setMaxListeners(0);var r=0;return t.writable=t.readable=!0,e.length?e.forEach(function(n){n.pipe(t,{end:!1});var i=!1;n.on("end",function(){i||(i=!0,r++,r==e.length&&t.emit("end"))})}):process.nextTick(function(){t.emit("end")}),t.write=function(n){this.emit("data",n)},t.destroy=function(){e.forEach(function(n){n.destroy&&n.destroy()})},t};me.collect=me.writeArray=function(e){if(typeof e!="function")throw new Error("function writeArray (done): done must be function");var t=new qu,r=[],n=!1;return t.write=function(i){r.push(i)},t.end=function(){n=!0,e(null,r)},t.writable=!0,t.readable=!1,t.destroy=function(){t.writable=t.readable=!1,!n&&e(new Error("destroyed before end"),r)},t};me.readArray=function(e){var t=new qu,r=0,n=!1,i=!1;if(t.readable=!0,t.writable=!1,!Array.isArray(e))throw new Error("event-stream.read expects an array");return t.resume=function(){if(!i){n=!1;for(var s=e.length;r1&&r.emit("data",f),S9(function(){if(!(s||i||a))try{a=!0,e.call(r,n++,function(){a=!1,u.apply(null,arguments)})}catch(h){r.emit("error",h)}})}return o(u,"get"),r.resume=function(){i=!1,u()},process.nextTick(u),r.pause=function(){i=!0},r.destroy=function(){r.emit("end"),r.emit("close"),s=!0},r};me.mapSync=function(e){return me.through(o(function(r){var n;try{n=e(r)}catch(i){return this.emit("error",i)}n!==void 0&&this.emit("data",n)},"write"))};me.filterSync=function(e){return me.through(function(t){var r=this;e(t)&&r.queue(t)})};me.flatmapSync=function(e){return me.through(function(t){var r=this;t.forEach(function(n){r.queue(e(n))})})};me.log=function(e){return me.through(function(t){var r=[].slice.call(arguments);e?console.error(e,t):console.error(t),this.emit("data",t)})};me.child=function(e){return me.duplex(e.stdin,e.stdout)};me.parse=function(e){var t=!!(e&&e.error);return me.through(function(r){var n;try{r&&(n=JSON.parse(r.toString()))}catch(i){return t?this.emit("error",i):console.error(i,"attempting to parse:",r)}n!==void 0&&this.emit("data",n)})};me.stringify=function(){var e=require("buffer").Buffer;return me.mapSync(function(t){return JSON.stringify(e.isBuffer(t)?t.toString():t)+` +`})};me.replace=function(e,t){return me.pipeline(me.split(e),me.join(t))};me.join=function(e){if(typeof e=="function")return me.wait(e);var t=!0;return me.through(function(r){return t||this.emit("data",e),t=!1,this.emit("data",r),!0})};me.wait=function(e){var t=[];return me.through(function(r){t.push(r)},function(){var r=Buffer.isBuffer(t[0])?Buffer.concat(t):t.join("");this.emit("data",r),this.emit("end"),e&&e(null,r)})};me.pipeable=function(){throw new Error("[EVENT-STREAM] es.pipeable is deprecated")}});var hx=w((ce,lx)=>{ce=lx.exports=Te;var Le;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?Le=o(function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)},"debug"):Le=o(function(){},"debug");ce.SEMVER_SPEC_VERSION="2.0.0";var Du=256,Lh=Number.MAX_SAFE_INTEGER||9007199254740991,ZO=16,w9=Du-6,Pu=ce.re=[],He=ce.safeRe=[],U=ce.src=[],Ee=0,nv="[a-zA-Z0-9-]",QO=[["\\s",1],["\\d",Du],[nv,w9]];function zh(e){for(var t=0;t)?=?)";var jh=Ee++;U[jh]=U[Co]+"|x|X|\\*";var Uh=Ee++;U[Uh]=U[bo]+"|x|X|\\*";var us=Ee++;U[us]="[v=\\s]*("+U[Uh]+")(?:\\.("+U[Uh]+")(?:\\.("+U[Uh]+")(?:"+U[sv]+")?"+U[ju]+"?)?)?";var Io=Ee++;U[Io]="[v=\\s]*("+U[jh]+")(?:\\.("+U[jh]+")(?:\\.("+U[jh]+")(?:"+U[ov]+")?"+U[ju]+"?)?)?";var ex=Ee++;U[ex]="^"+U[Mo]+"\\s*"+U[us]+"$";var tx=Ee++;U[tx]="^"+U[Mo]+"\\s*"+U[Io]+"$";var rx=Ee++;U[rx]="(?:^|[^\\d])(\\d{1,"+ZO+"})(?:\\.(\\d{1,"+ZO+"}))?(?:\\.(\\d{1,"+ZO+"}))?(?:$|[^\\d])";var Vh=Ee++;U[Vh]="(?:~>?)";var Bo=Ee++;U[Bo]="(\\s*)"+U[Vh]+"\\s+";Pu[Bo]=new RegExp(U[Bo],"g");He[Bo]=new RegExp(zh(U[Bo]),"g");var O9="$1~",nx=Ee++;U[nx]="^"+U[Vh]+U[us]+"$";var ix=Ee++;U[ix]="^"+U[Vh]+U[Io]+"$";var Hh=Ee++;U[Hh]="(?:\\^)";var Ro=Ee++;U[Ro]="(\\s*)"+U[Hh]+"\\s+";Pu[Ro]=new RegExp(U[Ro],"g");He[Ro]=new RegExp(zh(U[Ro]),"g");var v9="$1^",sx=Ee++;U[sx]="^"+U[Hh]+U[us]+"$";var ox=Ee++;U[ox]="^"+U[Hh]+U[Io]+"$";var fv=Ee++;U[fv]="^"+U[Mo]+"\\s*("+uv+")$|^$";var lv=Ee++;U[lv]="^"+U[Mo]+"\\s*("+QM+")$|^$";var cs=Ee++;U[cs]="(\\s*)"+U[Mo]+"\\s*("+uv+"|"+U[us]+")";Pu[cs]=new RegExp(U[cs],"g");He[cs]=new RegExp(zh(U[cs]),"g");var E9="$1$2$3",ax=Ee++;U[ax]="^\\s*("+U[us]+")\\s+-\\s+("+U[us]+")\\s*$";var ux=Ee++;U[ux]="^\\s*("+U[Io]+")\\s+-\\s+("+U[Io]+")\\s*$";var cx=Ee++;U[cx]="(<|>)?=?\\s*\\*";for(en=0;enDu)return null;var r=t.loose?He[cv]:He[av];if(!r.test(e))return null;try{return new Te(e,t)}catch{return null}}o(fs,"parse");ce.valid=_9;function _9(e,t){var r=fs(e,t);return r?r.version:null}o(_9,"valid");ce.clean=T9;function T9(e,t){var r=fs(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}o(T9,"clean");ce.SemVer=Te;function Te(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof Te){if(e.loose===t.loose)return e;e=e.version}else if(typeof e!="string")throw new TypeError("Invalid Version: "+e);if(e.length>Du)throw new TypeError("version is longer than "+Du+" characters");if(!(this instanceof Te))return new Te(e,t);Le("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?He[cv]:He[av]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Lh||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Lh||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Lh||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(function(n){if(/^[0-9]+$/.test(n)){var i=+n;if(i>=0&&i=0;)typeof this.prerelease[r]=="number"&&(this.prerelease[r]++,r=-2);r===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this};ce.inc=N9;function N9(e,t,r,n){typeof r=="string"&&(n=r,r=void 0);try{return new Te(e,r).inc(t,n).version}catch{return null}}o(N9,"inc");ce.diff=b9;function b9(e,t){if(hv(e,t))return null;var r=fs(e),n=fs(t),i="";if(r.prerelease.length||n.prerelease.length){i="pre";var s="prerelease"}for(var a in r)if((a==="major"||a==="minor"||a==="patch")&&r[a]!==n[a])return i+a;return s}o(b9,"diff");ce.compareIdentifiers=Ao;var XM=/^[0-9]+$/;function Ao(e,t){var r=XM.test(e),n=XM.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e0}o(Lu,"gt");ce.lt=Wh;function Wh(e,t,r){return Rn(e,t,r)<0}o(Wh,"lt");ce.eq=hv;function hv(e,t,r){return Rn(e,t,r)===0}o(hv,"eq");ce.neq=fx;function fx(e,t,r){return Rn(e,t,r)!==0}o(fx,"neq");ce.gte=dv;function dv(e,t,r){return Rn(e,t,r)>=0}o(dv,"gte");ce.lte=pv;function pv(e,t,r){return Rn(e,t,r)<=0}o(pv,"lte");ce.cmp=Fh;function Fh(e,t,r,n){switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return hv(e,r,n);case"!=":return fx(e,r,n);case">":return Lu(e,r,n);case">=":return dv(e,r,n);case"<":return Wh(e,r,n);case"<=":return pv(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}o(Fh,"cmp");ce.Comparator=Tr;function Tr(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof Tr){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof Tr))return new Tr(e,t);e=e.trim().split(/\s+/).join(" "),Le("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Uu?this.value="":this.value=this.operator+this.semver.version,Le("comp",this)}o(Tr,"Comparator");var Uu={};Tr.prototype.parse=function(e){var t=this.options.loose?He[fv]:He[lv],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1],this.operator==="="&&(this.operator=""),r[2]?this.semver=new Te(r[2],this.options.loose):this.semver=Uu};Tr.prototype.toString=function(){return this.value};Tr.prototype.test=function(e){return Le("Comparator.test",e,this.options.loose),this.semver===Uu?!0:(typeof e=="string"&&(e=new Te(e,this.options)),Fh(e,this.operator,this.semver,this.options))};Tr.prototype.intersects=function(e,t){if(!(e instanceof Tr))throw new TypeError("a Comparator is required");(!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1});var r;if(this.operator==="")return r=new et(e.value,t),$h(this.value,r,t);if(e.operator==="")return r=new et(this.value,t),$h(e.semver,r,t);var n=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),i=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),s=this.semver.version===e.semver.version,a=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),u=Fh(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),c=Fh(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return n||i||s&&a||u||c};ce.Range=et;function et(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof et)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new et(e.raw,t);if(e instanceof Tr)return new et(e.value,t);if(!(this instanceof et))return new et(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(function(r){return this.parseRange(r.trim())},this).filter(function(r){return r.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+this.raw);this.format()}o(et,"Range");et.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};et.prototype.toString=function(){return this.range};et.prototype.parseRange=function(e){var t=this.options.loose,r=t?He[ux]:He[ax];e=e.replace(r,V9),Le("hyphen replace",e),e=e.replace(He[cs],E9),Le("comparator trim",e,He[cs]),e=e.replace(He[Bo],O9),e=e.replace(He[Ro],v9);var n=t?He[fv]:He[lv],i=e.split(" ").map(function(s){return P9(s,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(i=i.filter(function(s){return!!s.match(n)})),i=i.map(function(s){return new Tr(s,this.options)},this),i};et.prototype.intersects=function(e,t){if(!(e instanceof et))throw new TypeError("a Range is required");return this.set.some(function(r){return r.every(function(n){return e.set.some(function(i){return i.every(function(s){return n.intersects(s,t)})})})})};ce.toComparators=D9;function D9(e,t){return new et(e,t).set.map(function(r){return r.map(function(n){return n.value}).join(" ").trim().split(" ")})}o(D9,"toComparators");function P9(e,t){return Le("comp",e,t),e=U9(e,t),Le("caret",e),e=L9(e,t),Le("tildes",e),e=F9(e,t),Le("xrange",e),e=z9(e,t),Le("stars",e),e}o(P9,"parseComparator");function Ht(e){return!e||e.toLowerCase()==="x"||e==="*"}o(Ht,"isX");function L9(e,t){return e.trim().split(/\s+/).map(function(r){return j9(r,t)}).join(" ")}o(L9,"replaceTildes");function j9(e,t){var r=t.loose?He[ix]:He[nx];return e.replace(r,function(n,i,s,a,u){Le("tilde",e,n,i,s,a,u);var c;return Ht(i)?c="":Ht(s)?c=">="+i+".0.0 <"+(+i+1)+".0.0":Ht(a)?c=">="+i+"."+s+".0 <"+i+"."+(+s+1)+".0":u?(Le("replaceTilde pr",u),c=">="+i+"."+s+"."+a+"-"+u+" <"+i+"."+(+s+1)+".0"):c=">="+i+"."+s+"."+a+" <"+i+"."+(+s+1)+".0",Le("tilde return",c),c})}o(j9,"replaceTilde");function U9(e,t){return e.trim().split(/\s+/).map(function(r){return W9(r,t)}).join(" ")}o(U9,"replaceCarets");function W9(e,t){Le("caret",e,t);var r=t.loose?He[ox]:He[sx];return e.replace(r,function(n,i,s,a,u){Le("caret",e,n,i,s,a,u);var c;return Ht(i)?c="":Ht(s)?c=">="+i+".0.0 <"+(+i+1)+".0.0":Ht(a)?i==="0"?c=">="+i+"."+s+".0 <"+i+"."+(+s+1)+".0":c=">="+i+"."+s+".0 <"+(+i+1)+".0.0":u?(Le("replaceCaret pr",u),i==="0"?s==="0"?c=">="+i+"."+s+"."+a+"-"+u+" <"+i+"."+s+"."+(+a+1):c=">="+i+"."+s+"."+a+"-"+u+" <"+i+"."+(+s+1)+".0":c=">="+i+"."+s+"."+a+"-"+u+" <"+(+i+1)+".0.0"):(Le("no pr"),i==="0"?s==="0"?c=">="+i+"."+s+"."+a+" <"+i+"."+s+"."+(+a+1):c=">="+i+"."+s+"."+a+" <"+i+"."+(+s+1)+".0":c=">="+i+"."+s+"."+a+" <"+(+i+1)+".0.0"),Le("caret return",c),c})}o(W9,"replaceCaret");function F9(e,t){return Le("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return $9(r,t)}).join(" ")}o(F9,"replaceXRanges");function $9(e,t){e=e.trim();var r=t.loose?He[tx]:He[ex];return e.replace(r,function(n,i,s,a,u,c){Le("xRange",e,n,i,s,a,u,c);var f=Ht(s),h=f||Ht(a),l=h||Ht(u),d=l;return i==="="&&d&&(i=""),f?i===">"||i==="<"?n="<0.0.0":n="*":i&&d?(h&&(a=0),u=0,i===">"?(i=">=",h?(s=+s+1,a=0,u=0):(a=+a+1,u=0)):i==="<="&&(i="<",h?s=+s+1:a=+a+1),n=i+s+"."+a+"."+u):h?n=">="+s+".0.0 <"+(+s+1)+".0.0":l&&(n=">="+s+"."+a+".0 <"+s+"."+(+a+1)+".0"),Le("xRange return",n),n})}o($9,"replaceXRange");function z9(e,t){return Le("replaceStars",e,t),e.trim().replace(He[cx],"")}o(z9,"replaceStars");function V9(e,t,r,n,i,s,a,u,c,f,h,l,d){return Ht(r)?t="":Ht(n)?t=">="+r+".0.0":Ht(i)?t=">="+r+"."+n+".0":t=">="+t,Ht(c)?u="":Ht(f)?u="<"+(+c+1)+".0.0":Ht(h)?u="<"+c+"."+(+f+1)+".0":l?u="<="+c+"."+f+"."+h+"-"+l:u="<="+u,(t+" "+u).trim()}o(V9,"hyphenReplace");et.prototype.test=function(e){if(!e)return!1;typeof e=="string"&&(e=new Te(e,this.options));for(var t=0;t0){var i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}o(H9,"testSet");ce.satisfies=$h;function $h(e,t,r){try{t=new et(t,r)}catch{return!1}return t.test(e)}o($h,"satisfies");ce.maxSatisfying=k9;function k9(e,t,r){var n=null,i=null;try{var s=new et(t,r)}catch{return null}return e.forEach(function(a){s.test(a)&&(!n||i.compare(a)===-1)&&(n=a,i=new Te(n,r))}),n}o(k9,"maxSatisfying");ce.minSatisfying=Y9;function Y9(e,t,r){var n=null,i=null;try{var s=new et(t,r)}catch{return null}return e.forEach(function(a){s.test(a)&&(!n||i.compare(a)===1)&&(n=a,i=new Te(n,r))}),n}o(Y9,"minSatisfying");ce.minVersion=G9;function G9(e,t){e=new et(e,t);var r=new Te("0.0.0");if(e.test(r)||(r=new Te("0.0.0-0"),e.test(r)))return r;r=null;for(var n=0;n":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!r||Lu(r,a))&&(r=a);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+s.operator)}})}return r&&e.test(r)?r:null}o(G9,"minVersion");ce.validRange=K9;function K9(e,t){try{return new et(e,t).range||"*"}catch{return null}}o(K9,"validRange");ce.ltr=X9;function X9(e,t,r){return mv(e,t,"<",r)}o(X9,"ltr");ce.gtr=J9;function J9(e,t,r){return mv(e,t,">",r)}o(J9,"gtr");ce.outside=mv;function mv(e,t,r,n){e=new Te(e,n),t=new et(t,n);var i,s,a,u,c;switch(r){case">":i=Lu,s=pv,a=Wh,u=">",c=">=";break;case"<":i=Wh,s=dv,a=Lu,u="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if($h(e,t,n))return!1;for(var f=0;f=0.0.0")),l=l||m,d=d||m,i(m.semver,l.semver,n)?l=m:a(m.semver,d.semver,n)&&(d=m)}),l.operator===u||l.operator===c||(!d.operator||d.operator===u)&&s(e,d.semver))return!1;if(d.operator===c&&a(e,d.semver))return!1}return!0}o(mv,"outside");ce.prerelease=Z9;function Z9(e,t){var r=fs(e,t);return r&&r.prerelease.length?r.prerelease:null}o(Z9,"prerelease");ce.intersects=Q9;function Q9(e,t,r){return e=new et(e,r),t=new et(t,r),e.intersects(t)}o(Q9,"intersects");ce.coerce=eZ;function eZ(e){if(e instanceof Te)return e;if(typeof e!="string")return null;var t=e.match(He[rx]);return t==null?null:fs(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}o(eZ,"coerce")});var px=w((Que,dx)=>{var xo=1e3,qo=xo*60,Do=qo*60,ls=Do*24,tZ=ls*7,rZ=ls*365.25;dx.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return nZ(e);if(r==="number"&&isFinite(e))return t.long?sZ(e):iZ(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function nZ(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*rZ;case"weeks":case"week":case"w":return r*tZ;case"days":case"day":case"d":return r*ls;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Do;case"minutes":case"minute":case"mins":case"min":case"m":return r*qo;case"seconds":case"second":case"secs":case"sec":case"s":return r*xo;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}o(nZ,"parse");function iZ(e){var t=Math.abs(e);return t>=ls?Math.round(e/ls)+"d":t>=Do?Math.round(e/Do)+"h":t>=qo?Math.round(e/qo)+"m":t>=xo?Math.round(e/xo)+"s":e+"ms"}o(iZ,"fmtShort");function sZ(e){var t=Math.abs(e);return t>=ls?kh(e,t,ls,"day"):t>=Do?kh(e,t,Do,"hour"):t>=qo?kh(e,t,qo,"minute"):t>=xo?kh(e,t,xo,"second"):e+" ms"}o(sZ,"fmtLong");function kh(e,t,r,n){var i=t>=r*1.5;return Math.round(e/r)+" "+n+(i?"s":"")}o(kh,"plural")});var yv=w((tce,mx)=>{function oZ(e){r.debug=r,r.default=r,r.coerce=c,r.disable=s,r.enable=i,r.enabled=a,r.humanize=px(),r.destroy=f,Object.keys(e).forEach(h=>{r[h]=e[h]}),r.names=[],r.skips=[],r.formatters={};function t(h){let l=0;for(let d=0;d{if(q==="%%")return"%";N++;let ue=r.formatters[H];if(typeof ue=="function"){let j=O[N];q=ue.call(T,j),O.splice(N,1),N--}return q}),r.formatArgs.call(T,O),(T.log||r.log).apply(T,O)}return o(E,"debug"),E.namespace=h,E.useColors=r.useColors(),E.color=r.selectColor(h),E.extend=n,E.destroy=r.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==r.namespaces&&(m=r.namespaces,S=r.enabled(h)),S),set:O=>{d=O}}),typeof r.init=="function"&&r.init(E),E}o(r,"createDebug");function n(h,l){let d=r(this.namespace+(typeof l>"u"?":":l)+h);return d.log=this.log,d}o(n,"extend");function i(h){r.save(h),r.namespaces=h,r.names=[],r.skips=[];let l,d=(typeof h=="string"?h:"").split(/[\s,]+/),m=d.length;for(l=0;l"-"+l)].join(",");return r.enable(""),h}o(s,"disable");function a(h){if(h[h.length-1]==="*")return!0;let l,d;for(l=0,d=r.skips.length;l{hr.formatArgs=uZ;hr.save=cZ;hr.load=fZ;hr.useColors=aZ;hr.storage=lZ();hr.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();hr.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function aZ(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}o(aZ,"useColors");function uZ(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Yh.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),e.splice(n,0,t)}o(uZ,"formatArgs");hr.log=console.debug||console.log||(()=>{});function cZ(e){try{e?hr.storage.setItem("debug",e):hr.storage.removeItem("debug")}catch{}}o(cZ,"save");function fZ(){let e;try{e=hr.storage.getItem("debug")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}o(fZ,"load");function lZ(){try{return localStorage}catch{}}o(lZ,"localstorage");Yh.exports=yv()(hr);var{formatters:hZ}=Yh.exports;hZ.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Sx=w((ice,gx)=>{"use strict";gx.exports=(e,t=process.argv)=>{let r=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return n!==-1&&(i===-1||n{"use strict";var dZ=require("os"),wx=require("tty"),Nr=Sx(),{env:yt}=process,Si;Nr("no-color")||Nr("no-colors")||Nr("color=false")||Nr("color=never")?Si=0:(Nr("color")||Nr("colors")||Nr("color=true")||Nr("color=always"))&&(Si=1);"FORCE_COLOR"in yt&&(yt.FORCE_COLOR==="true"?Si=1:yt.FORCE_COLOR==="false"?Si=0:Si=yt.FORCE_COLOR.length===0?1:Math.min(parseInt(yt.FORCE_COLOR,10),3));function gv(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}o(gv,"translateLevel");function Sv(e,t){if(Si===0)return 0;if(Nr("color=16m")||Nr("color=full")||Nr("color=truecolor"))return 3;if(Nr("color=256"))return 2;if(e&&!t&&Si===void 0)return 0;let r=Si||0;if(yt.TERM==="dumb")return r;if(process.platform==="win32"){let n=dZ.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in yt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in yt)||yt.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in yt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(yt.TEAMCITY_VERSION)?1:0;if(yt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in yt){let n=parseInt((yt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(yt.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(yt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(yt.TERM)||"COLORTERM"in yt?1:r}o(Sv,"supportsColor");function pZ(e){let t=Sv(e,e&&e.isTTY);return gv(t)}o(pZ,"getSupportLevel");Ox.exports={supportsColor:pZ,stdout:gv(Sv(!0,wx.isatty(1))),stderr:gv(Sv(!0,wx.isatty(2)))}});var _x=w((Nt,Kh)=>{var mZ=require("tty"),Gh=require("util");Nt.init=EZ;Nt.log=wZ;Nt.formatArgs=gZ;Nt.save=OZ;Nt.load=vZ;Nt.useColors=yZ;Nt.destroy=Gh.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Nt.colors=[6,2,3,4,5,1];try{let e=vx();e&&(e.stderr||e).level>=2&&(Nt.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Nt.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(i,s)=>s.toUpperCase()),n=process.env[t];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),e[r]=n,e},{});function yZ(){return"colors"in Nt.inspectOpts?!!Nt.inspectOpts.colors:mZ.isatty(process.stderr.fd)}o(yZ,"useColors");function gZ(e){let{namespace:t,useColors:r}=this;if(r){let n=this.color,i="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${i};1m${t} \x1B[0m`;e[0]=s+e[0].split(` +`).join(` +`+s),e.push(i+"m+"+Kh.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=SZ()+t+" "+e[0]}o(gZ,"formatArgs");function SZ(){return Nt.inspectOpts.hideDate?"":new Date().toISOString()+" "}o(SZ,"getDate");function wZ(...e){return process.stderr.write(Gh.format(...e)+` +`)}o(wZ,"log");function OZ(e){e?process.env.DEBUG=e:delete process.env.DEBUG}o(OZ,"save");function vZ(){return process.env.DEBUG}o(vZ,"load");function EZ(e){e.inspectOpts={};let t=Object.keys(Nt.inspectOpts);for(let r=0;rt.trim()).join(" ")};Ex.O=function(e){return this.inspectOpts.colors=this.useColors,Gh.inspect(e,this.inspectOpts)}});var Xh=w((uce,wv)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?wv.exports=yx():wv.exports=_x()});var _v=w((cce,Bx)=>{var Nx=9007199254740991,_Z="[object Arguments]",TZ="[object Function]",NZ="[object GeneratorFunction]",bZ=/^(?:0|[1-9]\d*)$/;function bx(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}o(bx,"apply");function CZ(e,t){for(var r=-1,n=Array(e);++r1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(s=e.length>3&&typeof s=="function"?(i--,s):void 0,a&&DZ(r[0],r[1],a)&&(s=i<3?void 0:s,i=1),t=Object(t);++n-1&&e%1==0&&e-1&&e%1==0&&e<=Nx}o($Z,"isLength");function Ev(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}o(Ev,"isObject");function zZ(e){return!!e&&typeof e=="object"}o(zZ,"isObjectLike");var VZ=qZ(function(e,t,r,n){xZ(t,kZ(t),e,n)}),HZ=Ax(function(e){return e.push(void 0,BZ),bx(VZ,void 0,e)});function kZ(e){return vv(e)?IZ(e,!0):MZ(e)}o(kZ,"keysIn");Bx.exports=HZ});var Nv=w((lce,Mx)=>{var YZ=_v(),Rx=require("stream").Readable,GZ=require("util").inherits;function Tv(e,t,r){this.db=e,this.collectionName=t,this.opts=r,r=YZ(r||{},{query:{},size:5,fields:null,raw:!1,sort:{_id:-1},maxTimeMS:void 0,promoteValues:!0}),this.query=r.query||{},this.size=r.size,this.raw=r.raw,this.fields=r.fields,this.sort=r.sort,this.maxTimeMS=r.maxTimeMS,this.promoteValues=r.promoteValues,Rx.call(this,{objectMode:!0})}o(Tv,"BaseSampler");GZ(Tv,Rx);Object.defineProperty(Tv.prototype,"collection",{get:function(){return this.db.collection(this.collectionName,{})}});Mx.exports=Tv});var qx=w((bv,xx)=>{(function(e,t){"use strict";typeof bv=="object"?xx.exports=t():typeof define=="function"&&define.amd?define(t):e.Reservoir=t()})(bv,function(){"use strict";var e=22,t="none";function r(a,i){var s=i||Math.random,a=Math.max(1,Math.floor(a)>>0||1),u=0,c=-1,f=R,h=e*a;t==="R"?f=T:t==="X"?h=1/0:t==="Z"&&(f=_);var l=0,d=Math.exp(-Math.log(s())/a),m=null,S=[];S.pushSome=function(){this.length=Math.min(this.length,a);for(var N=0;N=a;)q++,N++,P=Math.floor(s()*N);return m=P,q}o(T,"algorithmR");function R(){var N=u,P=s(),q=0,H;if(u<=h){for(N++,l++,H=l/N;H>P;)q++,N++,l++,H=H*l/N;return q}else return f=_,f()}o(R,"algorithmX");function _(){for(var N=u-a+1,P,q,H;;){var ue=s(),j=u*(d-1),te=Math.floor(j),K=(u+1)/N;K*=K;var W=N+te,z=Math.exp(Math.log(ue*K*W/(u+j))/a),Y=(u+j)/W*N/u;if(z<=Y){d=Y/z;break}var fe=ue*(u+1)/N*(u+te+1)/(u+j);for(a=H;q--)fe=fe*q/P,P--;if(d=Math.exp(-Math.log(s())/a),Math.exp(Math.log(fe)/a)<=(u+j)/u)break}return te}return o(_,"algorithmZ"),S}return o(r,"_Reservoir"),r})});var Wx=w((pce,Ux)=>{var Dx=1/0,Lx=9007199254740991,KZ=17976931348623157e292,Px=0/0,XZ="[object Function]",JZ="[object GeneratorFunction]",ZZ="[object Symbol]",QZ=/^\s+|\s+$/g,eQ=/^[-+]0x[0-9a-f]+$/i,tQ=/^0b[01]+$/i,rQ=/^0o[0-7]+$/i,nQ=/^(?:0|[1-9]\d*)$/,iQ=parseInt,sQ=Object.prototype,jx=sQ.toString,oQ=Math.ceil,aQ=Math.max;function uQ(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),r=r>i?i:r,r<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var s=Array(i);++n-1&&e%1==0&&e-1&&e%1==0&&e<=Lx}o(mQ,"isLength");function Jh(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}o(Jh,"isObject");function yQ(e){return!!e&&typeof e=="object"}o(yQ,"isObjectLike");function gQ(e){return typeof e=="symbol"||yQ(e)&&jx.call(e)==ZZ}o(gQ,"isSymbol");function SQ(e){if(!e)return e===0?e:0;if(e=OQ(e),e===Dx||e===-Dx){var t=e<0?-1:1;return t*KZ}return e===e?e:0}o(SQ,"toFinite");function wQ(e){var t=SQ(e),r=t%1;return t===t?r?t-r:t:0}o(wQ,"toInteger");function OQ(e){if(typeof e=="number")return e;if(gQ(e))return Px;if(Jh(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=Jh(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=e.replace(QZ,"");var r=tQ.test(e);return r||rQ.test(e)?iQ(e.slice(2),r?2:8):eQ.test(e)?Px:+e}o(OQ,"toNumber");Ux.exports=lQ});var Av=w((yce,zx)=>{var $x=Nv(),vQ=require("util").inherits,Zh=JO(),EQ=qx(),_Q=_v(),TQ=Wx(),Fx=Xh()("mongodb-collection-sample:reservoir-sampler"),NQ=1e4,bQ=1e3;function CQ(e,t,r){r=_Q(r||{},{chunkSize:bQ,promoteValues:!0});var n=new EQ(t),i=Zh.through(o(function(a){n.pushSome(a)},"write"),o(function(){var a=TQ(n,r.chunkSize),u=a.map(function(c){var f=e.find({_id:{$in:c}},{promoteValues:r.promoteValues,raw:r.raw});return r.fields&&f.project(r.fields),r.maxTimeMS&&f.maxTimeMS(r.maxTimeMS),f.stream()});Zh.merge(u).pipe(Zh.through(function(c){i.emit("data",c)})).on("end",function(){i.emit("end")})},"end"));return i}o(CQ,"reservoirStream");function Cv(e,t,r){this.running=!1,this.chunkSize=r?r.chunkSize:void 0,$x.call(this,e,t,r)}o(Cv,"ReservoirSampler");vQ(Cv,$x);Cv.prototype._read=function(){this.running||(this.running=!0,Fx("using query `%j`",this.query),this.collection.countDocuments(this.query,function(e,t){if(e)return this.emit("error",e);Fx("sampling %d documents from a collection with %d documents",this.size,t),this.collection.find(this.query,{projection:{_id:1},sort:this.sort,limit:NQ}).stream().pipe(Zh.map(function(r,n){return n(null,r._id)})).pipe(CQ(this.collection,this.size,{chunkSize:this.chunkSize,fields:this.fields,maxTimeMS:this.maxTimeMS,raw:this.raw,promoteValues:this.promoteValues})).on("error",this.emit.bind(this,"error")).on("data",this.push.bind(this)).on("end",function(){this.running=!1,this.push(null)}.bind(this))}.bind(this)))};zx.exports=Cv});var br=w(wi=>{"use strict";var Vx=wi&&wi.__extends||function(){var e=o(function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},e(t,r)},"extendStatics");return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}o(n,"__"),t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(wi,"__esModule",{value:!0});wi.BSONTypeError=wi.BSONError=void 0;var AQ=function(e){Vx(t,e);function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return o(t,"BSONError"),Object.defineProperty(t.prototype,"name",{get:function(){return"BSONError"},enumerable:!1,configurable:!0}),t}(Error);wi.BSONError=AQ;var IQ=function(e){Vx(t,e);function t(r){var n=e.call(this,r)||this;return Object.setPrototypeOf(n,t.prototype),n}return o(t,"BSONTypeError"),Object.defineProperty(t.prototype,"name",{get:function(){return"BSONTypeError"},enumerable:!1,configurable:!0}),t}(TypeError);wi.BSONTypeError=IQ});var Iv=w(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});ed.getGlobal=void 0;function Qh(e){return e&&e.Math==Math&&e}o(Qh,"checkForMath");function BQ(){return Qh(typeof globalThis=="object"&&globalThis)||Qh(typeof window=="object"&&window)||Qh(typeof self=="object"&&self)||Qh(typeof global=="object"&&global)||Function("return this")()}o(BQ,"getGlobal");ed.getGlobal=BQ});var Ur=w(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.deprecate=ke.isObjectLike=ke.isDate=ke.haveBuffer=ke.isMap=ke.isRegExp=ke.isBigUInt64Array=ke.isBigInt64Array=ke.isUint8Array=ke.isAnyArrayBuffer=ke.randomBytes=ke.normalizedFunctionString=void 0;var Bv=require("buffer"),RQ=Iv();function MQ(e){return e.toString().replace("function(","function (")}o(MQ,"normalizedFunctionString");ke.normalizedFunctionString=MQ;function xQ(){var e=(0,RQ.getGlobal)();return typeof e.navigator=="object"&&e.navigator.product==="ReactNative"}o(xQ,"isReactNative");var Hx=o(function(t){var r=xQ()?"BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.":"BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.";console.warn(r);for(var n=Bv.Buffer.alloc(t),i=0;i{"use strict";Object.defineProperty(td,"__esModule",{value:!0});td.ensureBuffer=void 0;var Yx=require("buffer"),VQ=br(),HQ=Ur();function kQ(e){if(ArrayBuffer.isView(e))return Yx.Buffer.from(e.buffer,e.byteOffset,e.byteLength);if((0,HQ.isAnyArrayBuffer)(e))return Yx.Buffer.from(e);throw new VQ.BSONTypeError("Must use either Buffer or TypedArray")}o(kQ,"ensureBuffer");td.ensureBuffer=kQ});var Gx=w(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.bufferToUuidHexString=Mn.uuidHexStringToBuffer=Mn.uuidValidateString=void 0;var YQ=require("buffer"),GQ=br(),KQ=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i,XQ=o(function(e){return typeof e=="string"&&KQ.test(e)},"uuidValidateString");Mn.uuidValidateString=XQ;var JQ=o(function(e){if(!(0,Mn.uuidValidateString)(e))throw new GQ.BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');var t=e.replace(/-/g,"");return YQ.Buffer.from(t,"hex")},"uuidHexStringToBuffer");Mn.uuidHexStringToBuffer=JQ;var ZQ=o(function(e,t){return t===void 0&&(t=!0),t?e.toString("hex",0,4)+"-"+e.toString("hex",4,6)+"-"+e.toString("hex",6,8)+"-"+e.toString("hex",8,10)+"-"+e.toString("hex",10,16):e.toString("hex")},"bufferToUuidHexString");Mn.bufferToUuidHexString=ZQ});var Po=w(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.BSON_BINARY_SUBTYPE_USER_DEFINED=k.BSON_BINARY_SUBTYPE_COLUMN=k.BSON_BINARY_SUBTYPE_ENCRYPTED=k.BSON_BINARY_SUBTYPE_MD5=k.BSON_BINARY_SUBTYPE_UUID_NEW=k.BSON_BINARY_SUBTYPE_UUID=k.BSON_BINARY_SUBTYPE_BYTE_ARRAY=k.BSON_BINARY_SUBTYPE_FUNCTION=k.BSON_BINARY_SUBTYPE_DEFAULT=k.BSON_DATA_MAX_KEY=k.BSON_DATA_MIN_KEY=k.BSON_DATA_DECIMAL128=k.BSON_DATA_LONG=k.BSON_DATA_TIMESTAMP=k.BSON_DATA_INT=k.BSON_DATA_CODE_W_SCOPE=k.BSON_DATA_SYMBOL=k.BSON_DATA_CODE=k.BSON_DATA_DBPOINTER=k.BSON_DATA_REGEXP=k.BSON_DATA_NULL=k.BSON_DATA_DATE=k.BSON_DATA_BOOLEAN=k.BSON_DATA_OID=k.BSON_DATA_UNDEFINED=k.BSON_DATA_BINARY=k.BSON_DATA_ARRAY=k.BSON_DATA_OBJECT=k.BSON_DATA_STRING=k.BSON_DATA_NUMBER=k.JS_INT_MIN=k.JS_INT_MAX=k.BSON_INT64_MIN=k.BSON_INT64_MAX=k.BSON_INT32_MIN=k.BSON_INT32_MAX=void 0;k.BSON_INT32_MAX=2147483647;k.BSON_INT32_MIN=-2147483648;k.BSON_INT64_MAX=Math.pow(2,63)-1;k.BSON_INT64_MIN=-Math.pow(2,63);k.JS_INT_MAX=Math.pow(2,53);k.JS_INT_MIN=-Math.pow(2,53);k.BSON_DATA_NUMBER=1;k.BSON_DATA_STRING=2;k.BSON_DATA_OBJECT=3;k.BSON_DATA_ARRAY=4;k.BSON_DATA_BINARY=5;k.BSON_DATA_UNDEFINED=6;k.BSON_DATA_OID=7;k.BSON_DATA_BOOLEAN=8;k.BSON_DATA_DATE=9;k.BSON_DATA_NULL=10;k.BSON_DATA_REGEXP=11;k.BSON_DATA_DBPOINTER=12;k.BSON_DATA_CODE=13;k.BSON_DATA_SYMBOL=14;k.BSON_DATA_CODE_W_SCOPE=15;k.BSON_DATA_INT=16;k.BSON_DATA_TIMESTAMP=17;k.BSON_DATA_LONG=18;k.BSON_DATA_DECIMAL128=19;k.BSON_DATA_MIN_KEY=255;k.BSON_DATA_MAX_KEY=127;k.BSON_BINARY_SUBTYPE_DEFAULT=0;k.BSON_BINARY_SUBTYPE_FUNCTION=1;k.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;k.BSON_BINARY_SUBTYPE_UUID=3;k.BSON_BINARY_SUBTYPE_UUID_NEW=4;k.BSON_BINARY_SUBTYPE_MD5=5;k.BSON_BINARY_SUBTYPE_ENCRYPTED=6;k.BSON_BINARY_SUBTYPE_COLUMN=7;k.BSON_BINARY_SUBTYPE_USER_DEFINED=128});var jo=w(Oi=>{"use strict";var QQ=Oi&&Oi.__extends||function(){var e=o(function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},e(t,r)},"extendStatics");return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}o(n,"__"),t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(Oi,"__esModule",{value:!0});Oi.UUID=Oi.Binary=void 0;var xn=require("buffer"),Mv=$u(),Lo=Gx(),Kx=Ur(),hs=br(),Xx=Po(),zu=function(){function e(t,r){if(!(this instanceof e))return new e(t,r);if(t!=null&&typeof t!="string"&&!ArrayBuffer.isView(t)&&!(t instanceof ArrayBuffer)&&!Array.isArray(t))throw new hs.BSONTypeError("Binary can only be constructed from string, Buffer, TypedArray, or Array");this.sub_type=r??e.BSON_BINARY_SUBTYPE_DEFAULT,t==null?(this.buffer=xn.Buffer.alloc(e.BUFFER_SIZE),this.position=0):(typeof t=="string"?this.buffer=xn.Buffer.from(t,"binary"):Array.isArray(t)?this.buffer=xn.Buffer.from(t):this.buffer=(0,Mv.ensureBuffer)(t),this.position=this.buffer.byteLength)}return o(e,"Binary"),e.prototype.put=function(t){if(typeof t=="string"&&t.length!==1)throw new hs.BSONTypeError("only accepts single character String");if(typeof t!="number"&&t.length!==1)throw new hs.BSONTypeError("only accepts single character Uint8Array or Array");var r;if(typeof t=="string"?r=t.charCodeAt(0):typeof t=="number"?r=t:r=t[0],r<0||r>255)throw new hs.BSONTypeError("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.length>this.position)this.buffer[this.position++]=r;else{var n=xn.Buffer.alloc(e.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=r}},e.prototype.write=function(t,r){if(r=typeof r=="number"?r:this.position,this.buffer.lengththis.position?r+t.length:this.position):typeof t=="string"&&(this.buffer.write(t,r,t.length,"binary"),this.position=r+t.length>this.position?r+t.length:this.position)},e.prototype.read=function(t,r){return r=r&&r>0?r:this.position,this.buffer.slice(t,t+r)},e.prototype.value=function(t){return t=!!t,t&&this.buffer.length===this.position?this.buffer:t?this.buffer.slice(0,this.position):this.buffer.toString("binary",0,this.position)},e.prototype.length=function(){return this.position},e.prototype.toJSON=function(){return this.buffer.toString("base64")},e.prototype.toString=function(t){return this.buffer.toString(t)},e.prototype.toExtendedJSON=function(t){t=t||{};var r=this.buffer.toString("base64"),n=Number(this.sub_type).toString(16);return t.legacy?{$binary:r,$type:n.length===1?"0"+n:n}:{$binary:{base64:r,subType:n.length===1?"0"+n:n}}},e.prototype.toUUID=function(){if(this.sub_type===e.SUBTYPE_UUID)return new xv(this.buffer.slice(0,this.position));throw new hs.BSONError('Binary sub_type "'.concat(this.sub_type,'" is not supported for converting to UUID. Only "').concat(e.SUBTYPE_UUID,'" is currently supported.'))},e.fromExtendedJSON=function(t,r){r=r||{};var n,i;if("$binary"in t?r.legacy&&typeof t.$binary=="string"&&"$type"in t?(i=t.$type?parseInt(t.$type,16):0,n=xn.Buffer.from(t.$binary,"base64")):typeof t.$binary!="string"&&(i=t.$binary.subType?parseInt(t.$binary.subType,16):0,n=xn.Buffer.from(t.$binary.base64,"base64")):"$uuid"in t&&(i=4,n=(0,Lo.uuidHexStringToBuffer)(t.$uuid)),!n)throw new hs.BSONTypeError("Unexpected Binary Extended JSON format ".concat(JSON.stringify(t)));return i===Xx.BSON_BINARY_SUBTYPE_UUID_NEW?new xv(n):new e(n,i)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.value(!0);return'new Binary(Buffer.from("'.concat(t.toString("hex"),'", "hex"), ').concat(this.sub_type,")")},e.BSON_BINARY_SUBTYPE_DEFAULT=0,e.BUFFER_SIZE=256,e.SUBTYPE_DEFAULT=0,e.SUBTYPE_FUNCTION=1,e.SUBTYPE_BYTE_ARRAY=2,e.SUBTYPE_UUID_OLD=3,e.SUBTYPE_UUID=4,e.SUBTYPE_MD5=5,e.SUBTYPE_ENCRYPTED=6,e.SUBTYPE_COLUMN=7,e.SUBTYPE_USER_DEFINED=128,e}();Oi.Binary=zu;Object.defineProperty(zu.prototype,"_bsontype",{value:"Binary"});var Rv=16,xv=function(e){QQ(t,e);function t(r){var n=this,i,s;if(r==null)i=t.generate();else if(r instanceof t)i=xn.Buffer.from(r.buffer),s=r.__id;else if(ArrayBuffer.isView(r)&&r.byteLength===Rv)i=(0,Mv.ensureBuffer)(r);else if(typeof r=="string")i=(0,Lo.uuidHexStringToBuffer)(r);else throw new hs.BSONTypeError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");return n=e.call(this,i,Xx.BSON_BINARY_SUBTYPE_UUID_NEW)||this,n.__id=s,n}return o(t,"UUID"),Object.defineProperty(t.prototype,"id",{get:function(){return this.buffer},set:function(r){this.buffer=r,t.cacheHexString&&(this.__id=(0,Lo.bufferToUuidHexString)(r))},enumerable:!1,configurable:!0}),t.prototype.toHexString=function(r){if(r===void 0&&(r=!0),t.cacheHexString&&this.__id)return this.__id;var n=(0,Lo.bufferToUuidHexString)(this.id,r);return t.cacheHexString&&(this.__id=n),n},t.prototype.toString=function(r){return r?this.id.toString(r):this.toHexString()},t.prototype.toJSON=function(){return this.toHexString()},t.prototype.equals=function(r){if(!r)return!1;if(r instanceof t)return r.id.equals(this.id);try{return new t(r).id.equals(this.id)}catch{return!1}},t.prototype.toBinary=function(){return new zu(this.id,zu.SUBTYPE_UUID)},t.generate=function(){var r=(0,Kx.randomBytes)(Rv);return r[6]=r[6]&15|64,r[8]=r[8]&63|128,xn.Buffer.from(r)},t.isValid=function(r){return r?r instanceof t?!0:typeof r=="string"?(0,Lo.uuidValidateString)(r):(0,Kx.isUint8Array)(r)?r.length!==Rv?!1:(r[6]&240)===64&&(r[8]&128)===128:!1:!1},t.createFromHexString=function(r){var n=(0,Lo.uuidHexStringToBuffer)(r);return new t(n)},t.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},t.prototype.inspect=function(){return'new UUID("'.concat(this.toHexString(),'")')},t}(zu);Oi.UUID=xv});var nd=w(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.Code=void 0;var Jx=function(){function e(t,r){if(!(this instanceof e))return new e(t,r);this.code=t,this.scope=r}return o(e,"Code"),e.prototype.toJSON=function(){return{code:this.code,scope:this.scope}},e.prototype.toExtendedJSON=function(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}},e.fromExtendedJSON=function(t){return new e(t.$code,t.$scope)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.toJSON();return'new Code("'.concat(String(t.code),'"').concat(t.scope?", ".concat(JSON.stringify(t.scope)):"",")")},e}();rd.Code=Jx;Object.defineProperty(Jx.prototype,"_bsontype",{value:"Code"})});var id=w(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.DBRef=Uo.isDBRefLike=void 0;var eee=Ur();function tee(e){return(0,eee.isObjectLike)(e)&&e.$id!=null&&typeof e.$ref=="string"&&(e.$db==null||typeof e.$db=="string")}o(tee,"isDBRefLike");Uo.isDBRefLike=tee;var Zx=function(){function e(t,r,n,i){if(!(this instanceof e))return new e(t,r,n,i);var s=t.split(".");s.length===2&&(n=s.shift(),t=s.shift()),this.collection=t,this.oid=r,this.db=n,this.fields=i||{}}return o(e,"DBRef"),Object.defineProperty(e.prototype,"namespace",{get:function(){return this.collection},set:function(t){this.collection=t},enumerable:!1,configurable:!0}),e.prototype.toJSON=function(){var t=Object.assign({$ref:this.collection,$id:this.oid},this.fields);return this.db!=null&&(t.$db=this.db),t},e.prototype.toExtendedJSON=function(t){t=t||{};var r={$ref:this.collection,$id:this.oid};return t.legacy||(this.db&&(r.$db=this.db),r=Object.assign(r,this.fields)),r},e.fromExtendedJSON=function(t){var r=Object.assign({},t);return delete r.$ref,delete r.$id,delete r.$db,new e(t.$ref,t.$id,t.$db,r)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return'new DBRef("'.concat(this.namespace,'", new ObjectId("').concat(String(t),'")').concat(this.db?', "'.concat(this.db,'"'):"",")")},e}();Uo.DBRef=Zx;Object.defineProperty(Zx.prototype,"_bsontype",{value:"DBRef"})});var ds=w(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});sd.Long=void 0;var ree=Ur(),Cr=void 0;try{Cr=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var Qx=65536,nee=1<<24,Wo=Qx*Qx,nq=Wo*Wo,eq=nq/2,tq={},rq={},qv=function(){function e(t,r,n){if(t===void 0&&(t=0),!(this instanceof e))return new e(t,r,n);typeof t=="bigint"?Object.assign(this,e.fromBigInt(t,!!r)):typeof t=="string"?Object.assign(this,e.fromString(t,!!r)):(this.low=t|0,this.high=r|0,this.unsigned=!!n),Object.defineProperty(this,"__isLong__",{value:!0,configurable:!1,writable:!1,enumerable:!1})}return o(e,"Long"),e.fromBits=function(t,r,n){return new e(t,r,n)},e.fromInt=function(t,r){var n,i,s;return r?(t>>>=0,(s=0<=t&&t<256)&&(i=rq[t],i)?i:(n=e.fromBits(t,(t|0)<0?-1:0,!0),s&&(rq[t]=n),n)):(t|=0,(s=-128<=t&&t<128)&&(i=tq[t],i)?i:(n=e.fromBits(t,t<0?-1:0,!1),s&&(tq[t]=n),n))},e.fromNumber=function(t,r){if(isNaN(t))return r?e.UZERO:e.ZERO;if(r){if(t<0)return e.UZERO;if(t>=nq)return e.MAX_UNSIGNED_VALUE}else{if(t<=-eq)return e.MIN_VALUE;if(t+1>=eq)return e.MAX_VALUE}return t<0?e.fromNumber(-t,r).neg():e.fromBits(t%Wo|0,t/Wo|0,r)},e.fromBigInt=function(t,r){return e.fromString(t.toString(),r)},e.fromString=function(t,r,n){if(t.length===0)throw Error("empty string");if(t==="NaN"||t==="Infinity"||t==="+Infinity"||t==="-Infinity")return e.ZERO;if(typeof r=="number"?(n=r,r=!1):r=!!r,n=n||10,n<2||360)throw Error("interior hyphen");if(i===0)return e.fromString(t.substring(1),r,n).neg();for(var s=e.fromNumber(Math.pow(n,8)),a=e.ZERO,u=0;u>>16,n=this.high&65535,i=this.low>>>16,s=this.low&65535,a=t.high>>>16,u=t.high&65535,c=t.low>>>16,f=t.low&65535,h=0,l=0,d=0,m=0;return m+=s+f,d+=m>>>16,m&=65535,d+=i+c,l+=d>>>16,d&=65535,l+=n+u,h+=l>>>16,l&=65535,h+=r+a,h&=65535,e.fromBits(d<<16|m,h<<16|l,this.unsigned)},e.prototype.and=function(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low&t.low,this.high&t.high,this.unsigned)},e.prototype.compare=function(t){if(e.isLong(t)||(t=e.fromValue(t)),this.eq(t))return 0;var r=this.isNegative(),n=t.isNegative();return r&&!n?-1:!r&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},e.prototype.comp=function(t){return this.compare(t)},e.prototype.divide=function(t){if(e.isLong(t)||(t=e.fromValue(t)),t.isZero())throw Error("division by zero");if(Cr){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var r=(this.unsigned?Cr.div_u:Cr.div_s)(this.low,this.high,t.low,t.high);return e.fromBits(r,Cr.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?e.UZERO:e.ZERO;var n,i,s;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return e.UZERO;if(t.gt(this.shru(1)))return e.UONE;s=e.UZERO}else{if(this.eq(e.MIN_VALUE)){if(t.eq(e.ONE)||t.eq(e.NEG_ONE))return e.MIN_VALUE;if(t.eq(e.MIN_VALUE))return e.ONE;var a=this.shr(1);return n=a.div(t).shl(1),n.eq(e.ZERO)?t.isNegative()?e.ONE:e.NEG_ONE:(i=this.sub(t.mul(n)),s=n.add(i.div(t)),s)}else if(t.eq(e.MIN_VALUE))return this.unsigned?e.UZERO:e.ZERO;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=e.ZERO}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var u=Math.ceil(Math.log(n)/Math.LN2),c=u<=48?1:Math.pow(2,u-48),f=e.fromNumber(n),h=f.mul(t);h.isNegative()||h.gt(i);)n-=c,f=e.fromNumber(n,this.unsigned),h=f.mul(t);f.isZero()&&(f=e.ONE),s=s.add(f),i=i.sub(h)}return s},e.prototype.div=function(t){return this.divide(t)},e.prototype.equals=function(t){return e.isLong(t)||(t=e.fromValue(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low},e.prototype.eq=function(t){return this.equals(t)},e.prototype.getHighBits=function(){return this.high},e.prototype.getHighBitsUnsigned=function(){return this.high>>>0},e.prototype.getLowBits=function(){return this.low},e.prototype.getLowBitsUnsigned=function(){return this.low>>>0},e.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.eq(e.MIN_VALUE)?64:this.neg().getNumBitsAbs();var t=this.high!==0?this.high:this.low,r;for(r=31;r>0&&!(t&1<0},e.prototype.gt=function(t){return this.greaterThan(t)},e.prototype.greaterThanOrEqual=function(t){return this.comp(t)>=0},e.prototype.gte=function(t){return this.greaterThanOrEqual(t)},e.prototype.ge=function(t){return this.greaterThanOrEqual(t)},e.prototype.isEven=function(){return(this.low&1)===0},e.prototype.isNegative=function(){return!this.unsigned&&this.high<0},e.prototype.isOdd=function(){return(this.low&1)===1},e.prototype.isPositive=function(){return this.unsigned||this.high>=0},e.prototype.isZero=function(){return this.high===0&&this.low===0},e.prototype.lessThan=function(t){return this.comp(t)<0},e.prototype.lt=function(t){return this.lessThan(t)},e.prototype.lessThanOrEqual=function(t){return this.comp(t)<=0},e.prototype.lte=function(t){return this.lessThanOrEqual(t)},e.prototype.modulo=function(t){if(e.isLong(t)||(t=e.fromValue(t)),Cr){var r=(this.unsigned?Cr.rem_u:Cr.rem_s)(this.low,this.high,t.low,t.high);return e.fromBits(r,Cr.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},e.prototype.mod=function(t){return this.modulo(t)},e.prototype.rem=function(t){return this.modulo(t)},e.prototype.multiply=function(t){if(this.isZero())return e.ZERO;if(e.isLong(t)||(t=e.fromValue(t)),Cr){var r=Cr.mul(this.low,this.high,t.low,t.high);return e.fromBits(r,Cr.get_high(),this.unsigned)}if(t.isZero())return e.ZERO;if(this.eq(e.MIN_VALUE))return t.isOdd()?e.MIN_VALUE:e.ZERO;if(t.eq(e.MIN_VALUE))return this.isOdd()?e.MIN_VALUE:e.ZERO;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(e.TWO_PWR_24)&&t.lt(e.TWO_PWR_24))return e.fromNumber(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=this.high&65535,s=this.low>>>16,a=this.low&65535,u=t.high>>>16,c=t.high&65535,f=t.low>>>16,h=t.low&65535,l=0,d=0,m=0,S=0;return S+=a*h,m+=S>>>16,S&=65535,m+=s*h,d+=m>>>16,m&=65535,m+=a*f,d+=m>>>16,m&=65535,d+=i*h,l+=d>>>16,d&=65535,d+=s*f,l+=d>>>16,d&=65535,d+=a*c,l+=d>>>16,d&=65535,l+=n*h+i*f+s*c+a*u,l&=65535,e.fromBits(m<<16|S,l<<16|d,this.unsigned)},e.prototype.mul=function(t){return this.multiply(t)},e.prototype.negate=function(){return!this.unsigned&&this.eq(e.MIN_VALUE)?e.MIN_VALUE:this.not().add(e.ONE)},e.prototype.neg=function(){return this.negate()},e.prototype.not=function(){return e.fromBits(~this.low,~this.high,this.unsigned)},e.prototype.notEquals=function(t){return!this.equals(t)},e.prototype.neq=function(t){return this.notEquals(t)},e.prototype.ne=function(t){return this.notEquals(t)},e.prototype.or=function(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low|t.low,this.high|t.high,this.unsigned)},e.prototype.shiftLeft=function(t){return e.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?e.fromBits(this.low<>>32-t,this.unsigned):e.fromBits(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):e.fromBits(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},e.prototype.shr=function(t){return this.shiftRight(t)},e.prototype.shiftRightUnsigned=function(t){if(e.isLong(t)&&(t=t.toInt()),t&=63,t===0)return this;var r=this.high;if(t<32){var n=this.low;return e.fromBits(n>>>t|r<<32-t,r>>>t,this.unsigned)}else return t===32?e.fromBits(r,0,this.unsigned):e.fromBits(r>>>t-32,0,this.unsigned)},e.prototype.shr_u=function(t){return this.shiftRightUnsigned(t)},e.prototype.shru=function(t){return this.shiftRightUnsigned(t)},e.prototype.subtract=function(t){return e.isLong(t)||(t=e.fromValue(t)),this.add(t.neg())},e.prototype.sub=function(t){return this.subtract(t)},e.prototype.toInt=function(){return this.unsigned?this.low>>>0:this.low},e.prototype.toNumber=function(){return this.unsigned?(this.high>>>0)*Wo+(this.low>>>0):this.high*Wo+(this.low>>>0)},e.prototype.toBigInt=function(){return BigInt(this.toString())},e.prototype.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},e.prototype.toBytesLE=function(){var t=this.high,r=this.low;return[r&255,r>>>8&255,r>>>16&255,r>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]},e.prototype.toBytesBE=function(){var t=this.high,r=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,r>>>24,r>>>16&255,r>>>8&255,r&255]},e.prototype.toSigned=function(){return this.unsigned?e.fromBits(this.low,this.high,!1):this},e.prototype.toString=function(t){if(t=t||10,t<2||36>>0,h=f.toString(t);if(a=c,a.isZero())return h+u;for(;h.length<6;)h="0"+h;u=""+h+u}},e.prototype.toUnsigned=function(){return this.unsigned?this:e.fromBits(this.low,this.high,!0)},e.prototype.xor=function(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low^t.low,this.high^t.high,this.unsigned)},e.prototype.eqz=function(){return this.isZero()},e.prototype.le=function(t){return this.lessThanOrEqual(t)},e.prototype.toExtendedJSON=function(t){return t&&t.relaxed?this.toNumber():{$numberLong:this.toString()}},e.fromExtendedJSON=function(t,r){var n=e.fromString(t.$numberLong);return r&&r.relaxed?n.toNumber():n},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return'new Long("'.concat(this.toString(),'"').concat(this.unsigned?", true":"",")")},e.TWO_PWR_24=e.fromInt(nee),e.MAX_UNSIGNED_VALUE=e.fromBits(-1,-1,!0),e.ZERO=e.fromInt(0),e.UZERO=e.fromInt(0,!0),e.ONE=e.fromInt(1),e.UONE=e.fromInt(1,!0),e.NEG_ONE=e.fromInt(-1),e.MAX_VALUE=e.fromBits(-1,2147483647,!1),e.MIN_VALUE=e.fromBits(0,-2147483648,!1),e}();sd.Long=qv;Object.defineProperty(qv.prototype,"__isLong__",{value:!0});Object.defineProperty(qv.prototype,"_bsontype",{value:"Long"})});var ad=w(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});od.Decimal128=void 0;var Fo=require("buffer"),zo=br(),pe=ds(),iee=Ur(),see=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,oee=/^(\+|-)?(Infinity|inf)$/i,aee=/^(\+|-)?NaN$/i,Vu=6111,Dv=-6176,iq=6176,uee=34,Pv=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),sq=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),oq=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),cee=/^([-+])?(\d+)?$/,fee=31,aq=16383,lee=30,hee=31;function uq(e){return!isNaN(parseInt(e,10))}o(uq,"isDigit");function dee(e){var t=pe.Long.fromNumber(1e9),r=pe.Long.fromNumber(0);if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3])return{quotient:e,rem:r};for(var n=0;n<=3;n++)r=r.shiftLeft(32),r=r.add(new pe.Long(e.parts[n],0)),e.parts[n]=r.div(t).low,r=r.modulo(t);return{quotient:e,rem:r}}o(dee,"divideu128");function pee(e,t){if(!e&&!t)return{high:pe.Long.fromNumber(0),low:pe.Long.fromNumber(0)};var r=e.shiftRightUnsigned(32),n=new pe.Long(e.getLowBits(),0),i=t.shiftRightUnsigned(32),s=new pe.Long(t.getLowBits(),0),a=r.multiply(i),u=r.multiply(s),c=n.multiply(i),f=n.multiply(s);return a=a.add(u.shiftRightUnsigned(32)),u=new pe.Long(u.getLowBits(),0).add(c).add(f.shiftRightUnsigned(32)),a=a.add(u.shiftRightUnsigned(32)),f=u.shiftLeft(32).add(new pe.Long(f.getLowBits(),0)),{high:a,low:f}}o(pee,"multiply64x2");function mee(e,t){var r=e.high>>>0,n=t.high>>>0;if(r>>0,s=t.low>>>0;if(i=7e3)throw new zo.BSONTypeError(""+t+" not a valid Decimal128 string");var P=t.match(see),q=t.match(oee),H=t.match(aee);if(!P&&!q&&!H||t.length===0)throw new zo.BSONTypeError(""+t+" not a valid Decimal128 string");if(P){var ue=P[2],j=P[4],te=P[5],K=P[6];j&&K===void 0&&$o(t,"missing exponent power"),j&&ue===void 0&&$o(t,"missing exponent base"),j===void 0&&(te||K)&&$o(t,"missing e before exponent")}if((t[N]==="+"||t[N]==="-")&&(r=t[N++]==="-"),!uq(t[N])&&t[N]!=="."){if(t[N]==="i"||t[N]==="I")return new e(Fo.Buffer.from(r?sq:oq));if(t[N]==="N")return new e(Fo.Buffer.from(Pv))}for(;uq(t[N])||t[N]===".";){if(t[N]==="."){n&&$o(t,"contains multiple periods"),n=!0,N=N+1;continue}l<34&&(t[N]!=="0"||i)&&(i||(f=a),i=!0,h[d++]=parseInt(t[N],10),l=l+1),i&&(u=u+1),n&&(c=c+1),a=a+1,N=N+1}if(n&&!a)throw new zo.BSONTypeError(""+t+" not a valid Decimal128 string");if(t[N]==="e"||t[N]==="E"){var W=t.substr(++N).match(cee);if(!W||!W[2])return new e(Fo.Buffer.from(Pv));E=parseInt(W[0],10),N=N+W[0].length}if(t[N])return new e(Fo.Buffer.from(Pv));if(m=0,!l)m=0,S=0,h[0]=0,u=1,l=1,s=0;else if(S=l-1,s=u,s!==1)for(;h[f+s-1]===0;)s=s-1;for(E<=c&&c-E>16384?E=Dv:E=E-c;E>Vu;){if(S=S+1,S-m>uee){var z=h.join("");if(z.match(/^0+$/)){E=Vu;break}$o(t,"overflow")}E=E-1}for(;E=5&&(ee=1,fe===5)){for(ee=h[S]%2===1?1:0,O=f+S+2;O=0;Q--)if(++h[Q]>9&&(h[Q]=0,Q===0))if(E>8&255,de[N++]=he.low.low>>16&255,de[N++]=he.low.low>>24&255,de[N++]=he.low.high&255,de[N++]=he.low.high>>8&255,de[N++]=he.low.high>>16&255,de[N++]=he.low.high>>24&255,de[N++]=he.high.low&255,de[N++]=he.high.low>>8&255,de[N++]=he.high.low>>16&255,de[N++]=he.high.low>>24&255,de[N++]=he.high.high&255,de[N++]=he.high.high>>8&255,de[N++]=he.high.high>>16&255,de[N++]=he.high.high>>24&255,new e(de)},e.prototype.toString=function(){for(var t,r=0,n=new Array(36),i=0;i>26&fee;if(R>>3===3){if(R===lee)return l.join("")+"Infinity";if(R===hee)return"NaN";t=O>>15&aq,u=8+(O>>14&1)}else u=O>>14&7,t=O>>17&aq;var _=t-iq;if(c.parts[0]=(O&16383)+((u&15)<<14),c.parts[1]=E,c.parts[2]=S,c.parts[3]=m,c.parts[0]===0&&c.parts[1]===0&&c.parts[2]===0&&c.parts[3]===0)a=!0;else for(h=3;h>=0;h--){var N=0,P=dee(c);if(c=P.quotient,N=P.rem.low,!!N)for(f=8;f>=0;f--)n[h*9+f]=N%10,N=Math.floor(N/10)}if(a)r=1,n[s]=0;else for(r=36;!n[s];)r=r-1,s=s+1;var q=r-1+_;if(q>=34||q<=-7||_>0){if(r>34)return l.push("".concat(0)),_>0?l.push("E+".concat(_)):_<0&&l.push("E".concat(_)),l.join("");l.push("".concat(n[s++])),r=r-1,r&&l.push(".");for(var i=0;i0?l.push("+".concat(q)):l.push("".concat(q))}else if(_>=0)for(var i=0;i0)for(var i=0;i{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.Double=void 0;var fq=function(){function e(t){if(!(this instanceof e))return new e(t);t instanceof Number&&(t=t.valueOf()),this.value=+t}return o(e,"Double"),e.prototype.valueOf=function(){return this.value},e.prototype.toJSON=function(){return this.value},e.prototype.toString=function(t){return this.value.toString(t)},e.prototype.toExtendedJSON=function(t){return t&&(t.legacy||t.relaxed&&isFinite(this.value))?this.value:Object.is(Math.sign(this.value),-0)?{$numberDouble:"-".concat(this.value.toFixed(1))}:{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}},e.fromExtendedJSON=function(t,r){var n=parseFloat(t.$numberDouble);return r&&r.relaxed?n:new e(n)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){var t=this.toExtendedJSON();return"new Double(".concat(t.$numberDouble,")")},e}();ud.Double=fq;Object.defineProperty(fq.prototype,"_bsontype",{value:"Double"})});var ld=w(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});fd.Int32=void 0;var lq=function(){function e(t){if(!(this instanceof e))return new e(t);t instanceof Number&&(t=t.valueOf()),this.value=+t|0}return o(e,"Int32"),e.prototype.valueOf=function(){return this.value},e.prototype.toString=function(t){return this.value.toString(t)},e.prototype.toJSON=function(){return this.value},e.prototype.toExtendedJSON=function(t){return t&&(t.relaxed||t.legacy)?this.value:{$numberInt:this.value.toString()}},e.fromExtendedJSON=function(t,r){return r&&r.relaxed?parseInt(t.$numberInt,10):new e(t.$numberInt)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return"new Int32(".concat(this.valueOf(),")")},e}();fd.Int32=lq;Object.defineProperty(lq.prototype,"_bsontype",{value:"Int32"})});var dd=w(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.MaxKey=void 0;var hq=function(){function e(){if(!(this instanceof e))return new e}return o(e,"MaxKey"),e.prototype.toExtendedJSON=function(){return{$maxKey:1}},e.fromExtendedJSON=function(){return new e},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return"new MaxKey()"},e}();hd.MaxKey=hq;Object.defineProperty(hq.prototype,"_bsontype",{value:"MaxKey"})});var md=w(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.MinKey=void 0;var dq=function(){function e(){if(!(this instanceof e))return new e}return o(e,"MinKey"),e.prototype.toExtendedJSON=function(){return{$minKey:1}},e.fromExtendedJSON=function(){return new e},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return"new MinKey()"},e}();pd.MinKey=dq;Object.defineProperty(dq.prototype,"_bsontype",{value:"MinKey"})});var gd=w(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});yd.ObjectId=void 0;var qn=require("buffer"),yee=$u(),Hu=br(),Vo=Ur(),gee=new RegExp("^[0-9a-fA-F]{24}$"),ps=null,tn=Symbol("id"),rn=function(){function e(t){if(!(this instanceof e))return new e(t);var r;if(typeof t=="object"&&t&&"id"in t){if(typeof t.id!="string"&&!ArrayBuffer.isView(t.id))throw new Hu.BSONTypeError("Argument passed in must have an id that is of type string or Buffer");"toHexString"in t&&typeof t.toHexString=="function"?r=qn.Buffer.from(t.toHexString(),"hex"):r=t.id}else r=t;if(r==null||typeof r=="number")this[tn]=e.generate(typeof r=="number"?r:void 0);else if(ArrayBuffer.isView(r)&&r.byteLength===12)this[tn]=r instanceof qn.Buffer?r:(0,yee.ensureBuffer)(r);else if(typeof r=="string")if(r.length===12){var n=qn.Buffer.from(r);if(n.byteLength===12)this[tn]=n;else throw new Hu.BSONTypeError("Argument passed in must be a string of 12 bytes")}else if(r.length===24&&gee.test(r))this[tn]=qn.Buffer.from(r,"hex");else throw new Hu.BSONTypeError("Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer");else throw new Hu.BSONTypeError("Argument passed in does not match the accepted types");e.cacheHexString&&(this.__id=this.id.toString("hex"))}return o(e,"ObjectId"),Object.defineProperty(e.prototype,"id",{get:function(){return this[tn]},set:function(t){this[tn]=t,e.cacheHexString&&(this.__id=t.toString("hex"))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"generationTime",{get:function(){return this.id.readInt32BE(0)},set:function(t){this.id.writeUInt32BE(t,0)},enumerable:!1,configurable:!0}),e.prototype.toHexString=function(){if(e.cacheHexString&&this.__id)return this.__id;var t=this.id.toString("hex");return e.cacheHexString&&!this.__id&&(this.__id=t),t},e.getInc=function(){return e.index=(e.index+1)%16777215},e.generate=function(t){typeof t!="number"&&(t=Math.floor(Date.now()/1e3));var r=e.getInc(),n=qn.Buffer.alloc(12);return n.writeUInt32BE(t,0),ps===null&&(ps=(0,Vo.randomBytes)(5)),n[4]=ps[0],n[5]=ps[1],n[6]=ps[2],n[7]=ps[3],n[8]=ps[4],n[11]=r&255,n[10]=r>>8&255,n[9]=r>>16&255,n},e.prototype.toString=function(t){return t?this.id.toString(t):this.toHexString()},e.prototype.toJSON=function(){return this.toHexString()},e.prototype.equals=function(t){if(t==null)return!1;if(t instanceof e)return this[tn][11]===t[tn][11]&&this[tn].equals(t[tn]);if(typeof t=="string"&&e.isValid(t)&&t.length===12&&(0,Vo.isUint8Array)(this.id))return t===qn.Buffer.prototype.toString.call(this.id,"latin1");if(typeof t=="string"&&e.isValid(t)&&t.length===24)return t.toLowerCase()===this.toHexString();if(typeof t=="string"&&e.isValid(t)&&t.length===12)return qn.Buffer.from(t).equals(this.id);if(typeof t=="object"&&"toHexString"in t&&typeof t.toHexString=="function"){var r=t.toHexString(),n=this.toHexString().toLowerCase();return typeof r=="string"&&r.toLowerCase()===n}return!1},e.prototype.getTimestamp=function(){var t=new Date,r=this.id.readUInt32BE(0);return t.setTime(Math.floor(r)*1e3),t},e.createPk=function(){return new e},e.createFromTime=function(t){var r=qn.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0]);return r.writeUInt32BE(t,0),new e(r)},e.createFromHexString=function(t){if(typeof t>"u"||t!=null&&t.length!==24)throw new Hu.BSONTypeError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");return new e(qn.Buffer.from(t,"hex"))},e.isValid=function(t){if(t==null)return!1;try{return new e(t),!0}catch{return!1}},e.prototype.toExtendedJSON=function(){return this.toHexString?{$oid:this.toHexString()}:{$oid:this.toString("hex")}},e.fromExtendedJSON=function(t){return new e(t.$oid)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e.prototype.inspect=function(){return'new ObjectId("'.concat(this.toHexString(),'")')},e.index=Math.floor(Math.random()*16777215),e}();yd.ObjectId=rn;Object.defineProperty(rn.prototype,"generate",{value:(0,Vo.deprecate)(function(e){return rn.generate(e)},"Please use the static `ObjectId.generate(time)` instead")});Object.defineProperty(rn.prototype,"getInc",{value:(0,Vo.deprecate)(function(){return rn.getInc()},"Please use the static `ObjectId.getInc()` instead")});Object.defineProperty(rn.prototype,"get_inc",{value:(0,Vo.deprecate)(function(){return rn.getInc()},"Please use the static `ObjectId.getInc()` instead")});Object.defineProperty(rn,"get_inc",{value:(0,Vo.deprecate)(function(){return rn.getInc()},"Please use the static `ObjectId.getInc()` instead")});Object.defineProperty(rn.prototype,"_bsontype",{value:"ObjectID"})});var Od=w(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.BSONRegExp=void 0;var Sd=br();function See(e){return e.split("").sort().join("")}o(See,"alphabetize");var pq=function(){function e(t,r){if(!(this instanceof e))return new e(t,r);if(this.pattern=t,this.options=See(r??""),this.pattern.indexOf("\0")!==-1)throw new Sd.BSONError("BSON Regex patterns cannot contain null bytes, found: ".concat(JSON.stringify(this.pattern)));if(this.options.indexOf("\0")!==-1)throw new Sd.BSONError("BSON Regex options cannot contain null bytes, found: ".concat(JSON.stringify(this.options)));for(var n=0;n{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});vd.BSONSymbol=void 0;var mq=function(){function e(t){if(!(this instanceof e))return new e(t);this.value=t}return o(e,"BSONSymbol"),e.prototype.valueOf=function(){return this.value},e.prototype.toString=function(){return this.value},e.prototype.inspect=function(){return'new BSONSymbol("'.concat(this.value,'")')},e.prototype.toJSON=function(){return this.value},e.prototype.toExtendedJSON=function(){return{$symbol:this.value}},e.fromExtendedJSON=function(t){return new e(t.$symbol)},e.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},e}();vd.BSONSymbol=mq;Object.defineProperty(mq.prototype,"_bsontype",{value:"Symbol"})});var ku=w(Dn=>{"use strict";var wee=Dn&&Dn.__extends||function(){var e=o(function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},e(t,r)},"extendStatics");return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}o(n,"__"),t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(Dn,"__esModule",{value:!0});Dn.Timestamp=Dn.LongWithoutOverridesClass=void 0;var Ho=ds(),Oee=Ur();Dn.LongWithoutOverridesClass=Ho.Long;var vee=function(e){wee(t,e);function t(r,n){var i=this;return i instanceof t?(Ho.Long.isLong(r)?i=e.call(this,r.low,r.high,!0)||this:(0,Oee.isObjectLike)(r)&&typeof r.t<"u"&&typeof r.i<"u"?i=e.call(this,r.i,r.t,!0)||this:i=e.call(this,r,n,!0)||this,Object.defineProperty(i,"_bsontype",{value:"Timestamp",writable:!1,configurable:!1,enumerable:!1}),i):new t(r,n)}return o(t,"Timestamp"),t.prototype.toJSON=function(){return{$timestamp:this.toString()}},t.fromInt=function(r){return new t(Ho.Long.fromInt(r,!0))},t.fromNumber=function(r){return new t(Ho.Long.fromNumber(r,!0))},t.fromBits=function(r,n){return new t(r,n)},t.fromString=function(r,n){return new t(Ho.Long.fromString(r,!0,n))},t.prototype.toExtendedJSON=function(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}},t.fromExtendedJSON=function(r){return new t(r.$timestamp)},t.prototype[Symbol.for("nodejs.util.inspect.custom")]=function(){return this.inspect()},t.prototype.inspect=function(){return"new Timestamp({ t: ".concat(this.getHighBits(),", i: ").concat(this.getLowBits()," })")},t.MAX_VALUE=Ho.Long.MAX_UNSIGNED_VALUE,t}(Dn.LongWithoutOverridesClass);Dn.Timestamp=vee});var Nd=w(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.EJSON=ms.isBSONType=void 0;var Lv=jo(),Wv=nd(),Yu=id(),gq=ad(),Fv=cd(),Gu=br(),$v=ld(),_d=ds(),Sq=dd(),wq=md(),jv=gd(),Uv=Ur(),Td=Od(),Oq=Ed(),vq=ku();function Eq(e){return(0,Uv.isObjectLike)(e)&&Reflect.has(e,"_bsontype")&&typeof e._bsontype=="string"}o(Eq,"isBSONType");ms.isBSONType=Eq;var _q=2147483647,Tq=-2147483648,Nq=9223372036854776e3,bq=-9223372036854776e3,Eee={$oid:jv.ObjectId,$binary:Lv.Binary,$uuid:Lv.Binary,$symbol:Oq.BSONSymbol,$numberInt:$v.Int32,$numberDecimal:gq.Decimal128,$numberDouble:Fv.Double,$numberLong:_d.Long,$minKey:wq.MinKey,$maxKey:Sq.MaxKey,$regex:Td.BSONRegExp,$regularExpression:Td.BSONRegExp,$timestamp:vq.Timestamp};function Cq(e,t){if(t===void 0&&(t={}),typeof e=="number"){if(t.relaxed||t.legacy)return e;if(Math.floor(e)===e){if(e>=Tq&&e<=_q)return new $v.Int32(e);if(e>=bq&&e<=Nq)return _d.Long.fromNumber(e)}return new Fv.Double(e)}if(e==null||typeof e!="object")return e;if(e.$undefined)return null;for(var r=Object.keys(e).filter(function(l){return l.startsWith("$")&&e[l]!=null}),n=0;n ")}).join(""),s=n[r],a=" -> "+n.slice(r+1,n.length-1).map(function(T){return"".concat(T," -> ")}).join(""),u=n[n.length-1],c=" ".repeat(i.length+s.length/2),f="-".repeat(a.length+(s.length+u.length)/2-1);throw new Gu.BSONTypeError(`Converting circular structure to EJSON: +`+" ".concat(i).concat(s).concat(a).concat(u,` +`)+" ".concat(c,"\\").concat(f,"/"))}t.seenObjects[t.seenObjects.length-1].obj=e}if(Array.isArray(e))return _ee(e,t);if(e===void 0)return null;if(e instanceof Date||(0,Uv.isDate)(e)){var h=e.getTime(),l=h>-1&&h<2534023188e5;return t.legacy?t.relaxed&&l?{$date:e.getTime()}:{$date:yq(e)}:t.relaxed&&l?{$date:yq(e)}:{$date:{$numberLong:e.getTime().toString()}}}if(typeof e=="number"&&(!t.relaxed||!isFinite(e))){if(Math.floor(e)===e){var d=e>=Tq&&e<=_q,m=e>=bq&&e<=Nq;if(d)return{$numberInt:e.toString()};if(m)return{$numberLong:e.toString()}}return{$numberDouble:e.toString()}}if(e instanceof RegExp||(0,Uv.isRegExp)(e)){var S=e.flags;if(S===void 0){var E=e.toString().match(/[gimuy]*$/);E&&(S=E[0])}var O=new Td.BSONRegExp(e.source,S);return O.toExtendedJSON(t)}return e!=null&&typeof e=="object"?Nee(e,t):e}o(vi,"serializeValue");var Tee={Binary:function(e){return new Lv.Binary(e.value(),e.sub_type)},Code:function(e){return new Wv.Code(e.code,e.scope)},DBRef:function(e){return new Yu.DBRef(e.collection||e.namespace,e.oid,e.db,e.fields)},Decimal128:function(e){return new gq.Decimal128(e.bytes)},Double:function(e){return new Fv.Double(e.value)},Int32:function(e){return new $v.Int32(e.value)},Long:function(e){return _d.Long.fromBits(e.low!=null?e.low:e.low_,e.low!=null?e.high:e.high_,e.low!=null?e.unsigned:e.unsigned_)},MaxKey:function(){return new Sq.MaxKey},MinKey:function(){return new wq.MinKey},ObjectID:function(e){return new jv.ObjectId(e)},ObjectId:function(e){return new jv.ObjectId(e)},BSONRegExp:function(e){return new Td.BSONRegExp(e.pattern,e.options)},Symbol:function(e){return new Oq.BSONSymbol(e.value)},Timestamp:function(e){return vq.Timestamp.fromBits(e.low,e.high)}};function Nee(e,t){if(e==null||typeof e!="object")throw new Gu.BSONError("not an object instance");var r=e._bsontype;if(typeof r>"u"){var n={};for(var i in e){t.seenObjects.push({propertyName:i,obj:null});try{var s=vi(e[i],t);i==="__proto__"?Object.defineProperty(n,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[i]=s}finally{t.seenObjects.pop()}}return n}else if(Eq(e)){var a=e;if(typeof a.toExtendedJSON!="function"){var u=Tee[e._bsontype];if(!u)throw new Gu.BSONTypeError("Unrecognized or invalid _bsontype: "+e._bsontype);a=u(a)}return r==="Code"&&a.scope?a=new Wv.Code(a.code,vi(a.scope,t)):r==="DBRef"&&a.oid&&(a=new Yu.DBRef(vi(a.collection,t),vi(a.oid,t),vi(a.db,t),vi(a.fields,t))),a.toExtendedJSON(t)}else throw new Gu.BSONError("_bsontype must be a string, but was: "+typeof r)}o(Nee,"serializeDocument");var bee;(function(e){function t(s,a){var u=Object.assign({},{relaxed:!0,legacy:!1},a);return typeof u.relaxed=="boolean"&&(u.strict=!u.relaxed),typeof u.strict=="boolean"&&(u.relaxed=!u.strict),JSON.parse(s,function(c,f){if(c.indexOf("\0")!==-1)throw new Gu.BSONError("BSON Document field names cannot contain null bytes, found: ".concat(JSON.stringify(c)));return Cq(f,u)})}o(t,"parse"),e.parse=t;function r(s,a,u,c){u!=null&&typeof u=="object"&&(c=u,u=0),a!=null&&typeof a=="object"&&!Array.isArray(a)&&(c=a,a=void 0,u=0);var f=Object.assign({relaxed:!0,legacy:!1},c,{seenObjects:[{propertyName:"(root)",obj:null}]}),h=vi(s,f);return JSON.stringify(h,a,u)}o(r,"stringify"),e.stringify=r;function n(s,a){return a=a||{},JSON.parse(r(s,a))}o(n,"serialize"),e.serialize=n;function i(s,a){return a=a||{},t(JSON.stringify(s),a)}o(i,"deserialize"),e.deserialize=i})(bee=ms.EJSON||(ms.EJSON={}))});var Vv=w(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.Map=void 0;var Cee=Iv(),zv;ko.Map=zv;var Aq=(0,Cee.getGlobal)();Aq.Map?ko.Map=zv=Aq.Map:ko.Map=zv=function(){function e(t){t===void 0&&(t=[]),this._keys=[],this._values={};for(var r=0;r{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.calculateObjectSize=void 0;var Ie=require("buffer"),Aee=jo(),bd=Po(),Yo=Ur();function Ku(e,t,r){var n=5;if(Array.isArray(e))for(var i=0;i=bd.JS_INT_MIN&&t<=bd.JS_INT_MAX&&t>=bd.BSON_INT32_MIN&&t<=bd.BSON_INT32_MAX?(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(4+1):(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(8+1);case"undefined":return n||!i?(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t._bsontype==="MinKey"||t._bsontype==="MaxKey")return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1;if(t._bsontype==="ObjectId"||t._bsontype==="ObjectID")return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(12+1);if(t instanceof Date||(0,Yo.isDate)(t))return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||(0,Yo.isAnyArrayBuffer)(t))return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.byteLength;if(t._bsontype==="Long"||t._bsontype==="Double"||t._bsontype==="Timestamp")return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(8+1);if(t._bsontype==="Decimal128")return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(16+1);if(t._bsontype==="Code")return t.scope!=null&&Object.keys(t.scope).length>0?(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Ie.Buffer.byteLength(t.code.toString(),"utf8")+1+Ku(t.scope,r,i):(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+4+Ie.Buffer.byteLength(t.code.toString(),"utf8")+1;if(t._bsontype==="Binary"){var s=t;return s.sub_type===Aee.Binary.SUBTYPE_BYTE_ARRAY?(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(s.position+1+4+1+4):(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+(s.position+1+4+1)}else{if(t._bsontype==="Symbol")return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+Ie.Buffer.byteLength(t.value,"utf8")+4+1+1;if(t._bsontype==="DBRef"){var a=Object.assign({$ref:t.collection,$id:t.oid},t.fields);return t.db!=null&&(a.$db=t.db),(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+Ku(a,r,i)}else return t instanceof RegExp||(0,Yo.isRegExp)(t)?(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+Ie.Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t._bsontype==="BSONRegExp"?(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+Ie.Buffer.byteLength(t.pattern,"utf8")+1+Ie.Buffer.byteLength(t.options,"utf8")+1:(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+Ku(t,r,i)+1}case"function":if(t instanceof RegExp||(0,Yo.isRegExp)(t)||String.call(t)==="[object RegExp]")return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+Ie.Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(r&&t.scope!=null&&Object.keys(t.scope).length>0)return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Ie.Buffer.byteLength((0,Yo.normalizedFunctionString)(t),"utf8")+1+Ku(t.scope,r,i);if(r)return(e!=null?Ie.Buffer.byteLength(e,"utf8")+1:0)+1+4+Ie.Buffer.byteLength((0,Yo.normalizedFunctionString)(t),"utf8")+1}return 0}o(Iq,"calculateElement")});var Rq=w(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});Ad.validateUtf8=void 0;var Iee=128,Bee=192,Ree=224,Mee=240,xee=248,qee=192,Dee=224,Pee=240,Lee=128;function jee(e,t,r){for(var n=0,i=t;i{"use strict";var Go=Ko&&Ko.__assign||function(){return Go=Object.assign||function(e){for(var t,r=1,n=arguments.length;r= 5, is ".concat(i));if(t.allowObjectSmallerThanBufferSize&&e.length= bson size ").concat(i));if(!t.allowObjectSmallerThanBufferSize&&e.length!==i)throw new ye.BSONError("buffer length ".concat(e.length," must === bson size ").concat(i));if(i+n>e.byteLength)throw new ye.BSONError("(bson size ".concat(i," + options.index ").concat(n," must be <= buffer length ").concat(e.byteLength,")"));if(e[n+i-1]!==0)throw new ye.BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return Md(e,n,t,r)}o(Kee,"deserialize");Ko.deserialize=Kee;var Xee=/^\$ref$|^\$id$|^\$db$/;function Md(e,t,r,n){n===void 0&&(n=!1);var i=r.evalFunctions==null?!1:r.evalFunctions,s=r.cacheFunctions==null?!1:r.cacheFunctions,a=r.fieldsAsRaw==null?null:r.fieldsAsRaw,u=r.raw==null?!1:r.raw,c=typeof r.bsonRegExp=="boolean"?r.bsonRegExp:!1,f=r.promoteBuffers==null?!1:r.promoteBuffers,h=r.promoteLongs==null?!0:r.promoteLongs,l=r.promoteValues==null?!0:r.promoteValues,d=r.validation==null?{utf8:!0}:r.validation,m=!0,S,E=new Set,O=d.utf8;if(typeof O=="boolean")S=O;else{m=!1;var T=Object.keys(O).map(function(ea){return O[ea]});if(T.length===0)throw new ye.BSONError("UTF-8 validation setting cannot be empty");if(typeof T[0]!="boolean")throw new ye.BSONError("Invalid UTF-8 validation option, must specify boolean values");if(S=T[0],!T.every(function(ea){return ea===S}))throw new ye.BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}if(!m)for(var R=0,_=Object.keys(O);R<_.length;R++){var N=_[R];E.add(N)}var P=t;if(e.length<5)throw new ye.BSONError("corrupt bson message < 5 bytes long");var q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(q<5||q>e.length)throw new ye.BSONError("corrupt bson message");for(var H=n?[]:{},ue=0,j=!1,te=n?!1:null,K=new DataView(e.buffer,e.byteOffset,e.byteLength);!j;){var W=e[t++];if(W===0)break;for(var z=t;e[z]!==0&&z=e.byteLength)throw new ye.BSONError("Bad BSON Document: illegal CString");var Y=n?ue++:e.toString("utf8",t,z),fe=!0;m||E.has(Y)?fe=S:fe=!S,te!==!1&&Y[0]==="$"&&(te=Xee.test(Y));var ee=void 0;if(t=z+1,W===$e.BSON_DATA_STRING){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new ye.BSONError("bad string length in bson");ee=Rd(e,t,t+Q-1,fe),t=t+Q}else if(W===$e.BSON_DATA_OID){var Ne=Id.Buffer.alloc(12);e.copy(Ne,0,t,t+12),ee=new xq.ObjectId(Ne),t=t+12}else if(W===$e.BSON_DATA_INT&&l===!1)ee=new Fee.Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(W===$e.BSON_DATA_INT)ee=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(W===$e.BSON_DATA_NUMBER&&l===!1)ee=new Wee.Double(K.getFloat64(t,!0)),t=t+8;else if(W===$e.BSON_DATA_NUMBER)ee=K.getFloat64(t,!0),t=t+8;else if(W===$e.BSON_DATA_DATE){var he=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,de=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;ee=new Date(new xd.Long(he,de).toNumber())}else if(W===$e.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new ye.BSONError("illegal boolean type value");ee=e[t++]===1}else if(W===$e.BSON_DATA_OBJECT){var Ar=t,ft=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(ft<=0||ft>e.length-t)throw new ye.BSONError("bad embedded document length in bson");if(u)ee=e.slice(t,t+ft);else{var Ir=r;m||(Ir=Go(Go({},r),{validation:{utf8:fe}})),ee=Md(e,Ar,Ir,!1)}t=t+ft}else if(W===$e.BSON_DATA_ARRAY){var Ar=t,ft=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,tr=r,Ye=t+ft;if(a&&a[Y]){tr={};for(var jn in r)tr[jn]=r[jn];tr.raw=!0}if(m||(tr=Go(Go({},tr),{validation:{utf8:fe}})),ee=Md(e,Ar,tr,!0),t=t+ft,e[t-1]!==0)throw new ye.BSONError("invalid array terminator byte");if(t!==Ye)throw new ye.BSONError("corrupted array bson")}else if(W===$e.BSON_DATA_UNDEFINED)ee=void 0;else if(W===$e.BSON_DATA_NULL)ee=null;else if(W===$e.BSON_DATA_LONG){var he=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,de=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,rr=new xd.Long(he,de);h&&l===!0?ee=rr.lessThanOrEqual(Yee)&&rr.greaterThanOrEqual(Gee)?rr.toNumber():rr:ee=rr}else if(W===$e.BSON_DATA_DECIMAL128){var Un=Id.Buffer.alloc(16);e.copy(Un,0,t,t+16),t=t+16;var nr=new Uee.Decimal128(Un);"toObject"in nr&&typeof nr.toObject=="function"?ee=nr.toObject():ee=nr}else if(W===$e.BSON_DATA_BINARY){var Ue=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,Br=Ue,Rr=e[t++];if(Ue<0)throw new ye.BSONError("Negative binary type element size found");if(Ue>e.byteLength)throw new ye.BSONError("Binary type size larger than document size");if(e.slice!=null){if(Rr===Xu.Binary.SUBTYPE_BYTE_ARRAY){if(Ue=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,Ue<0)throw new ye.BSONError("Negative binary type element size found for subtype 0x02");if(Ue>Br-4)throw new ye.BSONError("Binary type with subtype 0x02 contains too long binary size");if(UeBr-4)throw new ye.BSONError("Binary type with subtype 0x02 contains too long binary size");if(Ue=e.length)throw new ye.BSONError("Bad BSON Document: illegal CString");var Xo=e.toString("utf8",t,z);for(t=z+1,z=t;e[z]!==0&&z=e.length)throw new ye.BSONError("Bad BSON Document: illegal CString");var _i=e.toString("utf8",t,z);t=z+1;var Ss=new Array(_i.length);for(z=0;z<_i.length;z++)switch(_i[z]){case"m":Ss[z]="m";break;case"s":Ss[z]="g";break;case"i":Ss[z]="i";break}ee=new RegExp(Xo,Ss.join(""))}else if(W===$e.BSON_DATA_REGEXP&&c===!0){for(z=t;e[z]!==0&&z=e.length)throw new ye.BSONError("Bad BSON Document: illegal CString");var Xo=e.toString("utf8",t,z);for(t=z+1,z=t;e[z]!==0&&z=e.length)throw new ye.BSONError("Bad BSON Document: illegal CString");var _i=e.toString("utf8",t,z);t=z+1,ee=new Vee.BSONRegExp(Xo,_i)}else if(W===$e.BSON_DATA_SYMBOL){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new ye.BSONError("bad string length in bson");var ec=Rd(e,t,t+Q-1,fe);ee=l?ec:new Hee.BSONSymbol(ec),t=t+Q}else if(W===$e.BSON_DATA_TIMESTAMP){var he=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,de=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;ee=new kee.Timestamp(he,de)}else if(W===$e.BSON_DATA_MIN_KEY)ee=new zee.MinKey;else if(W===$e.BSON_DATA_MAX_KEY)ee=new $ee.MaxKey;else if(W===$e.BSON_DATA_CODE){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new ye.BSONError("bad string length in bson");var Wr=Rd(e,t,t+Q-1,fe);i?s?ee=Bd(Wr,qq,H):ee=Bd(Wr):ee=new Mq.Code(Wr),t=t+Q}else if(W===$e.BSON_DATA_CODE_W_SCOPE){var Ti=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Ti<4+4+4+1)throw new ye.BSONError("code_w_scope total size shorter minimum expected length");var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new ye.BSONError("bad string length in bson");var Wr=Rd(e,t,t+Q-1,fe);t=t+Q;var Ar=t,ft=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,Jo=Md(e,Ar,r,!1);if(t=t+ft,Ti<4+4+ft+Q)throw new ye.BSONError("code_w_scope total size is too short, truncating scope");if(Ti>4+4+ft+Q)throw new ye.BSONError("code_w_scope total size is too long, clips outer document");i?(s?ee=Bd(Wr,qq,H):ee=Bd(Wr),ee.scope=Jo):ee=new Mq.Code(Wr,Jo)}else if(W===$e.BSON_DATA_DBPOINTER){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new ye.BSONError("bad string length in bson");if(d!=null&&d.utf8&&!(0,Dq.validateUtf8)(e,t,t+Q-1))throw new ye.BSONError("Invalid UTF-8 string in BSON document");var Zo=e.toString("utf8",t,t+Q-1);t=t+Q;var Qo=Id.Buffer.alloc(12);e.copy(Qo,0,t,t+12);var Ne=new xq.ObjectId(Qo);t=t+12,ee=new Hv.DBRef(Zo,Ne)}else throw new ye.BSONError("Detected unknown BSON type ".concat(W.toString(16),' for fieldname "').concat(Y,'"'));Y==="__proto__"?Object.defineProperty(H,Y,{value:ee,writable:!0,enumerable:!0,configurable:!0}):H[Y]=ee}if(q!==t-P)throw n?new ye.BSONError("corrupt array bson"):new ye.BSONError("corrupt object bson");if(!te)return H;if((0,Hv.isDBRefLike)(H)){var Ni=Object.assign({},H);return delete Ni.$ref,delete Ni.$id,delete Ni.$db,new Hv.DBRef(H.$ref,H.$id,H.$db,Ni)}return H}o(Md,"deserializeObject");function Bd(e,t,r){return t?(t[e]==null&&(t[e]=new Function(e)),t[e].bind(r)):new Function(e)}o(Bd,"isolateEval");function Rd(e,t,r,n){var i=e.toString("utf8",t,r);if(n){for(var s=0;s{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.serializeInto=void 0;var Lq=jo(),je=Po(),Jee=$u(),Pn=br(),Zee=Nd(),Qee=ds(),ete=Vv(),er=Ur(),qd=/\x00/,jq=new Set(["$db","$ref","$id","$clusterTime"]);function kv(e,t,r,n,i){e[n++]=je.BSON_DATA_STRING;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+s+1,e[n-1]=0;var a=e.write(r,n+4,void 0,"utf8");return e[n+3]=a+1>>24&255,e[n+2]=a+1>>16&255,e[n+1]=a+1>>8&255,e[n]=a+1&255,n=n+4+a,e[n++]=0,n}o(kv,"serializeString");var Zu=new Uint8Array(8),Uq=new DataView(Zu.buffer,Zu.byteOffset,Zu.byteLength);function Yv(e,t,r,n,i){if(Number.isInteger(r)&&r>=je.BSON_INT32_MIN&&r<=je.BSON_INT32_MAX){e[n++]=je.BSON_DATA_INT;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+s,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255}else{e[n++]=je.BSON_DATA_NUMBER;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+s,e[n++]=0,Uq.setFloat64(0,r,!0),e.set(Zu,n),n=n+8}return n}o(Yv,"serializeNumber");function Ju(e,t,r,n,i){e[n++]=je.BSON_DATA_NULL;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+s,e[n++]=0,n}o(Ju,"serializeNull");function Gv(e,t,r,n,i){e[n++]=je.BSON_DATA_BOOLEAN;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+s,e[n++]=0,e[n++]=r?1:0,n}o(Gv,"serializeBoolean");function Kv(e,t,r,n,i){e[n++]=je.BSON_DATA_DATE;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+s,e[n++]=0;var a=Qee.Long.fromNumber(r.getTime()),u=a.getLowBits(),c=a.getHighBits();return e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=c&255,e[n++]=c>>8&255,e[n++]=c>>16&255,e[n++]=c>>24&255,n}o(Kv,"serializeDate");function Xv(e,t,r,n,i){e[n++]=je.BSON_DATA_REGEXP;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");if(n=n+s,e[n++]=0,r.source&&r.source.match(qd)!=null)throw Error("value "+r.source+" must not contain null bytes");return n=n+e.write(r.source,n,void 0,"utf8"),e[n++]=0,r.ignoreCase&&(e[n++]=105),r.global&&(e[n++]=115),r.multiline&&(e[n++]=109),e[n++]=0,n}o(Xv,"serializeRegExp");function Jv(e,t,r,n,i){e[n++]=je.BSON_DATA_REGEXP;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");if(n=n+s,e[n++]=0,r.pattern.match(qd)!=null)throw Error("pattern "+r.pattern+" must not contain null bytes");return n=n+e.write(r.pattern,n,void 0,"utf8"),e[n++]=0,n=n+e.write(r.options.split("").sort().join(""),n,void 0,"utf8"),e[n++]=0,n}o(Jv,"serializeBSONRegExp");function Zv(e,t,r,n,i){r===null?e[n++]=je.BSON_DATA_NULL:r._bsontype==="MinKey"?e[n++]=je.BSON_DATA_MIN_KEY:e[n++]=je.BSON_DATA_MAX_KEY;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+s,e[n++]=0,n}o(Zv,"serializeMinMax");function Qv(e,t,r,n,i){e[n++]=je.BSON_DATA_OID;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");if(n=n+s,e[n++]=0,typeof r.id=="string")e.write(r.id,n,void 0,"binary");else if((0,er.isUint8Array)(r.id))e.set(r.id.subarray(0,12),n);else throw new Pn.BSONTypeError("object ["+JSON.stringify(r)+"] is not a valid ObjectId");return n+12}o(Qv,"serializeObjectId");function eE(e,t,r,n,i){e[n++]=je.BSON_DATA_BINARY;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+s,e[n++]=0;var a=r.length;return e[n++]=a&255,e[n++]=a>>8&255,e[n++]=a>>16&255,e[n++]=a>>24&255,e[n++]=je.BSON_BINARY_SUBTYPE_DEFAULT,e.set((0,Jee.ensureBuffer)(r),n),n=n+a,n}o(eE,"serializeBuffer");function tE(e,t,r,n,i,s,a,u,c,f){i===void 0&&(i=!1),s===void 0&&(s=0),a===void 0&&(a=!1),u===void 0&&(u=!0),c===void 0&&(c=!1),f===void 0&&(f=[]);for(var h=0;h>8&255,e[n++]=a>>16&255,e[n++]=a>>24&255,e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,n}o(nE,"serializeLong");function iE(e,t,r,n,i){r=r.valueOf(),e[n++]=je.BSON_DATA_INT;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+s,e[n++]=0,e[n++]=r&255,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255,n}o(iE,"serializeInt32");function sE(e,t,r,n,i){e[n++]=je.BSON_DATA_NUMBER;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");return n=n+s,e[n++]=0,Uq.setFloat64(0,r.value,!0),e.set(Zu,n),n=n+8,n}o(sE,"serializeDouble");function oE(e,t,r,n,i,s,a){i===void 0&&(i=!1),s===void 0&&(s=0),e[n++]=je.BSON_DATA_CODE;var u=a?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+u,e[n++]=0;var c=(0,er.normalizedFunctionString)(r),f=e.write(c,n+4,void 0,"utf8")+1;return e[n]=f&255,e[n+1]=f>>8&255,e[n+2]=f>>16&255,e[n+3]=f>>24&255,n=n+4+f-1,e[n++]=0,n}o(oE,"serializeFunction");function aE(e,t,r,n,i,s,a,u,c){if(i===void 0&&(i=!1),s===void 0&&(s=0),a===void 0&&(a=!1),u===void 0&&(u=!0),c===void 0&&(c=!1),r.scope&&typeof r.scope=="object"){e[n++]=je.BSON_DATA_CODE_W_SCOPE;var f=c?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+f,e[n++]=0;var h=n,l=typeof r.code=="string"?r.code:r.code.toString();n=n+4;var d=e.write(l,n+4,void 0,"utf8")+1;e[n]=d&255,e[n+1]=d>>8&255,e[n+2]=d>>16&255,e[n+3]=d>>24&255,e[n+4+d-1]=0,n=n+d+4;var m=Dd(e,r.scope,i,n,s+1,a,u);n=m-1;var S=m-h;e[h++]=S&255,e[h++]=S>>8&255,e[h++]=S>>16&255,e[h++]=S>>24&255,e[n++]=0}else{e[n++]=je.BSON_DATA_CODE;var f=c?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+f,e[n++]=0;var l=r.code.toString(),E=e.write(l,n+4,void 0,"utf8")+1;e[n]=E&255,e[n+1]=E>>8&255,e[n+2]=E>>16&255,e[n+3]=E>>24&255,n=n+4+E-1,e[n++]=0}return n}o(aE,"serializeCode");function uE(e,t,r,n,i){e[n++]=je.BSON_DATA_BINARY;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+s,e[n++]=0;var a=r.value(!0),u=r.position;return r.sub_type===Lq.Binary.SUBTYPE_BYTE_ARRAY&&(u=u+4),e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255,e[n++]=r.sub_type,r.sub_type===Lq.Binary.SUBTYPE_BYTE_ARRAY&&(u=u-4,e[n++]=u&255,e[n++]=u>>8&255,e[n++]=u>>16&255,e[n++]=u>>24&255),e.set(a,n),n=n+r.position,n}o(uE,"serializeBinary");function cE(e,t,r,n,i){e[n++]=je.BSON_DATA_SYMBOL;var s=i?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+s,e[n++]=0;var a=e.write(r.value,n+4,void 0,"utf8")+1;return e[n]=a&255,e[n+1]=a>>8&255,e[n+2]=a>>16&255,e[n+3]=a>>24&255,n=n+4+a-1,e[n++]=0,n}o(cE,"serializeSymbol");function fE(e,t,r,n,i,s,a){e[n++]=je.BSON_DATA_OBJECT;var u=a?e.write(t,n,void 0,"ascii"):e.write(t,n,void 0,"utf8");n=n+u,e[n++]=0;var c=n,f={$ref:r.collection||r.namespace,$id:r.oid};r.db!=null&&(f.$db=r.db),f=Object.assign(f,r.fields);var h=Dd(e,f,!1,n,i+1,s),l=h-c;return e[c++]=l&255,e[c++]=l>>8&255,e[c++]=l>>16&255,e[c++]=l>>24&255,h}o(fE,"serializeDBRef");function Dd(e,t,r,n,i,s,a,u){r===void 0&&(r=!1),n===void 0&&(n=0),i===void 0&&(i=0),s===void 0&&(s=!1),a===void 0&&(a=!0),u===void 0&&(u=[]),n=n||0,u=u||[],u.push(t);var c=n+4;if(Array.isArray(t))for(var f=0;f>8&255,e[n++]=O>>16&255,e[n++]=O>>24&255,c}o(Dd,"serializeInto");Pd.serializeInto=Dd});var lD=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.BSONRegExp=D.MaxKey=D.MinKey=D.Int32=D.Double=D.Timestamp=D.Long=D.UUID=D.ObjectId=D.Binary=D.DBRef=D.BSONSymbol=D.Map=D.Code=D.LongWithoutOverridesClass=D.EJSON=D.BSON_INT64_MIN=D.BSON_INT64_MAX=D.BSON_INT32_MIN=D.BSON_INT32_MAX=D.BSON_DATA_UNDEFINED=D.BSON_DATA_TIMESTAMP=D.BSON_DATA_SYMBOL=D.BSON_DATA_STRING=D.BSON_DATA_REGEXP=D.BSON_DATA_OID=D.BSON_DATA_OBJECT=D.BSON_DATA_NUMBER=D.BSON_DATA_NULL=D.BSON_DATA_MIN_KEY=D.BSON_DATA_MAX_KEY=D.BSON_DATA_LONG=D.BSON_DATA_INT=D.BSON_DATA_DECIMAL128=D.BSON_DATA_DBPOINTER=D.BSON_DATA_DATE=D.BSON_DATA_CODE_W_SCOPE=D.BSON_DATA_CODE=D.BSON_DATA_BOOLEAN=D.BSON_DATA_BINARY=D.BSON_DATA_ARRAY=D.BSON_BINARY_SUBTYPE_COLUMN=D.BSON_BINARY_SUBTYPE_ENCRYPTED=D.BSON_BINARY_SUBTYPE_UUID_NEW=D.BSON_BINARY_SUBTYPE_UUID=D.BSON_BINARY_SUBTYPE_USER_DEFINED=D.BSON_BINARY_SUBTYPE_MD5=D.BSON_BINARY_SUBTYPE_FUNCTION=D.BSON_BINARY_SUBTYPE_DEFAULT=D.BSON_BINARY_SUBTYPE_BYTE_ARRAY=void 0;D.deserializeStream=D.calculateObjectSize=D.deserialize=D.serializeWithBufferAndIndex=D.serialize=D.setInternalBufferSize=D.BSONTypeError=D.BSONError=D.ObjectID=D.Decimal128=void 0;var Qu=require("buffer"),Ld=jo();Object.defineProperty(D,"Binary",{enumerable:!0,get:function(){return Ld.Binary}});Object.defineProperty(D,"UUID",{enumerable:!0,get:function(){return Ld.UUID}});var $q=nd();Object.defineProperty(D,"Code",{enumerable:!0,get:function(){return $q.Code}});var zq=id();Object.defineProperty(D,"DBRef",{enumerable:!0,get:function(){return zq.DBRef}});var Vq=ad();Object.defineProperty(D,"Decimal128",{enumerable:!0,get:function(){return Vq.Decimal128}});var Hq=cd();Object.defineProperty(D,"Double",{enumerable:!0,get:function(){return Hq.Double}});var kq=$u(),tte=Nd(),Yq=ld();Object.defineProperty(D,"Int32",{enumerable:!0,get:function(){return Yq.Int32}});var Gq=ds();Object.defineProperty(D,"Long",{enumerable:!0,get:function(){return Gq.Long}});var Kq=Vv();Object.defineProperty(D,"Map",{enumerable:!0,get:function(){return Kq.Map}});var Xq=dd();Object.defineProperty(D,"MaxKey",{enumerable:!0,get:function(){return Xq.MaxKey}});var Jq=md();Object.defineProperty(D,"MinKey",{enumerable:!0,get:function(){return Jq.MinKey}});var jd=gd();Object.defineProperty(D,"ObjectId",{enumerable:!0,get:function(){return jd.ObjectId}});Object.defineProperty(D,"ObjectID",{enumerable:!0,get:function(){return jd.ObjectId}});var Fq=br(),rte=Bq(),Zq=Pq(),Qq=Wq(),eD=Od();Object.defineProperty(D,"BSONRegExp",{enumerable:!0,get:function(){return eD.BSONRegExp}});var tD=Ed();Object.defineProperty(D,"BSONSymbol",{enumerable:!0,get:function(){return tD.BSONSymbol}});var rD=ku();Object.defineProperty(D,"Timestamp",{enumerable:!0,get:function(){return rD.Timestamp}});var Be=Po();Object.defineProperty(D,"BSON_BINARY_SUBTYPE_BYTE_ARRAY",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_BYTE_ARRAY}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_DEFAULT",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_DEFAULT}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_FUNCTION",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_FUNCTION}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_MD5",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_MD5}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_USER_DEFINED",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_USER_DEFINED}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_UUID",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_UUID}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_UUID_NEW",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_UUID_NEW}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_ENCRYPTED",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_ENCRYPTED}});Object.defineProperty(D,"BSON_BINARY_SUBTYPE_COLUMN",{enumerable:!0,get:function(){return Be.BSON_BINARY_SUBTYPE_COLUMN}});Object.defineProperty(D,"BSON_DATA_ARRAY",{enumerable:!0,get:function(){return Be.BSON_DATA_ARRAY}});Object.defineProperty(D,"BSON_DATA_BINARY",{enumerable:!0,get:function(){return Be.BSON_DATA_BINARY}});Object.defineProperty(D,"BSON_DATA_BOOLEAN",{enumerable:!0,get:function(){return Be.BSON_DATA_BOOLEAN}});Object.defineProperty(D,"BSON_DATA_CODE",{enumerable:!0,get:function(){return Be.BSON_DATA_CODE}});Object.defineProperty(D,"BSON_DATA_CODE_W_SCOPE",{enumerable:!0,get:function(){return Be.BSON_DATA_CODE_W_SCOPE}});Object.defineProperty(D,"BSON_DATA_DATE",{enumerable:!0,get:function(){return Be.BSON_DATA_DATE}});Object.defineProperty(D,"BSON_DATA_DBPOINTER",{enumerable:!0,get:function(){return Be.BSON_DATA_DBPOINTER}});Object.defineProperty(D,"BSON_DATA_DECIMAL128",{enumerable:!0,get:function(){return Be.BSON_DATA_DECIMAL128}});Object.defineProperty(D,"BSON_DATA_INT",{enumerable:!0,get:function(){return Be.BSON_DATA_INT}});Object.defineProperty(D,"BSON_DATA_LONG",{enumerable:!0,get:function(){return Be.BSON_DATA_LONG}});Object.defineProperty(D,"BSON_DATA_MAX_KEY",{enumerable:!0,get:function(){return Be.BSON_DATA_MAX_KEY}});Object.defineProperty(D,"BSON_DATA_MIN_KEY",{enumerable:!0,get:function(){return Be.BSON_DATA_MIN_KEY}});Object.defineProperty(D,"BSON_DATA_NULL",{enumerable:!0,get:function(){return Be.BSON_DATA_NULL}});Object.defineProperty(D,"BSON_DATA_NUMBER",{enumerable:!0,get:function(){return Be.BSON_DATA_NUMBER}});Object.defineProperty(D,"BSON_DATA_OBJECT",{enumerable:!0,get:function(){return Be.BSON_DATA_OBJECT}});Object.defineProperty(D,"BSON_DATA_OID",{enumerable:!0,get:function(){return Be.BSON_DATA_OID}});Object.defineProperty(D,"BSON_DATA_REGEXP",{enumerable:!0,get:function(){return Be.BSON_DATA_REGEXP}});Object.defineProperty(D,"BSON_DATA_STRING",{enumerable:!0,get:function(){return Be.BSON_DATA_STRING}});Object.defineProperty(D,"BSON_DATA_SYMBOL",{enumerable:!0,get:function(){return Be.BSON_DATA_SYMBOL}});Object.defineProperty(D,"BSON_DATA_TIMESTAMP",{enumerable:!0,get:function(){return Be.BSON_DATA_TIMESTAMP}});Object.defineProperty(D,"BSON_DATA_UNDEFINED",{enumerable:!0,get:function(){return Be.BSON_DATA_UNDEFINED}});Object.defineProperty(D,"BSON_INT32_MAX",{enumerable:!0,get:function(){return Be.BSON_INT32_MAX}});Object.defineProperty(D,"BSON_INT32_MIN",{enumerable:!0,get:function(){return Be.BSON_INT32_MIN}});Object.defineProperty(D,"BSON_INT64_MAX",{enumerable:!0,get:function(){return Be.BSON_INT64_MAX}});Object.defineProperty(D,"BSON_INT64_MIN",{enumerable:!0,get:function(){return Be.BSON_INT64_MIN}});var nte=Nd();Object.defineProperty(D,"EJSON",{enumerable:!0,get:function(){return nte.EJSON}});var ite=ku();Object.defineProperty(D,"LongWithoutOverridesClass",{enumerable:!0,get:function(){return ite.LongWithoutOverridesClass}});var nD=br();Object.defineProperty(D,"BSONError",{enumerable:!0,get:function(){return nD.BSONError}});Object.defineProperty(D,"BSONTypeError",{enumerable:!0,get:function(){return nD.BSONTypeError}});var iD=1024*1024*17,Ei=Qu.Buffer.alloc(iD);function sD(e){Ei.length{var ote=require("stream").Transform,hD=lD();dD.exports=o(function(t){function r(n,i,s){if(t){var a=hD.deserialize(n);return a.cursor.firstBatch.forEach(function(u){this.push(hD.serialize(u))}.bind(this)),s()}return s(null,n)}return o(r,"transform"),new ote({readableObjectMode:!0,writableObjectMode:!0,transform:r})},"rawTransform")});var gD=w((gfe,yD)=>{var mD=Nv(),ate=pD(),ute=Av(),cte=require("util").inherits,fte=Xh()("mongodb-collection-sample:native-sampler");function lE(e,t,r){mD.call(this,e,t,r),this.running=!1}o(lE,"NativeSampler");cte(lE,mD);lE.prototype._read=function(){if(!this.running){this.running=!0;var e={maxTimeMS:this.maxTimeMS,allowDiskUse:!0,promoteValues:this.promoteValues};this.collection.countDocuments(this.query,e,function(t,r){if(t)return this.emit("error",t);if(fte("sampling %d documents from a collection with %d documents",this.size,r),r>this.size&&r<=this.size*20){var n=new ute(this.db,this.collectionName,this.opts);return n.on("error",this.emit.bind(this,"error")).on("data",this.push.bind(this)).on("end",this.push.bind(this,null))}this.pipeline=[],Object.keys(this.query).length>0&&this.pipeline.push({$match:this.query}),r>this.size&&this.pipeline.push({$sample:{size:this.size}}),this.fields&&Object.keys(this.fields).length>0&&this.pipeline.push({$project:this.fields}),e.raw=this.raw,e.cursor=this.cursor,e.batchSize=this.size;var i=this.collection.aggregate(this.pipeline,e);i.pipe(ate(this.raw)).on("error",this.emit.bind(this,"error")).on("data",this.push.bind(this)).on("end",this.push.bind(this,null))}.bind(this))}};yD.exports=lE});var wD=w((wfe,hE)=>{var lte=JO(),hte=hx(),dte=Xh()("mongodb-collection-sample"),pte=Av(),mte=gD();function SD(e,t,r,n){e.admin().serverInfo(function(i,s){if(i)return n(i);var a=hte.gte(s.version,"3.1.6");return dte("has native $sample?",a),a?n(null,new mte(e,t,r)):n(null,new pte(e,t,r))})}o(SD,"getSampler");hE.exports=function(e,t,r){var n=lte.readable(function(){SD(e,t,r,function(i,s){if(i)return n.emit("error",i);s.on("data",n.emit.bind(n,"data")),s.on("error",n.emit.bind(n,"error")),s.on("end",n.emit.bind(n,"end"))})});return n};hE.exports.getSampler=SD});var vD=w((vfe,OD)=>{OD.exports=wD()});var ND=w((Efe,TD)=>{var yte=TO().MongoClient,gte=vD(),dE,ys;function Ste(e){return{sshTunnelUsername:e.ssh_user||"ec2-user",sshTunnelHostname:e.ssh_host,sshTunnelPort:Number(e.ssh_port)||22,sshAuthMethod:e.ssh_method==="privateKey"?"IDENTITY_FILE":"",sshTunnelIdentityFile:e.ssh_key_file,sshTunnelPassphrase:e.ssh_key_passphrase,host:e.host,port:Number(e.port)}}o(Ste,"getSshConfig");var wte=o(async(e,t)=>{let r=Ste(e),{options:n}=await t.openTunnel(r);return{...e,host:n.host,port:n.port.toString()||"22"}},"getSshConnectionSettings");function Ote(e){let t=_D(e.username),r=_D(e.password);return e.sslType==="TRUST_CUSTOM_CA_SIGNED_CERTIFICATES"&&e.ssh||e.sslType==="UNVALIDATED_SSL"?{url:`mongodb://${t}:${r}@${e.host}:${e.port}/?retryWrites=false`,options:{tls:!0,tlsAllowInvalidHostnames:!0,useUnifiedTopology:!0,sslValidate:!1}}:e.sslType==="TRUST_CUSTOM_CA_SIGNED_CERTIFICATES"?{url:`mongodb://${t}:${r}@${e.host}:${e.port}/?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`,options:{tlsCAFile:e.certAuthority,useUnifiedTopology:!0}}:{url:`mongodb://${t}:${r}@${e.host}:${e.port}/?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`,options:{useNewUrlParser:!0,useUnifiedTopology:!0}}}o(Ote,"generateConnectionParams");async function vte(e,t){try{if(ys)return ED(ys);e.ssh&&(e=await wte(e,t),dE=!0);let r=Ote(e);return ys=await yte.connect(r.url,r.options),ED(ys)}catch(r){throw{message:r.code===18?"Authentication failed. Please, check connection settings and try again":r.message,stack:r.stack}}}o(vte,"connect");function ED(e){let t=o(()=>new Promise((d,m)=>{e.db().admin().listDatabases((E,O)=>E?m(E):d(O.databases))}),"getDatabases"),r=o(d=>new Promise((m,S)=>{let E=e.db(d);if(!E)return S(new Error(`Failed connection to database "${d}"`));E.listCollections().toArray((O,T)=>O?S(O):m(T))}),"getCollections"),n=o(()=>new Promise((d,m)=>{e.db().admin().buildInfo((E,O)=>{E?m(E):d(O)})}),"getBuildInfo"),i=o((d,m,S)=>{let E=e.db(d);return!S.sort||Object.keys(S.sort).length===0?gte(E,m,S):E.collection(m).find(S.query,{sort:S.sort,limit:Number(S.size),maxTimeMS:S.maxTimeMS}).stream()},"getDataStream"),s=o((d,m,{query:S,sort:E,limit:O,maxTimeMS:T})=>new Promise((R,_)=>{let q=[],H={size:Number(O),query:S,sort:E,maxTimeMS:T||12e4},ue,j=o(K=>{if(K.code===28799&&(K={message:"MongoDB Error: $sample stage could not find a non-duplicate document after 100 while using a random cursor. Please try again."}),K.code===11601){let W=new Error("MongoDB Error: "+K.message+". Please, try to increase query timeout (Options -> Reverse-Engineering) and try again.");W.stack=K.stack,K=W}ue=K,_(K)},"streamErrorHandler"),te=i(d,m,H);te.on("error",K=>{j(K)}),te.on("data",K=>{q.push(K)}),te.on("end",()=>{ue||R(q)})}),"getRandomDocuments"),a=o((d,m)=>new Promise((S,E)=>{e.db(d).collection(m).estimatedDocumentCount((R,_)=>R?E(R):S(_))}),"getCount"),u=o((d,m,S)=>new Promise((E,O)=>{e.db(d).collection(m).findOne(S,(_,N)=>_?O(_):E(N))}),"findOne");return{getDatabases:t,getCollections:r,getBuildInfo:n,getDataStream:i,getCount:a,getRandomDocuments:s,findOne:u,hasPermission:o(async(d,m)=>{try{return await u(d,m),!0}catch(S){if(S.code===13)return!1;throw S}},"hasPermission"),getIndexes:o((d,m)=>new Promise((S,E)=>{e.db(d).collection(m).indexes({full:!0},(R,_)=>R?E(R):S(_))}),"getIndexes"),getCollection:o((d,m)=>{let E=e.db(d).collection(m);return{createIndex(O,T){return E.createIndex(O,T)},insertOne(O){return E.insertOne(O)}}},"getCollection"),createCollection:o(async(d,m)=>{let E=e.db(d);try{return await E.createCollection(m)}catch(O){if(O.code===48)return;throw O}},"createCollection")}}o(ED,"createConnection");async function Ete(e){ys&&(ys.close(),ys=null),dE&&(dE=!1,await e.closeConsumer())}o(Ete,"close");var _D=o(e=>encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16)}),"encodeURIComponentRFC3986");TD.exports={connect:vte,close:Ete}});var bD=w((Tfe,_te)=>{_te.exports={name:"DocumentDB",version:"0.1.8",versionDate:"2023-08-03",author:"hackolade",engines:{hackolade:"6.10.3",hackoladePlugin:"1.0.1"},contributes:{target:{applicationTarget:"DocumentDB",title:"DocumentDB",versions:["3.6.0","4.0.0","5.0.0"]},features:{nestedCollections:!1,forwardEngineering:{jsonSchema:{keepParentType:{objectId:{type:"string",pattern:"^[a-fA-F0-9]{24}$"},regex:"string",date:{type:"string",format:"date-time"},timestamp:{type:"string",format:"date-time"},binary:{type:"string",mediaType:"image/png",contentEncoding:"base64"},minKey:"number",maxKey:"number"}}},enableReverseEngineering:!0,enableForwardEngineering:!0,enableReverseEngineeringDetectionSchemaByContent:!1,enableReversingDateTypeAsISODate:!0,supportInferRelationships:!0,enableREQueryAndSortCriteria:!0}},description:"Hackolade plugin for Amazon DocumentDB",scripts:{lint:"eslint . --max-warnings=0",package:"node esbuild.package.js"},dependencies:{async:"^3.2.4",bson:"^1.1.6",lodash:"^4.17.21",mongodb:"^3.7.3","mongodb-collection-sample":"^4.5.1"},devDependencies:{"@hackolade/hck-esbuild-plugins-pack":"^0.0.1",esbuild:"^0.19.4","esbuild-plugin-clean":"^1.0.1",eslint:"^8.51.0","eslint-config-prettier":"^9.0.0","eslint-plugin-prettier":"^5.0.0","lint-staged":"^14.0.1",prettier:"^3.0.3","simple-git-hooks":"^2.9.0"},"lint-staged":{"*.{js,json}":"prettier --write"},"simple-git-hooks":{"pre-commit":"npx lint-staged","pre-push":"npx eslint ."}}});var AD=w((Nfe,CD)=>{var Ln=require("os"),Tte=bD(),Nte=o(()=>Tte.version,"getPluginVersion"),bte=o(e=>`Date: ${new Date} +Application version: ${e} +Plugin version: ${Nte()} + +System information: + Hostname: ${Ln.hostname()} + Platform: ${Ln.platform()} ${Ln.arch()} + Release: ${Ln.release()} + Uptime: ${Ite(Ln.uptime())} + Total RAM: ${(Ln.totalmem()/1073741824).toFixed(2)} GB + CPU Model: ${Ln.cpus()[0].model} + CPU Clock: ${Cte(Ln.cpus())} MHZ + CPU Cores: ${Ln.cpus().length} cores + +`,"getSystemInfo"),Cte=o(e=>e.reduce((t,r)=>Math.max(t,r.speed),0),"maxClock"),Ate=o(e=>e<10?"0"+e:e,"prefixZero"),Ite=o(e=>Math.floor(e/3600)+":"+Ate(parseInt((e/3600-Math.floor(e/3600))*60)),"toTime"),Bte=o(({title:e,logger:t,hiddenKeys:r})=>({info(n){t.log("info",{message:n},e,r)},progress(n,i="",s=""){t.progress({message:n,containerName:i,entityName:s})},error(n){t.log("error",Rte(n),e)}}),"createLogger"),Rte=o(e=>({message:e.message||e.msg||e.errmsg,code:e.code,stack:e.stack}),"createError"),Mte={getSystemInfo:bte,createLogger:Bte};CD.exports=Mte});var BD=w((Cfe,ID)=>{var Ud,xte=o((e,t)=>{if(Ud)return Ud;let r=["accessKeyId","secretAccessKey","sessionToken","region"].reduce((a,u)=>e[u]?{...a,[u]:e[u]}:a,{});t.config.update(r);let n=new t.DocDB,i=e.dbClusterIdentifier,s=e.region;return Ud={getCluster(){return new Promise((a,u)=>{n.describeDBClusters({DBClusterIdentifier:i},(c,f)=>{var h;c?u(c):a((h=f==null?void 0:f.DBClusters)==null?void 0:h[0])})})},getRegion(){return s},tags(a){return new Promise((u,c)=>{n.listTagsForResource({ResourceName:a},(f,h)=>{f?c(f):u(h)})})}},Ud},"awsHelper");ID.exports=xte});var Wd=e_(),Fd=ND(),{createLogger:pE,getSystemInfo:RD}=AD(),mE=Wc(),MD=BD();module.exports={disconnect:async function(e,t,r,n){let i=n.require("@hackolade/ssh-service");await Fd.close(i),r()},async testConnection(e,t,r,n){let i=n.require("@hackolade/ssh-service"),s=pE({title:"Test connection",hiddenKeys:e.hiddenKeys,logger:t});try{t.clear(),s.info(RD(e.appVersion)),s.info(e),await Fd.connect(e,i),s.info("Connected successfully"),r()}catch(a){return s.error(a),r({message:a.message,stack:a.stack})}},async getDbCollectionsNames(e,t,r,n){let i=n.require("@hackolade/ssh-service"),s=n.require("aws-sdk"),a=pE({title:"Retrieving databases and collections information",hiddenKeys:e.hiddenKeys,logger:t});try{MD({...e,...zte(e.host,a)},s),t.clear(),a.info(RD(e.appVersion)),a.info(e);let u=e.includeSystemCollection,c=await Fd.connect(e,i),f=await c.getDatabases(),h=await Wd.mapSeries(f,async l=>{let m=(await c.getCollections(l.name)).map(S=>S.name);return a.info({message:"Found collections",collections:m}),m=await Wd.filter(m,async S=>c.hasPermission(l.name,S)),a.info({message:"Collections that user has access to",collections:m}),u||(m=Pte(m)),a.info({message:"Collections to process",collections:m}),{dbName:l.name,dbCollections:m,isEmpty:m.length===0}});a.info("Names retrieved successfully"),r(null,h)}catch(u){a.error(u),r({message:u.message,stack:u.stack})}},async getDbCollectionsData(e,t,r,n){var s;let i=pE({title:"Retrieving data for inferring schema",hiddenKeys:e.hiddenKeys,logger:t});try{let{recordSamplingSettings:a,fieldInference:u,includeEmptyCollection:c,collectionData:f}=e,h=xD(e.queryCriteria),l=xD(e.sortCriteria),d=Number(e.queryRequestTimeout)||12e4,m=MD();i.info({title:"Parameters",sampling:Dte(a,u),data:e});let S=await Fd.connect(),O={version:(await S.getBuildInfo()).version};i.progress("Start reverse-engineering");try{i.info("Getting cluster information"),i.progress("Getting cluster information ...");let R=await m.getCluster();if(!R)throw new Error("Cluster doesn't exist in the chosen region.");let _=await m.tags(R.DBClusterArn),N=Fte(R);O={...O,"source-region":m.getRegion(),...N,tags:(s=_.TagList)==null?void 0:s.map(P=>({tagName:P.Key,tagValue:P.Value}))}}catch(R){i.progress("[color:red]Error of getting cluster information"),i.info("Cannot get information about the cluster from AWS. Please, check AWS credentials in the connection settings."),i.error(R)}let T=await Wd.reduce(f.dataBaseNames,[],async(R,_)=>await Wd.reduce(f.collections[_],R,async(N,P)=>{i.info({message:"Calculate count of documents",dbName:_,collectionName:P}),i.progress("Calculate count of documents",_,P);let q=await S.getCount(_,P);if(!c&&q===0)return N;let H=Lte(q,a);i.info({message:"Getting documents for sampling",dbName:_,collectionName:P,countOfDocuments:q,documentsToSample:H}),i.progress("Getting documents for sampling",_,P);let ue=await S.getRandomDocuments(_,P,{maxTimeMS:d,limit:H,query:h,sort:l}),j={};u.active==="field"&&(i.info({message:"Getting a document for inferring",dbName:_,collectionName:P}),i.progress("Getting a document for inferring",_,P),j=await S.findOne(_,P,h)),i.info({message:"Getting indexes",dbName:_,collectionName:P}),i.progress("Getting indexes",_,P);let te=await S.getIndexes(_,P),K={dbName:_,collectionName:P,documents:ue,relationshipDocuments:qte(ue),primaryKey:"_id",standardDoc:j,validation:{jsonSchema:yE(ue[0])},entityLevel:{Indxs:jte(te)}};return i.info({message:"Collection processed",dbName:_,collectionName:P}),i.progress("Collection processed",_,P),N.concat(K)}));r(null,T,O,[])}catch(a){i.error(a),r({message:a.message,stack:a.stack})}}};var xD=o(e=>{try{return JSON.parse(e)}catch{return{}}},"safeParse"),qte=o(e=>{let t=o(i=>i&&typeof i=="object","isObject"),r=o(i=>i?Array.isArray(i)?i.length===0:t(i)?Object.keys(i).length===0:!1:!0,"isEmpty"),n=o(i=>Object.keys(i).reduce((s,a)=>{var u,c;if(((u=i==null?void 0:i[a])==null?void 0:u._bsontype)==="ObjectID")return{...s,[a]:i[a]};if(((c=i==null?void 0:i[a])==null?void 0:c._bsontype)==="DBRef")return{...s};if(t(i[a])||Array.isArray(i[a])){let f=n(i[a]);return r(f)?{...s}:{...s,[a]:f}}return{...s}},{}),"iterateProps");return e.map(i=>n(i)).filter(i=>!r(i))},"filterPotentialForeignKeys");function Dte(e,t){let r={},n=e[e.active].value,i=e.active==="relative"?"%":" records max";return r.recordSampling=`${e.active} ${n}${i}`,r.fieldInference=t.active==="field"?"keep field order":"alphabetical order",r}o(Dte,"getSamplingInfo");function Pte(e){return e.filter(t=>(t==null?void 0:t.length)<8||(t==null?void 0:t.substring(0,7))!=="system.")}o(Pte,"filterSystemCollections");var Lte=o((e,t)=>{if(t.active==="absolute")return Number(t.absolute.value);let r=Math.ceil(e*t.relative.value/100);return Math.min(r,t.maxValue)},"getSampleDocSize");function yE(e){if(!(e instanceof mE.ObjectID||e instanceof mE.DBRef))if(Array.isArray(e)){let t=yE(e[0]);if(t)return{items:t}}else{if(e instanceof mE.Long)return{type:"numeric",mode:"int64"};if(typeof e=="number"&&e%1!==0)return{type:"numeric",mode:"double"};if(typeof e=="number"&&Math.abs(e)<2**32)return{type:"numeric",mode:"int32"};if(e&&typeof e=="object"){let t=Object.keys(e).reduce((r,n)=>{let i=yE(e[n]);return i?{...r,[n]:i}:r},{});return Object.keys(t).length===0?void 0:{properties:t}}}}o(yE,"getJsonSchema");function jte(e){return e.filter(t=>t.name!=="_id_").map(t=>({name:t.name,key:Object.keys(t.key).map(r=>({name:r,type:Ute(t.key[r])})),sparse:t.sparse,unique:t.unique,expireAfterSeconds:t.expireAfterSeconds,"2dsphere":t["2dsphereIndexVersion"]?Wte(t["2dsphereIndexVersion"]):{}}))}o(jte,"getIndexes");var Ute=o(e=>{switch(e){case 1:return"ascending";case-1:return"descending";case"2dsphere":return"2DSphere"}return"ascending"},"getIndexType"),Wte=o(e=>{let t="default";return e===1&&(t="Version 1"),e===2&&(t="Version 2"),{"2dsphereIndexVersion":t}},"getGeoIndexVersion"),Fte=o(e=>{var t;return{dbInstances:(t=e.DBClusterMembers)==null?void 0:t.map(r=>({dbInstanceIdentifier:r.DBInstanceIdentifier,dbInstanceRole:r.IsClusterWriter?"Primary":"Replica"})),DBClusterIdentifier:e.DBClusterIdentifier,DBClusterArn:e.DBClusterArn,Endpoint:e.Endpoint,ReaderEndpoint:e.ReaderEndpoint,MultiAZ:e.MultiAZ,Port:e.Port??27017,DBClusterParameterGroup:e.DBClusterParameterGroup,DbClusterResourceId:e.DbClusterResourceId,StorageEncrypted:e.StorageEncrypted,BackupRetentionPeriod:String(e.BackupRetentionPeriod??""),auditLog:!1,maintenance:!!e.PreferredMaintenanceWindow,...e.PreferredMaintenanceWindow?$te(e.PreferredMaintenanceWindow):{}}},"getClusterData"),$te=o(e=>{let t=o(s=>{let a=s.slice(0,3);return{sun:"Sunday",mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday"}[a]||"Sunday"},"getDay"),r=o(s=>{let a=s.slice(4),[u,c]=a.split(":"),f=new Date(0);return f.setHours(+u),f.setMinutes(+c),f},"getTime"),[n,i]=e.split("-");return{startDay:t(n),startHour:String(r(n).getHours()).padStart(2,"0"),startMinute:String(r(n).getMinutes()).padStart(2,"0"),duration:String((r(i)-r(n))/(1e3*60*60))}},"parseMaintenance"),zte=o((e,t)=>{try{let[r,,n]=e.split(".");return{dbClusterIdentifier:r,region:n}}catch(r){t.error(r)}},"parseHost"); +/*! Bundled license information: + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) +*/ diff --git a/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json b/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json index 91000af..c33abf0 100644 --- a/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json +++ b/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json @@ -7,7 +7,6 @@ "inputKeyword": "name", "inputType": "text", "inputPlaceholder": "Name" - }, { "inputLabel": "Host", @@ -33,7 +32,6 @@ "inputKeyword": "username", "inputType": "text", "inputPlaceholder": "User Name" - }, { "inputLabel": "Password", @@ -52,18 +50,20 @@ "inputLabel": "SSL", "inputKeyword": "sslType", "inputType": "select", - "options": [{ - "value": "Off", - "label": "Off" - },{ - "value": "UNVALIDATED_SSL", - "label": "Unvalidated" - - },{ - "value": "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES", - "label": "Server validation" - - }] + "options": [ + { + "value": "Off", + "label": "Off" + }, + { + "value": "UNVALIDATED_SSL", + "label": "Unvalidated" + }, + { + "value": "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES", + "label": "Server validation" + } + ] }, { "inputLabel": "Certificate Authority", @@ -124,10 +124,12 @@ "inputKeyword": "ssh_method", "inputType": "select", "defaultValue": "privateKey", - "options": [{ - "value": "privateKey", - "label": "Private Key" - }], + "options": [ + { + "value": "privateKey", + "label": "Private Key" + } + ], "disable": { "key": "ssh", "value": false @@ -190,4 +192,4 @@ } ] } -] \ No newline at end of file +] diff --git a/reverse_engineering/helpers/awsHelper.js b/reverse_engineering/helpers/awsHelper.js deleted file mode 100644 index b73f120..0000000 --- a/reverse_engineering/helpers/awsHelper.js +++ /dev/null @@ -1,60 +0,0 @@ -let instance; - -const awsHelper = (connectionInfo, awsSdk) => { - if (instance) { - return instance; - } - - let awsOptions = ['accessKeyId', 'secretAccessKey', 'sessionToken', 'region'].reduce((options, key) => { - if (!connectionInfo[key]) { - return options; - } - - return { - ...options, - [key]: connectionInfo[key], - }; - }, {}); - - awsSdk.config.update(awsOptions); - const docDb = new awsSdk.DocDB(); - - const dbClusterIdentifier = connectionInfo.dbClusterIdentifier; - const clusterRegion = connectionInfo.region; - - instance = { - getCluster() { - return new Promise((resolve, reject) => { - docDb.describeDBClusters({ - DBClusterIdentifier: dbClusterIdentifier, - }, (err, data) => { - if (err) { - reject(err); - } else { - resolve(data?.['DBClusters']?.[0]); - } - }); - }); - }, - getRegion() { - return clusterRegion; - }, - tags(resourceName) { - return new Promise((resolve, reject) => { - docDb.listTagsForResource({ - ResourceName: resourceName, - }, (err, data) => { - if (err) { - reject(err); - } else { - resolve(data); - } - }); - }); - }, - }; - - return instance; -}; - -module.exports = awsHelper; diff --git a/reverse_engineering/helpers/connectionHelper.js b/reverse_engineering/helpers/connectionHelper.js deleted file mode 100644 index 49014c3..0000000 --- a/reverse_engineering/helpers/connectionHelper.js +++ /dev/null @@ -1,334 +0,0 @@ -const MongoClient = require('mongodb').MongoClient; -const ssh = require('tunnel-ssh'); -const fs = require('fs'); -const mongodbSample = require('mongodb-collection-sample'); - -let sshTunnel; -let connection; - -function getSshConfig(info) { - const config = { - username: info.ssh_user || 'ec2-user', - host: info.ssh_host, - port: info.ssh_port || 22, - dstHost: info.host, - dstPort: info.port, - localHost: '127.0.0.1', - localPort: info.port, - keepAlive: true, - }; - - return Object.assign({}, config, { - privateKey: fs.readFileSync(info.ssh_key_file), - passphrase: info.ssh_key_passphrase - }); -}; - -const connectViaSsh = (info) => new Promise((resolve, reject) => { - ssh(getSshConfig(info), (err, tunnel) => { - if (err) { - reject(err); - } else { - resolve({ - tunnel, - info: Object.assign({}, info, { - host: '127.0.0.1', - }) - }); - } - }); -}); - -function generateConnectionParams(connectionInfo){ - if ((connectionInfo.sslType === 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' && connectionInfo.ssh) || connectionInfo.sslType === 'UNVALIDATED_SSL') { - return { - url: `mongodb://${connectionInfo.username}:${connectionInfo.password}@${connectionInfo.host}:${connectionInfo.port}/?retryWrites=false`, - options: { - tls: true, - tlsAllowInvalidHostnames: true, - useUnifiedTopology: true, - sslValidate: false, - } - }; - } - if (connectionInfo.sslType === 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES') { - return { - url: `mongodb://${connectionInfo.username}:${connectionInfo.password}@${connectionInfo.host}:${connectionInfo.port}/?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`, - options: { - tlsCAFile: connectionInfo.certAuthority, - useUnifiedTopology: true, - } - }; - } else { - return { - url: `mongodb://${connectionInfo.username}:${connectionInfo.password}@${connectionInfo.host}:${connectionInfo.port}/?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`, - options: { - useNewUrlParser: true, - useUnifiedTopology: true, - } - }; - } -} - -async function connect(connectionInfo) { - try { - if (connection) { - return createConnection(connection); - } - - if (connectionInfo.ssh) { - const {tunnel, info} = await connectViaSsh(connectionInfo); - sshTunnel = tunnel; - connectionInfo = info; - } - - const params = generateConnectionParams(connectionInfo); - - connection = await MongoClient.connect(params.url, params.options); - - return createConnection(connection); - } catch (err) { - throw { - message: err.code === 18 ? 'Authentication failed. Please, check connection settings and try again' : err.message, - stack: err.stack, - }; - } -} - -function createConnection(connection) { - const getDatabases = () => { - return new Promise((resolve, reject) => { - const db = connection.db(); - db.admin().listDatabases((err, dbs) => { - if (err) { - return reject(err); - } else { - return resolve(dbs.databases); - } - }); - }); - }; - const getCollections = (dbName) => { - return new Promise((resolve, reject) => { - const db = connection.db(dbName); - - if (!db) { - return reject(new Error(`Failed connection to database "${dbName}"`)); - } - - db.listCollections().toArray((err, collections) => { - if (err) { - return reject(err); - } else { - return resolve(collections); - } - }); - }); - }; - - const getBuildInfo = () => { - return new Promise((resolve, reject) => { - const db = connection.db(); - - db.admin().buildInfo((err, info) => { - if (err) { - reject(err); - } else { - resolve(info); - } - }); - }); - }; - - const getDataStream = (dbName, collectionName, options) => { - const db = connection.db(dbName); - - if (!options.sort || Object.keys(options.sort).length === 0) { - return mongodbSample(db, collectionName, options); - } - - const collection = db.collection(collectionName); - - return collection - .find(options.query, { - sort: options.sort, - limit: Number(options.size), - maxTimeMS: options.maxTimeMS, - }) - .stream(); - }; - - const getRandomDocuments = (dbName, collectionName, { - query, - sort, - limit, - maxTimeMS, - }) => { - return new Promise((resolve, reject) => { - const RANDOM_SAMPLING_ERROR_CODE = 28799; - const INTERRUPTED_OPERATION = 11601; - let sampledDocs = []; - const options = { - size: Number(limit), - query: query, - sort: sort, - maxTimeMS: maxTimeMS || 120000, - }; - let streamError; - - const streamErrorHandler = err => { - if (err.code === RANDOM_SAMPLING_ERROR_CODE) { - err = { - message: - 'MongoDB Error: $sample stage could not find a non-duplicate document after 100 while using a random cursor. Please try again.', - }; - } - - if (err.code === INTERRUPTED_OPERATION) { - const newError = new Error('MongoDB Error: ' + err.message + '. Please, try to increase query timeout (Options -> Reverse-Engineering) and try again.'); - newError.stack = err.stack; - err = newError; - } - - streamError = err; - - reject(err); - }; - - const stream = getDataStream(dbName, collectionName, options); - stream.on('error', err => { - streamErrorHandler(err); - }); - - stream.on('data', doc => { - sampledDocs.push(doc); - }); - - stream.on('end', () => { - if (streamError) { - return; - } - - resolve(sampledDocs); - }); - }); - }; - - const getCount = (dbName, collectionName) => { - return new Promise((resolve, reject) => { - const db = connection.db(dbName); - const collection = db.collection(collectionName); - - collection.estimatedDocumentCount((err, count) => { - if (err) { - return reject(err); - } else { - return resolve(count); - } - }); - }); - }; - - const findOne = (dbName, collectionName, query) => { - return new Promise((resolve, reject) => { - const db = connection.db(dbName); - const collection = db.collection(collectionName); - - collection.findOne(query, (err, result) => { - if (err) { - return reject(err); - } else { - return resolve(result); - } - }); - }); - }; - - const hasPermission = async (dbName, collectionName) => { - try { - await findOne(dbName, collectionName); - - return true; - } catch (e) { - if (e.code === 13) { - return false; - } - - throw e; - } - }; - - const getIndexes = (dbName, collectionName) => { - return new Promise((resolve, reject) => { - const db = connection.db(dbName); - const collection = db.collection(collectionName); - - collection.indexes({ full: true }, (err, indexes) => { - if (err) { - return reject(err); - } - - return resolve(indexes); - }); - }); - }; - - const getCollection = (dbName, collectionName) => { - const db = connection.db(dbName); - const collection = db.collection(collectionName); - - return { - createIndex(fields, options) { - return collection.createIndex(fields, options); - }, - insertOne(data) { - return collection.insertOne(data); - } - }; - }; - - const createCollection = async (dbName, collectionName) => { - const COLLECTION_ALREADY_EXISTS_ERROR = 48; - const db = connection.db(dbName); - - try { - return await db.createCollection(collectionName); - } catch (error) { - if (error.code === COLLECTION_ALREADY_EXISTS_ERROR) { - return; - } - throw error; - } - }; - - return { - getDatabases, - getCollections, - getBuildInfo, - getDataStream, - getCount, - getRandomDocuments, - findOne, - hasPermission, - getIndexes, - getCollection, - createCollection, - }; -} - -function close() { - if (connection) { - connection.close(); - connection = null; - } - - if (sshTunnel) { - sshTunnel.close(); - sshTunnel = null; - } -}; - -module.exports = { - connect, - close, -}; diff --git a/reverse_engineering/helpers/logHelper.js b/reverse_engineering/helpers/logHelper.js deleted file mode 100644 index b903397..0000000 --- a/reverse_engineering/helpers/logHelper.js +++ /dev/null @@ -1,65 +0,0 @@ -const os = require('os'); -const packageFile = require('../../package.json'); - -const getPluginVersion = () => packageFile.version; - -const getSystemInfo = (appVersion) => { - return '' + - `Date: ${new Date()}` + '\n' + - `Application version: ${appVersion}` + '\n' + - `Plugin version: ${getPluginVersion()}` + '\n\n' + - `System information:` + '\n' + - ` Hostname: ${os.hostname()}` + '\n' + - ` Platform: ${os.platform()} ${os.arch()}` + '\n' + - ` Release: ${os.release()}` + '\n' + - ` Uptime: ${toTime(os.uptime())}` + '\n' + - ` Total RAM: ${(os.totalmem()/1073741824).toFixed(2)} GB` + '\n' + - ` CPU Model: ${os.cpus()[0].model}` + '\n' + - ` CPU Clock: ${maxClock(os.cpus())} MHZ` + '\n' + - ` CPU Cores: ${os.cpus().length} cores` + '\n\n'; -}; - - -const maxClock = (cpus) => { - return cpus.reduce((highestClock, cpu) => Math.max(highestClock, cpu.speed), 0); -}; - -const prefixZero = (number) => number < 10 ? "0" + number : number; - -const toTime = (number) => { - return (Math.floor(number/3600))+":"+prefixZero(parseInt((number/3600-Math.floor(number/3600))*60)) -}; - -const createLogger = ({ title, logger, hiddenKeys }) => { - return { - info(message) { - logger.log('info', { message }, title, hiddenKeys); - }, - - progress(message, dbName = '', tableName = '') { - logger.progress({ message, containerName: dbName, entityName: tableName }); - }, - - error(error) { - logger.log('error', createError(error), title); - } - }; -}; - -const createError = (error) => { - message = error.message || error.msg || error.errmsg; - - return { - message, - code: error.code, - stack: error.stack, - }; -} - - -const logHelper = { - getSystemInfo, - createLogger, -}; - -module.exports = logHelper; diff --git a/reverse_engineering/node_modules/.bin/mongodb-collection-sample b/reverse_engineering/node_modules/.bin/mongodb-collection-sample deleted file mode 120000 index 5431d01..0000000 --- a/reverse_engineering/node_modules/.bin/mongodb-collection-sample +++ /dev/null @@ -1 +0,0 @@ -../mongodb-collection-sample/bin/mongodb-collection-sample.js \ No newline at end of file diff --git a/reverse_engineering/node_modules/.bin/semver b/reverse_engineering/node_modules/.bin/semver deleted file mode 120000 index 317eb29..0000000 --- a/reverse_engineering/node_modules/.bin/semver +++ /dev/null @@ -1 +0,0 @@ -../semver/bin/semver \ No newline at end of file diff --git a/reverse_engineering/node_modules/.package-lock.json b/reverse_engineering/node_modules/.package-lock.json deleted file mode 100644 index 0617b2c..0000000 --- a/reverse_engineering/node_modules/.package-lock.json +++ /dev/null @@ -1,737 +0,0 @@ -{ - "name": "cosmosdb", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "optional": true, - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/asn1": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", - "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", - "dependencies": { - "safer-buffer": "~2.1.0" - } - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/bcrypt-pbkdf": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", - "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", - "dependencies": { - "tweetnacl": "^0.14.3" - } - }, - "node_modules/bl": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/bl/-/bl-2.2.1.tgz", - "integrity": "sha512-6Pesp1w0DEX1N550i/uGV/TqucVL4AM/pgThFSN/Qq9si1/DF9aIHs1BxD8V/QU0HoeHO6cQRTAuYnLPKq1e4g==", - "dependencies": { - "readable-stream": "^2.3.5", - "safe-buffer": "^5.1.1" - } - }, - "node_modules/bson": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.6.tgz", - "integrity": "sha512-EvVNVeGo4tHxwi8L6bPj3y3itEvStdwvvlojVxxbyYfoaxJ6keLgrTuKdyfEAszFK+H3olzBuafE0yoh0D1gdg==", - "engines": { - "node": ">=0.6.19" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "optional": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/cliui": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", - "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", - "optional": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^6.2.0" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "optional": true, - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "optional": true - }, - "node_modules/core-util-is": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", - "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" - }, - "node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/denque": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/denque/-/denque-1.5.1.tgz", - "integrity": "sha512-XwE+iZ4D6ZUB7mfYRMb5wByE8L74HCn30FBN7sWnXksWc1LO1bPDl67pBR9o/kC4z/xSNAwkMYcGgqDV3BE3Hw==", - "engines": { - "node": ">=0.10" - } - }, - "node_modules/duplexer": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz", - "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==" - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "optional": true - }, - "node_modules/event-stream": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/event-stream/-/event-stream-4.0.1.tgz", - "integrity": "sha512-qACXdu/9VHPBzcyhdOWR5/IahhGMf0roTeZJfzz077GwylcDd90yOHLouhmv7GJ5XzPi6ekaQWd8AvPP2nOvpA==", - "dependencies": { - "duplexer": "^0.1.1", - "from": "^0.1.7", - "map-stream": "0.0.7", - "pause-stream": "^0.0.11", - "split": "^1.0.1", - "stream-combiner": "^0.2.2", - "through": "^2.3.8" - } - }, - "node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "optional": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/from": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/from/-/from-0.1.7.tgz", - "integrity": "sha1-g8YK/Fi5xWmXAH7Rp2izqzA6RP4=" - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "optional": true, - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "optional": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/lodash.chunk": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.chunk/-/lodash.chunk-4.2.0.tgz", - "integrity": "sha1-ZuXOH3btJ7QwPYxlEujRIW6BBrw=" - }, - "node_modules/lodash.defaults": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "integrity": "sha1-0JF4cW/+pN3p5ft7N/bwgCJ0WAw=" - }, - "node_modules/map-stream": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.0.7.tgz", - "integrity": "sha1-ih8HiW2CsQkmvTdEokIACfiJdKg=" - }, - "node_modules/memory-pager": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", - "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "optional": true - }, - "node_modules/mongodb": { - "version": "3.7.3", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.7.3.tgz", - "integrity": "sha512-Psm+g3/wHXhjBEktkxXsFMZvd3nemI0r3IPsE0bU+4//PnvNWKkzhZcEsbPcYiWqe8XqXJJEg4Tgtr7Raw67Yw==", - "dependencies": { - "bl": "^2.2.1", - "bson": "^1.1.4", - "denque": "^1.4.1", - "optional-require": "^1.1.8", - "safe-buffer": "^5.1.2" - }, - "engines": { - "node": ">=4" - }, - "optionalDependencies": { - "saslprep": "^1.0.0" - }, - "peerDependenciesMeta": { - "aws4": { - "optional": true - }, - "bson-ext": { - "optional": true - }, - "kerberos": { - "optional": true - }, - "mongodb-client-encryption": { - "optional": true - }, - "mongodb-extjson": { - "optional": true - }, - "snappy": { - "optional": true - } - } - }, - "node_modules/mongodb-collection-sample": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/mongodb-collection-sample/-/mongodb-collection-sample-4.5.1.tgz", - "integrity": "sha512-tUCdRLToheOh2Tn+KVdhYtbLifxCo60+wVMf0zxtbZLKPYbZqQaYmyrYTsEunePNJyxIutBWdayX79VJ/Fb2hg==", - "dependencies": { - "bson": "^4.0.3", - "debug": "^4.1.1", - "event-stream": "^4.0.1", - "lodash.chunk": "^4.2.0", - "lodash.defaults": "^4.2.0", - "reservoir": "^0.1.2", - "semver": "^5.7.1" - }, - "bin": { - "mongodb-collection-sample": "bin/mongodb-collection-sample.js" - }, - "optionalDependencies": { - "mongodb-ns": "^2.2.0", - "yargs": "^15.1.0" - } - }, - "node_modules/mongodb-collection-sample/node_modules/bson": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/bson/-/bson-4.6.0.tgz", - "integrity": "sha512-8jw1NU1hglS+Da1jDOUYuNcBJ4cNHCFIqzlwoFNnsTOg2R/ox0aTYcTiBN4dzRa9q7Cvy6XErh3L8ReTEb9AQQ==", - "dependencies": { - "buffer": "^5.6.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/mongodb-collection-sample/node_modules/debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/mongodb-collection-sample/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/mongodb-ns": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/mongodb-ns/-/mongodb-ns-2.2.0.tgz", - "integrity": "sha512-sch/9jd74VjRCmB5U+Fj4WJnkmAtDQgxqJkBInO7zEknXE+lnDEuNBT5/Wp59HMrWUabssGGq08r6Y6F7pkvVA==", - "optional": true - }, - "node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - }, - "node_modules/optional-require": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/optional-require/-/optional-require-1.1.8.tgz", - "integrity": "sha512-jq83qaUb0wNg9Krv1c5OQ+58EK+vHde6aBPzLvPPqJm89UQWsvSuFy9X/OSNJnFeSOKo7btE0n8Nl2+nE+z5nA==", - "dependencies": { - "require-at": "^1.0.6" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "optional": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "optional": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "optional": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/pause-stream": { - "version": "0.0.11", - "resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz", - "integrity": "sha1-/lo0sMvOErWqaitAPuLnO2AvFEU=", - "dependencies": { - "through": "~2.3" - } - }, - "node_modules/process-nextick-args": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", - "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" - }, - "node_modules/readable-stream": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", - "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/readable-stream/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" - }, - "node_modules/require-at": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/require-at/-/require-at-1.0.6.tgz", - "integrity": "sha512-7i1auJbMUrXEAZCOQ0VNJgmcT2VOKPRl2YGJwgpHpC9CE91Mv4/4UYIUm4chGJaI381ZDq1JUicFii64Hapd8g==", - "engines": { - "node": ">=4" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/require-main-filename": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "optional": true - }, - "node_modules/reservoir": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/reservoir/-/reservoir-0.1.2.tgz", - "integrity": "sha1-8I6sFWSVEjA5y8XuBvP1iXnkVgU=" - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "node_modules/saslprep": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", - "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", - "optional": true, - "dependencies": { - "sparse-bitfield": "^3.0.3" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", - "optional": true - }, - "node_modules/sparse-bitfield": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", - "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", - "optional": true, - "dependencies": { - "memory-pager": "^1.0.2" - } - }, - "node_modules/split": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", - "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==", - "dependencies": { - "through": "2" - }, - "engines": { - "node": "*" - } - }, - "node_modules/ssh2": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.4.0.tgz", - "integrity": "sha512-XvXwcXKvS452DyQvCa6Ct+chpucwc/UyxgliYz+rWXJ3jDHdtBb9xgmxJdMmnIn5bpgGAEV3KaEsH98ZGPHqwg==", - "hasInstallScript": true, - "dependencies": { - "asn1": "^0.2.4", - "bcrypt-pbkdf": "^1.0.2" - }, - "engines": { - "node": ">=10.16.0" - }, - "optionalDependencies": { - "cpu-features": "0.0.2", - "nan": "^2.15.0" - } - }, - "node_modules/stream-combiner": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.2.2.tgz", - "integrity": "sha1-rsjLrBd7Vrb0+kec7YwZEs7lKFg=", - "dependencies": { - "duplexer": "~0.1.1", - "through": "~2.3.4" - } - }, - "node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "optional": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "optional": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" - }, - "node_modules/tunnel-ssh": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/tunnel-ssh/-/tunnel-ssh-4.1.6.tgz", - "integrity": "sha512-y7+x+T3F3rkx2Zov5Tk9DGfeEBVAdWU3A/91E0Dk5rrZ/VFIlpV2uhhRuaISJUdyG0N+Lcp1fXZMXz+ovPt5vA==", - "dependencies": { - "debug": "2.6.9", - "lodash.defaults": "^4.1.0", - "ssh2": "1.4.0" - } - }, - "node_modules/tweetnacl": { - "version": "0.14.5", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" - }, - "node_modules/which-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", - "optional": true - }, - "node_modules/wrap-ansi": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", - "optional": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/y18n": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", - "optional": true - }, - "node_modules/yargs": { - "version": "15.4.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", - "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", - "optional": true, - "dependencies": { - "cliui": "^6.0.0", - "decamelize": "^1.2.0", - "find-up": "^4.1.0", - "get-caller-file": "^2.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^4.2.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^18.1.2" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs-parser": { - "version": "18.1.3", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", - "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", - "optional": true, - "dependencies": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - }, - "engines": { - "node": ">=6" - } - } - } -} diff --git a/reverse_engineering/node_modules/ansi-regex/index.d.ts b/reverse_engineering/node_modules/ansi-regex/index.d.ts deleted file mode 100644 index 2dbf6af..0000000 --- a/reverse_engineering/node_modules/ansi-regex/index.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -declare namespace ansiRegex { - interface Options { - /** - Match only the first ANSI escape. - - @default false - */ - onlyFirst: boolean; - } -} - -/** -Regular expression for matching ANSI escape codes. - -@example -``` -import ansiRegex = require('ansi-regex'); - -ansiRegex().test('\u001B[4mcake\u001B[0m'); -//=> true - -ansiRegex().test('cake'); -//=> false - -'\u001B[4mcake\u001B[0m'.match(ansiRegex()); -//=> ['\u001B[4m', '\u001B[0m'] - -'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); -//=> ['\u001B[4m'] - -'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); -//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] -``` -*/ -declare function ansiRegex(options?: ansiRegex.Options): RegExp; - -export = ansiRegex; diff --git a/reverse_engineering/node_modules/ansi-regex/index.js b/reverse_engineering/node_modules/ansi-regex/index.js deleted file mode 100644 index 616ff83..0000000 --- a/reverse_engineering/node_modules/ansi-regex/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; diff --git a/reverse_engineering/node_modules/ansi-regex/license b/reverse_engineering/node_modules/ansi-regex/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/ansi-regex/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/ansi-regex/package.json b/reverse_engineering/node_modules/ansi-regex/package.json deleted file mode 100644 index 017f531..0000000 --- a/reverse_engineering/node_modules/ansi-regex/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "ansi-regex", - "version": "5.0.1", - "description": "Regular expression for matching ANSI escape codes", - "license": "MIT", - "repository": "chalk/ansi-regex", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd", - "view-supported": "node fixtures/view-codes.js" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "command-line", - "text", - "regex", - "regexp", - "re", - "match", - "test", - "find", - "pattern" - ], - "devDependencies": { - "ava": "^2.4.0", - "tsd": "^0.9.0", - "xo": "^0.25.3" - } -} diff --git a/reverse_engineering/node_modules/ansi-regex/readme.md b/reverse_engineering/node_modules/ansi-regex/readme.md deleted file mode 100644 index 4d848bc..0000000 --- a/reverse_engineering/node_modules/ansi-regex/readme.md +++ /dev/null @@ -1,78 +0,0 @@ -# ansi-regex - -> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) - - -## Install - -``` -$ npm install ansi-regex -``` - - -## Usage - -```js -const ansiRegex = require('ansi-regex'); - -ansiRegex().test('\u001B[4mcake\u001B[0m'); -//=> true - -ansiRegex().test('cake'); -//=> false - -'\u001B[4mcake\u001B[0m'.match(ansiRegex()); -//=> ['\u001B[4m', '\u001B[0m'] - -'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); -//=> ['\u001B[4m'] - -'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); -//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] -``` - - -## API - -### ansiRegex(options?) - -Returns a regex for matching ANSI escape codes. - -#### options - -Type: `object` - -##### onlyFirst - -Type: `boolean`
-Default: `false` *(Matches any ANSI escape codes in a string)* - -Match only the first ANSI escape. - - -## FAQ - -### Why do you test for codes not in the ECMA 48 standard? - -Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. - -On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. - - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - - ---- - -
diff --git a/reverse_engineering/node_modules/ansi-styles/index.d.ts b/reverse_engineering/node_modules/ansi-styles/index.d.ts deleted file mode 100644 index 44a907e..0000000 --- a/reverse_engineering/node_modules/ansi-styles/index.d.ts +++ /dev/null @@ -1,345 +0,0 @@ -declare type CSSColor = - | 'aliceblue' - | 'antiquewhite' - | 'aqua' - | 'aquamarine' - | 'azure' - | 'beige' - | 'bisque' - | 'black' - | 'blanchedalmond' - | 'blue' - | 'blueviolet' - | 'brown' - | 'burlywood' - | 'cadetblue' - | 'chartreuse' - | 'chocolate' - | 'coral' - | 'cornflowerblue' - | 'cornsilk' - | 'crimson' - | 'cyan' - | 'darkblue' - | 'darkcyan' - | 'darkgoldenrod' - | 'darkgray' - | 'darkgreen' - | 'darkgrey' - | 'darkkhaki' - | 'darkmagenta' - | 'darkolivegreen' - | 'darkorange' - | 'darkorchid' - | 'darkred' - | 'darksalmon' - | 'darkseagreen' - | 'darkslateblue' - | 'darkslategray' - | 'darkslategrey' - | 'darkturquoise' - | 'darkviolet' - | 'deeppink' - | 'deepskyblue' - | 'dimgray' - | 'dimgrey' - | 'dodgerblue' - | 'firebrick' - | 'floralwhite' - | 'forestgreen' - | 'fuchsia' - | 'gainsboro' - | 'ghostwhite' - | 'gold' - | 'goldenrod' - | 'gray' - | 'green' - | 'greenyellow' - | 'grey' - | 'honeydew' - | 'hotpink' - | 'indianred' - | 'indigo' - | 'ivory' - | 'khaki' - | 'lavender' - | 'lavenderblush' - | 'lawngreen' - | 'lemonchiffon' - | 'lightblue' - | 'lightcoral' - | 'lightcyan' - | 'lightgoldenrodyellow' - | 'lightgray' - | 'lightgreen' - | 'lightgrey' - | 'lightpink' - | 'lightsalmon' - | 'lightseagreen' - | 'lightskyblue' - | 'lightslategray' - | 'lightslategrey' - | 'lightsteelblue' - | 'lightyellow' - | 'lime' - | 'limegreen' - | 'linen' - | 'magenta' - | 'maroon' - | 'mediumaquamarine' - | 'mediumblue' - | 'mediumorchid' - | 'mediumpurple' - | 'mediumseagreen' - | 'mediumslateblue' - | 'mediumspringgreen' - | 'mediumturquoise' - | 'mediumvioletred' - | 'midnightblue' - | 'mintcream' - | 'mistyrose' - | 'moccasin' - | 'navajowhite' - | 'navy' - | 'oldlace' - | 'olive' - | 'olivedrab' - | 'orange' - | 'orangered' - | 'orchid' - | 'palegoldenrod' - | 'palegreen' - | 'paleturquoise' - | 'palevioletred' - | 'papayawhip' - | 'peachpuff' - | 'peru' - | 'pink' - | 'plum' - | 'powderblue' - | 'purple' - | 'rebeccapurple' - | 'red' - | 'rosybrown' - | 'royalblue' - | 'saddlebrown' - | 'salmon' - | 'sandybrown' - | 'seagreen' - | 'seashell' - | 'sienna' - | 'silver' - | 'skyblue' - | 'slateblue' - | 'slategray' - | 'slategrey' - | 'snow' - | 'springgreen' - | 'steelblue' - | 'tan' - | 'teal' - | 'thistle' - | 'tomato' - | 'turquoise' - | 'violet' - | 'wheat' - | 'white' - | 'whitesmoke' - | 'yellow' - | 'yellowgreen'; - -declare namespace ansiStyles { - interface ColorConvert { - /** - The RGB color space. - - @param red - (`0`-`255`) - @param green - (`0`-`255`) - @param blue - (`0`-`255`) - */ - rgb(red: number, green: number, blue: number): string; - - /** - The RGB HEX color space. - - @param hex - A hexadecimal string containing RGB data. - */ - hex(hex: string): string; - - /** - @param keyword - A CSS color name. - */ - keyword(keyword: CSSColor): string; - - /** - The HSL color space. - - @param hue - (`0`-`360`) - @param saturation - (`0`-`100`) - @param lightness - (`0`-`100`) - */ - hsl(hue: number, saturation: number, lightness: number): string; - - /** - The HSV color space. - - @param hue - (`0`-`360`) - @param saturation - (`0`-`100`) - @param value - (`0`-`100`) - */ - hsv(hue: number, saturation: number, value: number): string; - - /** - The HSV color space. - - @param hue - (`0`-`360`) - @param whiteness - (`0`-`100`) - @param blackness - (`0`-`100`) - */ - hwb(hue: number, whiteness: number, blackness: number): string; - - /** - Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. - */ - ansi(ansi: number): string; - - /** - Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. - */ - ansi256(ansi: number): string; - } - - interface CSPair { - /** - The ANSI terminal control sequence for starting this style. - */ - readonly open: string; - - /** - The ANSI terminal control sequence for ending this style. - */ - readonly close: string; - } - - interface ColorBase { - readonly ansi: ColorConvert; - readonly ansi256: ColorConvert; - readonly ansi16m: ColorConvert; - - /** - The ANSI terminal control sequence for ending this color. - */ - readonly close: string; - } - - interface Modifier { - /** - Resets the current color chain. - */ - readonly reset: CSPair; - - /** - Make text bold. - */ - readonly bold: CSPair; - - /** - Emitting only a small amount of light. - */ - readonly dim: CSPair; - - /** - Make text italic. (Not widely supported) - */ - readonly italic: CSPair; - - /** - Make text underline. (Not widely supported) - */ - readonly underline: CSPair; - - /** - Inverse background and foreground colors. - */ - readonly inverse: CSPair; - - /** - Prints the text, but makes it invisible. - */ - readonly hidden: CSPair; - - /** - Puts a horizontal line through the center of the text. (Not widely supported) - */ - readonly strikethrough: CSPair; - } - - interface ForegroundColor { - readonly black: CSPair; - readonly red: CSPair; - readonly green: CSPair; - readonly yellow: CSPair; - readonly blue: CSPair; - readonly cyan: CSPair; - readonly magenta: CSPair; - readonly white: CSPair; - - /** - Alias for `blackBright`. - */ - readonly gray: CSPair; - - /** - Alias for `blackBright`. - */ - readonly grey: CSPair; - - readonly blackBright: CSPair; - readonly redBright: CSPair; - readonly greenBright: CSPair; - readonly yellowBright: CSPair; - readonly blueBright: CSPair; - readonly cyanBright: CSPair; - readonly magentaBright: CSPair; - readonly whiteBright: CSPair; - } - - interface BackgroundColor { - readonly bgBlack: CSPair; - readonly bgRed: CSPair; - readonly bgGreen: CSPair; - readonly bgYellow: CSPair; - readonly bgBlue: CSPair; - readonly bgCyan: CSPair; - readonly bgMagenta: CSPair; - readonly bgWhite: CSPair; - - /** - Alias for `bgBlackBright`. - */ - readonly bgGray: CSPair; - - /** - Alias for `bgBlackBright`. - */ - readonly bgGrey: CSPair; - - readonly bgBlackBright: CSPair; - readonly bgRedBright: CSPair; - readonly bgGreenBright: CSPair; - readonly bgYellowBright: CSPair; - readonly bgBlueBright: CSPair; - readonly bgCyanBright: CSPair; - readonly bgMagentaBright: CSPair; - readonly bgWhiteBright: CSPair; - } -} - -declare const ansiStyles: { - readonly modifier: ansiStyles.Modifier; - readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; - readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; - readonly codes: ReadonlyMap; -} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; - -export = ansiStyles; diff --git a/reverse_engineering/node_modules/ansi-styles/index.js b/reverse_engineering/node_modules/ansi-styles/index.js deleted file mode 100644 index 5d82581..0000000 --- a/reverse_engineering/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,163 +0,0 @@ -'use strict'; - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = require('color-convert'); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); diff --git a/reverse_engineering/node_modules/ansi-styles/license b/reverse_engineering/node_modules/ansi-styles/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/ansi-styles/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/ansi-styles/package.json b/reverse_engineering/node_modules/ansi-styles/package.json deleted file mode 100644 index 7539328..0000000 --- a/reverse_engineering/node_modules/ansi-styles/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "ansi-styles", - "version": "4.3.0", - "description": "ANSI escape codes for styling strings in the terminal", - "license": "MIT", - "repository": "chalk/ansi-styles", - "funding": "https://github.com/chalk/ansi-styles?sponsor=1", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd", - "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "color-convert": "^2.0.1" - }, - "devDependencies": { - "@types/color-convert": "^1.9.0", - "ava": "^2.3.0", - "svg-term-cli": "^2.1.1", - "tsd": "^0.11.0", - "xo": "^0.25.3" - } -} diff --git a/reverse_engineering/node_modules/ansi-styles/readme.md b/reverse_engineering/node_modules/ansi-styles/readme.md deleted file mode 100644 index 24883de..0000000 --- a/reverse_engineering/node_modules/ansi-styles/readme.md +++ /dev/null @@ -1,152 +0,0 @@ -# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) - -> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal - -You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. - - - -## Install - -``` -$ npm install ansi-styles -``` - -## Usage - -```js -const style = require('ansi-styles'); - -console.log(`${style.green.open}Hello world!${style.green.close}`); - - -// Color conversion between 16/256/truecolor -// NOTE: If conversion goes to 16 colors or 256 colors, the original color -// may be degraded to fit that color palette. This means terminals -// that do not support 16 million colors will best-match the -// original color. -console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); -console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); -console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); -``` - -## API - -Each style has an `open` and `close` property. - -## Styles - -### Modifiers - -- `reset` -- `bold` -- `dim` -- `italic` *(Not widely supported)* -- `underline` -- `inverse` -- `hidden` -- `strikethrough` *(Not widely supported)* - -### Colors - -- `black` -- `red` -- `green` -- `yellow` -- `blue` -- `magenta` -- `cyan` -- `white` -- `blackBright` (alias: `gray`, `grey`) -- `redBright` -- `greenBright` -- `yellowBright` -- `blueBright` -- `magentaBright` -- `cyanBright` -- `whiteBright` - -### Background colors - -- `bgBlack` -- `bgRed` -- `bgGreen` -- `bgYellow` -- `bgBlue` -- `bgMagenta` -- `bgCyan` -- `bgWhite` -- `bgBlackBright` (alias: `bgGray`, `bgGrey`) -- `bgRedBright` -- `bgGreenBright` -- `bgYellowBright` -- `bgBlueBright` -- `bgMagentaBright` -- `bgCyanBright` -- `bgWhiteBright` - -## Advanced usage - -By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - -- `style.modifier` -- `style.color` -- `style.bgColor` - -###### Example - -```js -console.log(style.color.green.open); -``` - -Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. - -###### Example - -```js -console.log(style.codes.get(36)); -//=> 39 -``` - -## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) - -`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. - -The following color spaces from `color-convert` are supported: - -- `rgb` -- `hex` -- `keyword` -- `hsl` -- `hsv` -- `hwb` -- `ansi` -- `ansi256` - -To use these, call the associated conversion function with the intended output, for example: - -```js -style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code -style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code - -style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code -style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code - -style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code -style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code -``` - -## Related - -- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - -## For enterprise - -Available as part of the Tidelift Subscription. - -The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/reverse_engineering/node_modules/asn1/Jenkinsfile b/reverse_engineering/node_modules/asn1/Jenkinsfile deleted file mode 100644 index d1b4593..0000000 --- a/reverse_engineering/node_modules/asn1/Jenkinsfile +++ /dev/null @@ -1,65 +0,0 @@ -@Library('jenkins-joylib@v1.0.8') _ - -pipeline { - - agent none - - options { - buildDiscarder(logRotator(numToKeepStr: '45')) - timestamps() - } - - stages { - stage('top') { - parallel { - stage('v4-zone') { - agent { - label joyCommonLabels(image_ver: '15.4.1') - } - tools { - nodejs 'sdcnode-v4-zone' - } - stages { - stage('check') { - steps{ - sh('make check') - } - } - stage('test') { - steps{ - sh('make test') - } - } - } - } - - stage('v6-zone64') { - agent { - label joyCommonLabels(image_ver: '18.4.0') - } - tools { - nodejs 'sdcnode-v6-zone64' - } - stages { - stage('check') { - steps{ - sh('make check') - } - } - stage('test') { - steps{ - sh('make test') - } - } - } - } - } - } - } - - post { - always { - joySlackNotifications() - } - } -} diff --git a/reverse_engineering/node_modules/asn1/LICENSE b/reverse_engineering/node_modules/asn1/LICENSE deleted file mode 100644 index 9b5dcdb..0000000 --- a/reverse_engineering/node_modules/asn1/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011 Mark Cavage, All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE diff --git a/reverse_engineering/node_modules/asn1/README.md b/reverse_engineering/node_modules/asn1/README.md deleted file mode 100644 index 2208210..0000000 --- a/reverse_engineering/node_modules/asn1/README.md +++ /dev/null @@ -1,50 +0,0 @@ -node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS. -Currently BER encoding is supported; at some point I'll likely have to do DER. - -## Usage - -Mostly, if you're *actually* needing to read and write ASN.1, you probably don't -need this readme to explain what and why. If you have no idea what ASN.1 is, -see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc - -The source is pretty much self-explanatory, and has read/write methods for the -common types out there. - -### Decoding - -The following reads an ASN.1 sequence with a boolean. - - var Ber = require('asn1').Ber; - - var reader = new Ber.Reader(Buffer.from([0x30, 0x03, 0x01, 0x01, 0xff])); - - reader.readSequence(); - console.log('Sequence len: ' + reader.length); - if (reader.peek() === Ber.Boolean) - console.log(reader.readBoolean()); - -### Encoding - -The following generates the same payload as above. - - var Ber = require('asn1').Ber; - - var writer = new Ber.Writer(); - - writer.startSequence(); - writer.writeBoolean(true); - writer.endSequence(); - - console.log(writer.buffer); - -## Installation - - npm install asn1 - -## License - -MIT. - -## Bugs - -See . diff --git a/reverse_engineering/node_modules/asn1/lib/ber/errors.js b/reverse_engineering/node_modules/asn1/lib/ber/errors.js deleted file mode 100644 index 4557b8a..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/errors.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - - -module.exports = { - - newInvalidAsn1Error: function (msg) { - var e = new Error(); - e.name = 'InvalidAsn1Error'; - e.message = msg || ''; - return e; - } - -}; diff --git a/reverse_engineering/node_modules/asn1/lib/ber/index.js b/reverse_engineering/node_modules/asn1/lib/ber/index.js deleted file mode 100644 index 387d132..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/index.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -var errors = require('./errors'); -var types = require('./types'); - -var Reader = require('./reader'); -var Writer = require('./writer'); - - -// --- Exports - -module.exports = { - - Reader: Reader, - - Writer: Writer - -}; - -for (var t in types) { - if (types.hasOwnProperty(t)) - module.exports[t] = types[t]; -} -for (var e in errors) { - if (errors.hasOwnProperty(e)) - module.exports[e] = errors[e]; -} diff --git a/reverse_engineering/node_modules/asn1/lib/ber/reader.js b/reverse_engineering/node_modules/asn1/lib/ber/reader.js deleted file mode 100644 index 8a7e4ca..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/reader.js +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -var assert = require('assert'); -var Buffer = require('safer-buffer').Buffer; - -var ASN1 = require('./types'); -var errors = require('./errors'); - - -// --- Globals - -var newInvalidAsn1Error = errors.newInvalidAsn1Error; - - - -// --- API - -function Reader(data) { - if (!data || !Buffer.isBuffer(data)) - throw new TypeError('data must be a node Buffer'); - - this._buf = data; - this._size = data.length; - - // These hold the "current" state - this._len = 0; - this._offset = 0; -} - -Object.defineProperty(Reader.prototype, 'length', { - enumerable: true, - get: function () { return (this._len); } -}); - -Object.defineProperty(Reader.prototype, 'offset', { - enumerable: true, - get: function () { return (this._offset); } -}); - -Object.defineProperty(Reader.prototype, 'remain', { - get: function () { return (this._size - this._offset); } -}); - -Object.defineProperty(Reader.prototype, 'buffer', { - get: function () { return (this._buf.slice(this._offset)); } -}); - - -/** - * Reads a single byte and advances offset; you can pass in `true` to make this - * a "peek" operation (i.e., get the byte, but don't advance the offset). - * - * @param {Boolean} peek true means don't move offset. - * @return {Number} the next byte, null if not enough data. - */ -Reader.prototype.readByte = function (peek) { - if (this._size - this._offset < 1) - return null; - - var b = this._buf[this._offset] & 0xff; - - if (!peek) - this._offset += 1; - - return b; -}; - - -Reader.prototype.peek = function () { - return this.readByte(true); -}; - - -/** - * Reads a (potentially) variable length off the BER buffer. This call is - * not really meant to be called directly, as callers have to manipulate - * the internal buffer afterwards. - * - * As a result of this call, you can call `Reader.length`, until the - * next thing called that does a readLength. - * - * @return {Number} the amount of offset to advance the buffer. - * @throws {InvalidAsn1Error} on bad ASN.1 - */ -Reader.prototype.readLength = function (offset) { - if (offset === undefined) - offset = this._offset; - - if (offset >= this._size) - return null; - - var lenB = this._buf[offset++] & 0xff; - if (lenB === null) - return null; - - if ((lenB & 0x80) === 0x80) { - lenB &= 0x7f; - - if (lenB === 0) - throw newInvalidAsn1Error('Indefinite length not supported'); - - if (lenB > 4) - throw newInvalidAsn1Error('encoding too long'); - - if (this._size - offset < lenB) - return null; - - this._len = 0; - for (var i = 0; i < lenB; i++) - this._len = (this._len << 8) + (this._buf[offset++] & 0xff); - - } else { - // Wasn't a variable length - this._len = lenB; - } - - return offset; -}; - - -/** - * Parses the next sequence in this BER buffer. - * - * To get the length of the sequence, call `Reader.length`. - * - * @return {Number} the sequence's tag. - */ -Reader.prototype.readSequence = function (tag) { - var seq = this.peek(); - if (seq === null) - return null; - if (tag !== undefined && tag !== seq) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + seq.toString(16)); - - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; - - this._offset = o; - return seq; -}; - - -Reader.prototype.readInt = function () { - return this._readTag(ASN1.Integer); -}; - - -Reader.prototype.readBoolean = function () { - return (this._readTag(ASN1.Boolean) === 0 ? false : true); -}; - - -Reader.prototype.readEnumeration = function () { - return this._readTag(ASN1.Enumeration); -}; - - -Reader.prototype.readString = function (tag, retbuf) { - if (!tag) - tag = ASN1.OctetString; - - var b = this.peek(); - if (b === null) - return null; - - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); - - var o = this.readLength(this._offset + 1); // stored in `length` - - if (o === null) - return null; - - if (this.length > this._size - o) - return null; - - this._offset = o; - - if (this.length === 0) - return retbuf ? Buffer.alloc(0) : ''; - - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; - - return retbuf ? str : str.toString('utf8'); -}; - -Reader.prototype.readOID = function (tag) { - if (!tag) - tag = ASN1.OID; - - var b = this.readString(tag, true); - if (b === null) - return null; - - var values = []; - var value = 0; - - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 0xff; - - value <<= 7; - value += byte & 0x7f; - if ((byte & 0x80) === 0) { - values.push(value); - value = 0; - } - } - - value = values.shift(); - values.unshift(value % 40); - values.unshift((value / 40) >> 0); - - return values.join('.'); -}; - - -Reader.prototype._readTag = function (tag) { - assert.ok(tag !== undefined); - - var b = this.peek(); - - if (b === null) - return null; - - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); - - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; - - if (this.length > 4) - throw newInvalidAsn1Error('Integer too long: ' + this.length); - - if (this.length > this._size - o) - return null; - this._offset = o; - - var fb = this._buf[this._offset]; - var value = 0; - - for (var i = 0; i < this.length; i++) { - value <<= 8; - value |= (this._buf[this._offset++] & 0xff); - } - - if ((fb & 0x80) === 0x80 && i !== 4) - value -= (1 << (i * 8)); - - return value >> 0; -}; - - - -// --- Exported API - -module.exports = Reader; diff --git a/reverse_engineering/node_modules/asn1/lib/ber/types.js b/reverse_engineering/node_modules/asn1/lib/ber/types.js deleted file mode 100644 index 8aea000..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/types.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - - -module.exports = { - EOC: 0, - Boolean: 1, - Integer: 2, - BitString: 3, - OctetString: 4, - Null: 5, - OID: 6, - ObjectDescriptor: 7, - External: 8, - Real: 9, // float - Enumeration: 10, - PDV: 11, - Utf8String: 12, - RelativeOID: 13, - Sequence: 16, - Set: 17, - NumericString: 18, - PrintableString: 19, - T61String: 20, - VideotexString: 21, - IA5String: 22, - UTCTime: 23, - GeneralizedTime: 24, - GraphicString: 25, - VisibleString: 26, - GeneralString: 28, - UniversalString: 29, - CharacterString: 30, - BMPString: 31, - Constructor: 32, - Context: 128 -}; diff --git a/reverse_engineering/node_modules/asn1/lib/ber/writer.js b/reverse_engineering/node_modules/asn1/lib/ber/writer.js deleted file mode 100644 index 3515acf..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/writer.js +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -var assert = require('assert'); -var Buffer = require('safer-buffer').Buffer; -var ASN1 = require('./types'); -var errors = require('./errors'); - - -// --- Globals - -var newInvalidAsn1Error = errors.newInvalidAsn1Error; - -var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 -}; - - -// --- Helpers - -function merge(from, to) { - assert.ok(from); - assert.equal(typeof (from), 'object'); - assert.ok(to); - assert.equal(typeof (to), 'object'); - - var keys = Object.getOwnPropertyNames(from); - keys.forEach(function (key) { - if (to[key]) - return; - - var value = Object.getOwnPropertyDescriptor(from, key); - Object.defineProperty(to, key, value); - }); - - return to; -} - - - -// --- API - -function Writer(options) { - options = merge(DEFAULT_OPTS, options || {}); - - this._buf = Buffer.alloc(options.size || 1024); - this._size = this._buf.length; - this._offset = 0; - this._options = options; - - // A list of offsets in the buffer where we need to insert - // sequence tag/len pairs. - this._seq = []; -} - -Object.defineProperty(Writer.prototype, 'buffer', { - get: function () { - if (this._seq.length) - throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); - - return (this._buf.slice(0, this._offset)); - } -}); - -Writer.prototype.writeByte = function (b) { - if (typeof (b) !== 'number') - throw new TypeError('argument must be a Number'); - - this._ensure(1); - this._buf[this._offset++] = b; -}; - - -Writer.prototype.writeInt = function (i, tag) { - if (typeof (i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof (tag) !== 'number') - tag = ASN1.Integer; - - var sz = 4; - - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && - (sz > 1)) { - sz--; - i <<= 8; - } - - if (sz > 4) - throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; - - while (sz-- > 0) { - this._buf[this._offset++] = ((i & 0xff000000) >>> 24); - i <<= 8; - } - -}; - - -Writer.prototype.writeNull = function () { - this.writeByte(ASN1.Null); - this.writeByte(0x00); -}; - - -Writer.prototype.writeEnumeration = function (i, tag) { - if (typeof (i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof (tag) !== 'number') - tag = ASN1.Enumeration; - - return this.writeInt(i, tag); -}; - - -Writer.prototype.writeBoolean = function (b, tag) { - if (typeof (b) !== 'boolean') - throw new TypeError('argument must be a Boolean'); - if (typeof (tag) !== 'number') - tag = ASN1.Boolean; - - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 0x01; - this._buf[this._offset++] = b ? 0xff : 0x00; -}; - - -Writer.prototype.writeString = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); - if (typeof (tag) !== 'number') - tag = ASN1.OctetString; - - var len = Buffer.byteLength(s); - this.writeByte(tag); - this.writeLength(len); - if (len) { - this._ensure(len); - this._buf.write(s, this._offset); - this._offset += len; - } -}; - - -Writer.prototype.writeBuffer = function (buf, tag) { - if (typeof (tag) !== 'number') - throw new TypeError('tag must be a number'); - if (!Buffer.isBuffer(buf)) - throw new TypeError('argument must be a buffer'); - - this.writeByte(tag); - this.writeLength(buf.length); - this._ensure(buf.length); - buf.copy(this._buf, this._offset, 0, buf.length); - this._offset += buf.length; -}; - - -Writer.prototype.writeStringArray = function (strings) { - if ((!strings instanceof Array)) - throw new TypeError('argument must be an Array[String]'); - - var self = this; - strings.forEach(function (s) { - self.writeString(s); - }); -}; - -// This is really to solve DER cases, but whatever for now -Writer.prototype.writeOID = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string'); - if (typeof (tag) !== 'number') - tag = ASN1.OID; - - if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) - throw new Error('argument is not a valid OID string'); - - function encodeOctet(bytes, octet) { - if (octet < 128) { - bytes.push(octet); - } else if (octet < 16384) { - bytes.push((octet >>> 7) | 0x80); - bytes.push(octet & 0x7F); - } else if (octet < 2097152) { - bytes.push((octet >>> 14) | 0x80); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else if (octet < 268435456) { - bytes.push((octet >>> 21) | 0x80); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else { - bytes.push(((octet >>> 28) | 0x80) & 0xFF); - bytes.push(((octet >>> 21) | 0x80) & 0xFF); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } - } - - var tmp = s.split('.'); - var bytes = []; - bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); - tmp.slice(2).forEach(function (b) { - encodeOctet(bytes, parseInt(b, 10)); - }); - - var self = this; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function (b) { - self.writeByte(b); - }); -}; - - -Writer.prototype.writeLength = function (len) { - if (typeof (len) !== 'number') - throw new TypeError('argument must be a Number'); - - this._ensure(4); - - if (len <= 0x7f) { - this._buf[this._offset++] = len; - } else if (len <= 0xff) { - this._buf[this._offset++] = 0x81; - this._buf[this._offset++] = len; - } else if (len <= 0xffff) { - this._buf[this._offset++] = 0x82; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else if (len <= 0xffffff) { - this._buf[this._offset++] = 0x83; - this._buf[this._offset++] = len >> 16; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else { - throw newInvalidAsn1Error('Length too long (> 4 bytes)'); - } -}; - -Writer.prototype.startSequence = function (tag) { - if (typeof (tag) !== 'number') - tag = ASN1.Sequence | ASN1.Constructor; - - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; -}; - - -Writer.prototype.endSequence = function () { - var seq = this._seq.pop(); - var start = seq + 3; - var len = this._offset - start; - - if (len <= 0x7f) { - this._shift(start, len, -2); - this._buf[seq] = len; - } else if (len <= 0xff) { - this._shift(start, len, -1); - this._buf[seq] = 0x81; - this._buf[seq + 1] = len; - } else if (len <= 0xffff) { - this._buf[seq] = 0x82; - this._buf[seq + 1] = len >> 8; - this._buf[seq + 2] = len; - } else if (len <= 0xffffff) { - this._shift(start, len, 1); - this._buf[seq] = 0x83; - this._buf[seq + 1] = len >> 16; - this._buf[seq + 2] = len >> 8; - this._buf[seq + 3] = len; - } else { - throw newInvalidAsn1Error('Sequence too long'); - } -}; - - -Writer.prototype._shift = function (start, len, shift) { - assert.ok(start !== undefined); - assert.ok(len !== undefined); - assert.ok(shift); - - this._buf.copy(this._buf, start + shift, start, start + len); - this._offset += shift; -}; - -Writer.prototype._ensure = function (len) { - assert.ok(len); - - if (this._size - this._offset < len) { - var sz = this._size * this._options.growthFactor; - if (sz - this._offset < len) - sz += len; - - var buf = Buffer.alloc(sz); - - this._buf.copy(buf, 0, 0, this._offset); - this._buf = buf; - this._size = sz; - } -}; - - - -// --- Exported API - -module.exports = Writer; diff --git a/reverse_engineering/node_modules/asn1/lib/index.js b/reverse_engineering/node_modules/asn1/lib/index.js deleted file mode 100644 index ede3ab2..0000000 --- a/reverse_engineering/node_modules/asn1/lib/index.js +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -// If you have no idea what ASN.1 or BER is, see this: -// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc - -var Ber = require('./ber/index'); - - - -// --- Exported API - -module.exports = { - - Ber: Ber, - - BerReader: Ber.Reader, - - BerWriter: Ber.Writer - -}; diff --git a/reverse_engineering/node_modules/asn1/package.json b/reverse_engineering/node_modules/asn1/package.json deleted file mode 100644 index e31cce5..0000000 --- a/reverse_engineering/node_modules/asn1/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "author": "Joyent (joyent.com)", - "contributors": [ - "Mark Cavage ", - "David Gwynne ", - "Yunong Xiao ", - "Alex Wilson " - ], - "name": "asn1", - "description": "Contains parsers and serializers for ASN.1 (currently BER only)", - "version": "0.2.6", - "repository": { - "type": "git", - "url": "https://github.com/joyent/node-asn1.git" - }, - "main": "lib/index.js", - "dependencies": { - "safer-buffer": "~2.1.0" - }, - "devDependencies": { - "istanbul": "^0.3.6", - "faucet": "0.0.1", - "tape": "^3.5.0", - "eslint": "2.13.1", - "eslint-plugin-joyent": "~1.3.0" - }, - "scripts": { - "test": "./node_modules/.bin/tape ./test/ber/*.test.js" - }, - "license": "MIT" -} diff --git a/reverse_engineering/node_modules/base64-js/LICENSE b/reverse_engineering/node_modules/base64-js/LICENSE deleted file mode 100644 index 6d52b8a..0000000 --- a/reverse_engineering/node_modules/base64-js/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jameson Little - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/base64-js/README.md b/reverse_engineering/node_modules/base64-js/README.md deleted file mode 100644 index b42a48f..0000000 --- a/reverse_engineering/node_modules/base64-js/README.md +++ /dev/null @@ -1,34 +0,0 @@ -base64-js -========= - -`base64-js` does basic base64 encoding/decoding in pure JS. - -[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) - -Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. - -Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. - -## install - -With [npm](https://npmjs.org) do: - -`npm install base64-js` and `var base64js = require('base64-js')` - -For use in web browsers do: - -`` - -[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) - -## methods - -`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. - -* `byteLength` - Takes a base64 string and returns length of byte array -* `toByteArray` - Takes a base64 string and returns a byte array -* `fromByteArray` - Takes a byte array and returns a base64 string - -## license - -MIT diff --git a/reverse_engineering/node_modules/base64-js/base64js.min.js b/reverse_engineering/node_modules/base64-js/base64js.min.js deleted file mode 100644 index 908ac83..0000000 --- a/reverse_engineering/node_modules/base64-js/base64js.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -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 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - 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) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} diff --git a/reverse_engineering/node_modules/base64-js/package.json b/reverse_engineering/node_modules/base64-js/package.json deleted file mode 100644 index c3972e3..0000000 --- a/reverse_engineering/node_modules/base64-js/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "base64-js", - "description": "Base64 encoding/decoding in pure JS", - "version": "1.5.1", - "author": "T. Jameson Little ", - "typings": "index.d.ts", - "bugs": { - "url": "https://github.com/beatgammit/base64-js/issues" - }, - "devDependencies": { - "babel-minify": "^0.5.1", - "benchmark": "^2.1.4", - "browserify": "^16.3.0", - "standard": "*", - "tape": "4.x" - }, - "homepage": "https://github.com/beatgammit/base64-js", - "keywords": [ - "base64" - ], - "license": "MIT", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/beatgammit/base64-js.git" - }, - "scripts": { - "build": "browserify -s base64js -r ./ | minify > base64js.min.js", - "lint": "standard", - "test": "npm run lint && npm run unit", - "unit": "tape test/*.js" - }, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] -} diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/CONTRIBUTING.md b/reverse_engineering/node_modules/bcrypt-pbkdf/CONTRIBUTING.md deleted file mode 100644 index 401d34e..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +++ /dev/null @@ -1,13 +0,0 @@ -# Contributing - -This repository uses [cr.joyent.us](https://cr.joyent.us) (Gerrit) for new -changes. Anyone can submit changes. To get started, see the [cr.joyent.us user -guide](https://github.com/joyent/joyent-gerrit/blob/master/docs/user/README.md). -This repo does not use GitHub pull requests. - -See the [Joyent Engineering -Guidelines](https://github.com/joyent/eng/blob/master/docs/index.md) for general -best practices expected in this repository. - -If you're changing something non-trivial or user-facing, you may want to submit -an issue first. diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/LICENSE b/reverse_engineering/node_modules/bcrypt-pbkdf/LICENSE deleted file mode 100644 index fc58d2a..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/LICENSE +++ /dev/null @@ -1,66 +0,0 @@ -The Blowfish portions are under the following license: - -Blowfish block cipher for OpenBSD -Copyright 1997 Niels Provos -All rights reserved. - -Implementation advice by David Mazieres . - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -The bcrypt_pbkdf portions are under the following license: - -Copyright (c) 2013 Ted Unangst - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - - - -Performance improvements (Javascript-specific): - -Copyright 2016, Joyent Inc -Author: Alex Wilson - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/README.md b/reverse_engineering/node_modules/bcrypt-pbkdf/README.md deleted file mode 100644 index 7551f33..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/README.md +++ /dev/null @@ -1,45 +0,0 @@ -Port of the OpenBSD `bcrypt_pbkdf` function to pure Javascript. `npm`-ified -version of [Devi Mandiri's port](https://github.com/devi/tmp/blob/master/js/bcrypt_pbkdf.js), -with some minor performance improvements. The code is copied verbatim (and -un-styled) from Devi's work. - -This product includes software developed by Niels Provos. - -## API - -### `bcrypt_pbkdf.pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds)` - -Derive a cryptographic key of arbitrary length from a given password and salt, -using the OpenBSD `bcrypt_pbkdf` function. This is a combination of Blowfish and -SHA-512. - -See [this article](http://www.tedunangst.com/flak/post/bcrypt-pbkdf) for -further information. - -Parameters: - - * `pass`, a Uint8Array of length `passlen` - * `passlen`, an integer Number - * `salt`, a Uint8Array of length `saltlen` - * `saltlen`, an integer Number - * `key`, a Uint8Array of length `keylen`, will be filled with output - * `keylen`, an integer Number - * `rounds`, an integer Number, number of rounds of the PBKDF to run - -### `bcrypt_pbkdf.hash(sha2pass, sha2salt, out)` - -Calculate a Blowfish hash, given SHA2-512 output of a password and salt. Used as -part of the inner round function in the PBKDF. - -Parameters: - - * `sha2pass`, a Uint8Array of length 64 - * `sha2salt`, a Uint8Array of length 64 - * `out`, a Uint8Array of length 32, will be filled with output - -## License - -This source form is a 1:1 port from the OpenBSD `blowfish.c` and `bcrypt_pbkdf.c`. -As a result, it retains the original copyright and license. The two files are -under slightly different (but compatible) licenses, and are here combined in -one file. For each of the full license texts see `LICENSE`. diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/index.js b/reverse_engineering/node_modules/bcrypt-pbkdf/index.js deleted file mode 100644 index b1b5ad4..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/index.js +++ /dev/null @@ -1,556 +0,0 @@ -'use strict'; - -var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash; - -/* - * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a - * result, it retains the original copyright and license. The two files are - * under slightly different (but compatible) licenses, and are here combined in - * one file. - * - * Credit for the actual porting work goes to: - * Devi Mandiri - */ - -/* - * The Blowfish portions are under the following license: - * - * Blowfish block cipher for OpenBSD - * Copyright 1997 Niels Provos - * All rights reserved. - * - * Implementation advice by David Mazieres . - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * The bcrypt_pbkdf portions are under the following license: - * - * Copyright (c) 2013 Ted Unangst - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* - * Performance improvements (Javascript-specific): - * - * Copyright 2016, Joyent Inc - * Author: Alex Wilson - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -// Ported from OpenBSD bcrypt_pbkdf.c v1.9 - -var BLF_J = 0; - -var Blowfish = function() { - this.S = [ - new Uint32Array([ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, - 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, - 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, - 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, - 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, - 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, - 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, - 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, - 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, - 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, - 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, - 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, - 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, - 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, - 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, - 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, - 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, - 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, - 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, - 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, - 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, - 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, - 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, - 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, - 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, - 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, - 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, - 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, - 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, - 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, - 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, - 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, - 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, - 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, - 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), - new Uint32Array([ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, - 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, - 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, - 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, - 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, - 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, - 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, - 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, - 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, - 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, - 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, - 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, - 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, - 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, - 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, - 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, - 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, - 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, - 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, - 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, - 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, - 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, - 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, - 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, - 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, - 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, - 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, - 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, - 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, - 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, - 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, - 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, - 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, - 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), - new Uint32Array([ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, - 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, - 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, - 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, - 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, - 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, - 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, - 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, - 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, - 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, - 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, - 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, - 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, - 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, - 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, - 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, - 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, - 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, - 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, - 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, - 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, - 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, - 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, - 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, - 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, - 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, - 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, - 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, - 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, - 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, - 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, - 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, - 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, - 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), - new Uint32Array([ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, - 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, - 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, - 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, - 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, - 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, - 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, - 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, - 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, - 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, - 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, - 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, - 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, - 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, - 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, - 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, - 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, - 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, - 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, - 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, - 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, - 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, - 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, - 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, - 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, - 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, - 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, - 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, - 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, - 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, - 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, - 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, - 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, - 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, - 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) - ]; - this.P = new Uint32Array([ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, - 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, - 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, - 0x9216d5d9, 0x8979fb1b]); -}; - -function F(S, x8, i) { - return (((S[0][x8[i+3]] + - S[1][x8[i+2]]) ^ - S[2][x8[i+1]]) + - S[3][x8[i]]); -}; - -Blowfish.prototype.encipher = function(x, x8) { - if (x8 === undefined) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - x[0] ^= this.P[0]; - for (var i = 1; i < 16; i += 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; -}; - -Blowfish.prototype.decipher = function(x) { - var x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - x[0] ^= this.P[17]; - for (var i = 16; i > 0; i -= 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; -}; - -function stream2word(data, databytes){ - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = (temp << 8) | data[BLF_J]; - } - return temp; -}; - -Blowfish.prototype.expand0state = function(key, keybytes) { - var d = new Uint32Array(2), i, k; - var d8 = new Uint8Array(d.buffer); - - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - BLF_J = 0; - - for (i = 0; i < 18; i += 2) { - this.encipher(d, d8); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } - - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - this.encipher(d, d8); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } -}; - -Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; - - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - - for (i = 0, BLF_J = 0; i < 18; i += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } - - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } - BLF_J = 0; -}; - -Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i*2)); - } -}; - -Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i*2)); - } -}; - -var BCRYPT_BLOCKS = 8, - BCRYPT_HASHSIZE = 32; - -function bcrypt_hash(sha2pass, sha2salt, out) { - var state = new Blowfish(), - cdata = new Uint32Array(BCRYPT_BLOCKS), i, - ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, - 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, - 105,116,101]); //"OxychromaticBlowfishSwatDynamite" - - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); - } - - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); - - for (i = 0; i < BCRYPT_BLOCKS; i++) { - out[4*i+3] = cdata[i] >>> 24; - out[4*i+2] = cdata[i] >>> 16; - out[4*i+1] = cdata[i] >>> 8; - out[4*i+0] = cdata[i]; - } -}; - -function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { - var sha2pass = new Uint8Array(64), - sha2salt = new Uint8Array(64), - out = new Uint8Array(BCRYPT_HASHSIZE), - tmpout = new Uint8Array(BCRYPT_HASHSIZE), - countsalt = new Uint8Array(saltlen+4), - i, j, amt, stride, dest, count, - origkeylen = keylen; - - if (rounds < 1) - return -1; - if (passlen === 0 || saltlen === 0 || keylen === 0 || - keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) - return -1; - - stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); - amt = Math.floor((keylen + stride - 1) / stride); - - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; - - crypto_hash_sha512(sha2pass, pass, passlen); - - for (count = 1; keylen > 0; count++) { - countsalt[saltlen+0] = count >>> 24; - countsalt[saltlen+1] = count >>> 16; - countsalt[saltlen+2] = count >>> 8; - countsalt[saltlen+3] = count; - - crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (i = out.byteLength; i--;) - out[i] = tmpout[i]; - - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } - - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } - - return 0; -}; - -module.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf -}; diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/package.json b/reverse_engineering/node_modules/bcrypt-pbkdf/package.json deleted file mode 100644 index e93a969..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "bcrypt-pbkdf", - "version": "1.0.2", - "description": "Port of the OpenBSD bcrypt_pbkdf function to pure JS", - "repository": { - "type": "git", - "url": "git://github.com/joyent/node-bcrypt-pbkdf.git" - }, - "main": "index.js", - "dependencies": { - "tweetnacl": "^0.14.3" - }, - "devDependencies": {}, - "license": "BSD-3-Clause" -} diff --git a/reverse_engineering/node_modules/bl/.jshintrc b/reverse_engineering/node_modules/bl/.jshintrc deleted file mode 100644 index be119b2..0000000 --- a/reverse_engineering/node_modules/bl/.jshintrc +++ /dev/null @@ -1,60 +0,0 @@ -{ - "predef": [ ] - , "bitwise": false - , "camelcase": false - , "curly": false - , "eqeqeq": false - , "forin": false - , "immed": false - , "latedef": false - , "noarg": true - , "noempty": true - , "nonew": true - , "plusplus": false - , "quotmark": true - , "regexp": false - , "undef": true - , "unused": true - , "strict": false - , "trailing": true - , "maxlen": 120 - , "asi": true - , "boss": true - , "debug": true - , "eqnull": true - , "esnext": false - , "evil": true - , "expr": true - , "funcscope": false - , "globalstrict": false - , "iterator": false - , "lastsemic": true - , "laxbreak": true - , "laxcomma": true - , "loopfunc": true - , "multistr": false - , "onecase": false - , "proto": false - , "regexdash": false - , "scripturl": true - , "smarttabs": false - , "shadow": false - , "sub": true - , "supernew": false - , "validthis": true - , "browser": true - , "couch": false - , "devel": false - , "dojo": false - , "mootools": false - , "node": true - , "nonstandard": true - , "prototypejs": false - , "rhino": false - , "worker": true - , "wsh": false - , "nomen": false - , "onevar": false - , "passfail": false - , "esversion": 3 -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/bl/.travis.yml b/reverse_engineering/node_modules/bl/.travis.yml deleted file mode 100644 index 1044a09..0000000 --- a/reverse_engineering/node_modules/bl/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -sudo: false -language: node_js -node_js: - - '4' - - '6' - - '8' - - '9' - - '10' -branches: - only: - - master -notifications: - email: - - rod@vagg.org - - matteo.collina@gmail.com diff --git a/reverse_engineering/node_modules/bl/LICENSE.md b/reverse_engineering/node_modules/bl/LICENSE.md deleted file mode 100644 index dea757d..0000000 --- a/reverse_engineering/node_modules/bl/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2013-2018 bl contributors ----------------------------------- - -*bl contributors listed at * - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/bl/README.md b/reverse_engineering/node_modules/bl/README.md deleted file mode 100644 index 79dca35..0000000 --- a/reverse_engineering/node_modules/bl/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# bl *(BufferList)* - -[![Build Status](https://travis-ci.org/rvagg/bl.svg?branch=master)](https://travis-ci.org/rvagg/bl) - -**A Node.js Buffer list collector, reader and streamer thingy.** - -[![NPM](https://nodei.co/npm/bl.png?downloads=true&downloadRank=true)](https://nodei.co/npm/bl/) -[![NPM](https://nodei.co/npm-dl/bl.png?months=6&height=3)](https://nodei.co/npm/bl/) - -**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them! - -The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently. - -```js -const BufferList = require('bl') - -var bl = new BufferList() -bl.append(Buffer.from('abcd')) -bl.append(Buffer.from('efg')) -bl.append('hi') // bl will also accept & convert Strings -bl.append(Buffer.from('j')) -bl.append(Buffer.from([ 0x3, 0x4 ])) - -console.log(bl.length) // 12 - -console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij' -console.log(bl.slice(3, 10).toString('ascii')) // 'defghij' -console.log(bl.slice(3, 6).toString('ascii')) // 'def' -console.log(bl.slice(3, 8).toString('ascii')) // 'defgh' -console.log(bl.slice(5, 10).toString('ascii')) // 'fghij' - -console.log(bl.indexOf('def')) // 3 -console.log(bl.indexOf('asdf')) // -1 - -// or just use toString! -console.log(bl.toString()) // 'abcdefghij\u0003\u0004' -console.log(bl.toString('ascii', 3, 8)) // 'defgh' -console.log(bl.toString('ascii', 5, 10)) // 'fghij' - -// other standard Buffer readables -console.log(bl.readUInt16BE(10)) // 0x0304 -console.log(bl.readUInt16LE(10)) // 0x0403 -``` - -Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**: - -```js -const bl = require('bl') - , fs = require('fs') - -fs.createReadStream('README.md') - .pipe(bl(function (err, data) { // note 'new' isn't strictly required - // `data` is a complete Buffer object containing the full data - console.log(data.toString()) - })) -``` - -Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream. - -Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!): -```js -const hyperquest = require('hyperquest') - , bl = require('bl') - , url = 'https://raw.github.com/rvagg/bl/master/README.md' - -hyperquest(url).pipe(bl(function (err, data) { - console.log(data.toString()) -})) -``` - -Or, use it as a readable stream to recompose a list of Buffers to an output source: - -```js -const BufferList = require('bl') - , fs = require('fs') - -var bl = new BufferList() -bl.append(Buffer.from('abcd')) -bl.append(Buffer.from('efg')) -bl.append(Buffer.from('hi')) -bl.append(Buffer.from('j')) - -bl.pipe(fs.createWriteStream('gibberish.txt')) -``` - -## API - - * new BufferList([ callback ]) - * bl.length - * bl.append(buffer) - * bl.get(index) - * bl.indexOf(value[, byteOffset][, encoding]) - * bl.slice([ start[, end ] ]) - * bl.shallowSlice([ start[, end ] ]) - * bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) - * bl.duplicate() - * bl.consume(bytes) - * bl.toString([encoding, [ start, [ end ]]]) - * bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() - * Streams - --------------------------------------------------------- - -### new BufferList([ callback | Buffer | Buffer array | BufferList | BufferList array | String ]) -The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream. - -Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object. - -`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: - -```js -var bl = require('bl') -var myinstance = bl() - -// equivalent to: - -var BufferList = require('bl') -var myinstance = new BufferList() -``` - --------------------------------------------------------- - -### bl.length -Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list. - --------------------------------------------------------- - -### bl.append(Buffer | Buffer array | BufferList | BufferList array | String) -`append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained. - --------------------------------------------------------- - -### bl.get(index) -`get()` will return the byte at the specified index. - --------------------------------------------------------- - -### bl.indexOf(value[, byteOffset][, encoding]) -`get()` will return the byte at the specified index. -`indexOf()` method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present. - --------------------------------------------------------- - -### bl.slice([ start, [ end ] ]) -`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. - -If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer. - --------------------------------------------------------- - -### bl.shallowSlice([ start, [ end ] ]) -`shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. - -No copies will be performed. All buffers in the result share memory with the original list. - --------------------------------------------------------- - -### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) -`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively. - --------------------------------------------------------- - -### bl.duplicate() -`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example: - -```js -var bl = new BufferList() - -bl.append('hello') -bl.append(' world') -bl.append('\n') - -bl.duplicate().pipe(process.stdout, { end: false }) - -console.log(bl.toString()) -``` - --------------------------------------------------------- - -### bl.consume(bytes) -`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers—initial offsets will be calculated accordingly in order to give you a consistent view of the data. - --------------------------------------------------------- - -### bl.toString([encoding, [ start, [ end ]]]) -`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information. - --------------------------------------------------------- - -### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() - -All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently. - -See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. - --------------------------------------------------------- - -### Streams -**bl** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **bl** instance. - --------------------------------------------------------- - -## Contributors - -**bl** is brought to you by the following hackers: - - * [Rod Vagg](https://github.com/rvagg) - * [Matteo Collina](https://github.com/mcollina) - * [Jarett Cruger](https://github.com/jcrugzz) - -======= - - -## License & copyright - -Copyright (c) 2013-2018 bl contributors (listed above). - -bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. diff --git a/reverse_engineering/node_modules/bl/bl.js b/reverse_engineering/node_modules/bl/bl.js deleted file mode 100644 index 52c3740..0000000 --- a/reverse_engineering/node_modules/bl/bl.js +++ /dev/null @@ -1,392 +0,0 @@ -'use strict' -var DuplexStream = require('readable-stream').Duplex - , util = require('util') - , Buffer = require('safe-buffer').Buffer - -function BufferList (callback) { - if (!(this instanceof BufferList)) - return new BufferList(callback) - - this._bufs = [] - this.length = 0 - - if (typeof callback == 'function') { - this._callback = callback - - var piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) - - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - } else { - this.append(callback) - } - - DuplexStream.call(this) -} - - -util.inherits(BufferList, DuplexStream) - - -BufferList.prototype._offset = function _offset (offset) { - var tot = 0, i = 0, _t - if (offset === 0) return [ 0, 0 ] - for (; i < this._bufs.length; i++) { - _t = tot + this._bufs[i].length - if (offset < _t || i == this._bufs.length - 1) { - return [ i, offset - tot ] - } - tot = _t - } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - var bufferId = blOffset[0] - var offset = blOffset[1] - for (var i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - return offset -} - -BufferList.prototype.append = function append (buf) { - var i = 0 - - if (Buffer.isBuffer(buf)) { - this._appendBuffer(buf) - } else if (Array.isArray(buf)) { - for (; i < buf.length; i++) - this.append(buf[i]) - } else if (buf instanceof BufferList) { - // unwrap argument into individual BufferLists - for (; i < buf._bufs.length; i++) - this.append(buf._bufs[i]) - } else if (buf != null) { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf == 'number') - buf = buf.toString() - - this._appendBuffer(Buffer.from(buf)) - } - - return this -} - - -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} - - -BufferList.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback == 'function') - callback() -} - - -BufferList.prototype._read = function _read (size) { - if (!this.length) - return this.push(null) - - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} - - -BufferList.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} - - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - var offset = this._offset(index) - return this._bufs[offset[0]][offset[1]] -} - - -BufferList.prototype.slice = function slice (start, end) { - if (typeof start == 'number' && start < 0) - start += this.length - if (typeof end == 'number' && end < 0) - end += this.length - return this.copy(null, 0, start, end) -} - - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart != 'number' || srcStart < 0) - srcStart = 0 - if (typeof srcEnd != 'number' || srcEnd > this.length) - srcEnd = this.length - if (srcStart >= this.length) - return dst || Buffer.alloc(0) - if (srcEnd <= 0) - return dst || Buffer.alloc(0) - - var copy = !!dst - , off = this._offset(srcStart) - , len = srcEnd - srcStart - , bytes = len - , bufoff = (copy && dstStart) || 0 - , start = off[1] - , l - , i - - // copy/slice everything - if (srcStart === 0 && srcEnd == this.length) { - if (!copy) { // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - - // copy, need to copy individual buffers - for (i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } - - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - - for (i = off[0]; i < this._bufs.length; i++) { - l = this._bufs[i].length - start - - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } - - bytes -= l - - if (start) - start = 0 - } - - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) - - return dst -} - -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - - if (start < 0) - start += this.length - if (end < 0) - end += this.length - - if (start === end) { - return new BufferList() - } - var startOffset = this._offset(start) - , endOffset = this._offset(end) - , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - - if (endOffset[1] == 0) - buffers.pop() - else - buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) - - if (startOffset[1] != 0) - buffers[0] = buffers[0].slice(startOffset[1]) - - return new BufferList(buffers) -} - -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} - -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this - - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } - return this -} - - -BufferList.prototype.duplicate = function duplicate () { - var i = 0 - , copy = new BufferList() - - for (; i < this._bufs.length; i++) - copy.append(this._bufs[i]) - - return copy -} - - -BufferList.prototype.destroy = function destroy () { - this._bufs.length = 0 - this.length = 0 - this.push(null) -} - - -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (search instanceof BufferList) { - search = search.slice() - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - - offset = Number(offset || 0) - if (isNaN(offset)) { - offset = 0 - } - - if (offset < 0) { - offset = this.length + offset - } - - if (offset < 0) { - offset = 0 - } - - if (search.length === 0) { - return offset > this.length ? this.length : offset - } - - var blOffset = this._offset(offset) - var blIndex = blOffset[0] // index of which internal buffer we're working on - var buffOffset = blOffset[1] // offset of the internal buffer we're working on - - // scan over each buffer - for (blIndex; blIndex < this._bufs.length; blIndex++) { - var buff = this._bufs[blIndex] - while(buffOffset < buff.length) { - var availableWindow = buff.length - buffOffset - if (availableWindow >= search.length) { - var nativeSearchResult = buff.indexOf(search, buffOffset) - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - var revOffset = this._reverseOffset([blIndex, buffOffset]) - if (this._match(revOffset, search)) { - return revOffset - } - buffOffset++ - } - } - buffOffset = 0 - } - return -1 -} - -BufferList.prototype._match = function(offset, search) { - if (this.length - offset < search.length) { - return false - } - for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { - if(this.get(offset + searchOffset) !== search[searchOffset]){ - return false - } - } - return true -} - - -;(function () { - var methods = { - 'readDoubleBE' : 8 - , 'readDoubleLE' : 8 - , 'readFloatBE' : 4 - , 'readFloatLE' : 4 - , 'readInt32BE' : 4 - , 'readInt32LE' : 4 - , 'readUInt32BE' : 4 - , 'readUInt32LE' : 4 - , 'readInt16BE' : 2 - , 'readInt16LE' : 2 - , 'readUInt16BE' : 2 - , 'readUInt16LE' : 2 - , 'readInt8' : 1 - , 'readUInt8' : 1 - , 'readIntBE' : null - , 'readIntLE' : null - , 'readUIntBE' : null - , 'readUIntLE' : null - } - - for (var m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } - else { - BufferList.prototype[m] = function (offset) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) - - -module.exports = BufferList diff --git a/reverse_engineering/node_modules/bl/package.json b/reverse_engineering/node_modules/bl/package.json deleted file mode 100644 index 496a729..0000000 --- a/reverse_engineering/node_modules/bl/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "bl", - "version": "2.2.1", - "description": "Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!", - "main": "bl.js", - "scripts": { - "test": "node test/test.js | faucet" - }, - "repository": { - "type": "git", - "url": "https://github.com/rvagg/bl.git" - }, - "homepage": "https://github.com/rvagg/bl", - "authors": [ - "Rod Vagg (https://github.com/rvagg)", - "Matteo Collina (https://github.com/mcollina)", - "Jarett Cruger (https://github.com/jcrugzz)" - ], - "keywords": [ - "buffer", - "buffers", - "stream", - "awesomesauce" - ], - "license": "MIT", - "dependencies": { - "readable-stream": "^2.3.5", - "safe-buffer": "^5.1.1" - }, - "devDependencies": { - "faucet": "0.0.1", - "hash_file": "~0.1.1", - "tape": "~4.9.0" - } -} diff --git a/reverse_engineering/node_modules/bl/test/indexOf.js b/reverse_engineering/node_modules/bl/test/indexOf.js deleted file mode 100644 index 68435e1..0000000 --- a/reverse_engineering/node_modules/bl/test/indexOf.js +++ /dev/null @@ -1,463 +0,0 @@ -'use strict' - -var tape = require('tape') - , BufferList = require('../') - , Buffer = require('safe-buffer').Buffer - -tape('indexOf single byte needle', t => { - const bl = new BufferList(['abcdefg', 'abcdefg', '12345']) - t.equal(bl.indexOf('e'), 4) - t.equal(bl.indexOf('e', 5), 11) - t.equal(bl.indexOf('e', 12), -1) - t.equal(bl.indexOf('5'), 18) - t.end() -}) - -tape('indexOf multiple byte needle', t => { - const bl = new BufferList(['abcdefg', 'abcdefg']) - t.equal(bl.indexOf('ef'), 4) - t.equal(bl.indexOf('ef', 5), 11) - t.end() -}) - -tape('indexOf multiple byte needles across buffer boundaries', t => { - const bl = new BufferList(['abcdefg', 'abcdefg']) - t.equal(bl.indexOf('fgabc'), 5) - t.end() -}) - -tape('indexOf takes a buffer list search', t => { - const bl = new BufferList(['abcdefg', 'abcdefg']) - const search = new BufferList('fgabc') - t.equal(bl.indexOf(search), 5) - t.end() -}) - -tape('indexOf a zero byte needle', t => { - const b = new BufferList('abcdef') - const buf_empty = Buffer.from('') - t.equal(b.indexOf(''), 0) - t.equal(b.indexOf('', 1), 1) - t.equal(b.indexOf('', b.length + 1), b.length) - t.equal(b.indexOf('', Infinity), b.length) - t.equal(b.indexOf(buf_empty), 0) - t.equal(b.indexOf(buf_empty, 1), 1) - t.equal(b.indexOf(buf_empty, b.length + 1), b.length) - t.equal(b.indexOf(buf_empty, Infinity), b.length) - t.end() -}) - -tape('indexOf buffers smaller and larger than the needle', t => { - const bl = new BufferList(['abcdefg', 'a', 'bcdefg', 'a', 'bcfgab']) - t.equal(bl.indexOf('fgabc'), 5) - t.equal(bl.indexOf('fgabc', 6), 12) - t.equal(bl.indexOf('fgabc', 13), -1) - t.end() -}) - -// only present in node 6+ -;(process.version.substr(1).split('.')[0] >= 6) && tape('indexOf latin1 and binary encoding', t => { - const b = new BufferList('abcdef') - - // test latin1 encoding - t.equal( - new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) - .indexOf('d', 0, 'latin1'), - 3 - ) - t.equal( - new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) - .indexOf(Buffer.from('d', 'latin1'), 0, 'latin1'), - 3 - ) - t.equal( - new BufferList(Buffer.from('aa\u00e8aa', 'latin1')) - .indexOf('\u00e8', 'latin1'), - 2 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'latin1')) - .indexOf('\u00e8', 'latin1'), - 0 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'latin1')) - .indexOf(Buffer.from('\u00e8', 'latin1'), 'latin1'), - 0 - ) - - // test binary encoding - t.equal( - new BufferList(Buffer.from(b.toString('binary'), 'binary')) - .indexOf('d', 0, 'binary'), - 3 - ) - t.equal( - new BufferList(Buffer.from(b.toString('binary'), 'binary')) - .indexOf(Buffer.from('d', 'binary'), 0, 'binary'), - 3 - ) - t.equal( - new BufferList(Buffer.from('aa\u00e8aa', 'binary')) - .indexOf('\u00e8', 'binary'), - 2 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'binary')) - .indexOf('\u00e8', 'binary'), - 0 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'binary')) - .indexOf(Buffer.from('\u00e8', 'binary'), 'binary'), - 0 - ) - t.end() -}) - -tape('indexOf the entire nodejs10 buffer test suite', t => { - const b = new BufferList('abcdef') - const buf_a = Buffer.from('a') - const buf_bc = Buffer.from('bc') - const buf_f = Buffer.from('f') - const buf_z = Buffer.from('z') - - const stringComparison = 'abcdef' - - t.equal(b.indexOf('a'), 0) - t.equal(b.indexOf('a', 1), -1) - t.equal(b.indexOf('a', -1), -1) - t.equal(b.indexOf('a', -4), -1) - t.equal(b.indexOf('a', -b.length), 0) - t.equal(b.indexOf('a', NaN), 0) - t.equal(b.indexOf('a', -Infinity), 0) - t.equal(b.indexOf('a', Infinity), -1) - t.equal(b.indexOf('bc'), 1) - t.equal(b.indexOf('bc', 2), -1) - t.equal(b.indexOf('bc', -1), -1) - t.equal(b.indexOf('bc', -3), -1) - t.equal(b.indexOf('bc', -5), 1) - t.equal(b.indexOf('bc', NaN), 1) - t.equal(b.indexOf('bc', -Infinity), 1) - t.equal(b.indexOf('bc', Infinity), -1) - t.equal(b.indexOf('f'), b.length - 1) - t.equal(b.indexOf('z'), -1) - // empty search tests - t.equal(b.indexOf(buf_a), 0) - t.equal(b.indexOf(buf_a, 1), -1) - t.equal(b.indexOf(buf_a, -1), -1) - t.equal(b.indexOf(buf_a, -4), -1) - t.equal(b.indexOf(buf_a, -b.length), 0) - t.equal(b.indexOf(buf_a, NaN), 0) - t.equal(b.indexOf(buf_a, -Infinity), 0) - t.equal(b.indexOf(buf_a, Infinity), -1) - t.equal(b.indexOf(buf_bc), 1) - t.equal(b.indexOf(buf_bc, 2), -1) - t.equal(b.indexOf(buf_bc, -1), -1) - t.equal(b.indexOf(buf_bc, -3), -1) - t.equal(b.indexOf(buf_bc, -5), 1) - t.equal(b.indexOf(buf_bc, NaN), 1) - t.equal(b.indexOf(buf_bc, -Infinity), 1) - t.equal(b.indexOf(buf_bc, Infinity), -1) - t.equal(b.indexOf(buf_f), b.length - 1) - t.equal(b.indexOf(buf_z), -1) - t.equal(b.indexOf(0x61), 0) - t.equal(b.indexOf(0x61, 1), -1) - t.equal(b.indexOf(0x61, -1), -1) - t.equal(b.indexOf(0x61, -4), -1) - t.equal(b.indexOf(0x61, -b.length), 0) - t.equal(b.indexOf(0x61, NaN), 0) - t.equal(b.indexOf(0x61, -Infinity), 0) - t.equal(b.indexOf(0x61, Infinity), -1) - t.equal(b.indexOf(0x0), -1) - - // test offsets - t.equal(b.indexOf('d', 2), 3) - t.equal(b.indexOf('f', 5), 5) - t.equal(b.indexOf('f', -1), 5) - t.equal(b.indexOf('f', 6), -1) - - t.equal(b.indexOf(Buffer.from('d'), 2), 3) - t.equal(b.indexOf(Buffer.from('f'), 5), 5) - t.equal(b.indexOf(Buffer.from('f'), -1), 5) - t.equal(b.indexOf(Buffer.from('f'), 6), -1) - - t.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1) - - // test invalid and uppercase encoding - t.equal(b.indexOf('b', 'utf8'), 1) - t.equal(b.indexOf('b', 'UTF8'), 1) - t.equal(b.indexOf('62', 'HEX'), 1) - t.throws(() => b.indexOf('bad', 'enc'), TypeError) - - // test hex encoding - t.equal( - Buffer.from(b.toString('hex'), 'hex') - .indexOf('64', 0, 'hex'), - 3 - ) - t.equal( - Buffer.from(b.toString('hex'), 'hex') - .indexOf(Buffer.from('64', 'hex'), 0, 'hex'), - 3 - ) - - // test base64 encoding - t.equal( - Buffer.from(b.toString('base64'), 'base64') - .indexOf('ZA==', 0, 'base64'), - 3 - ) - t.equal( - Buffer.from(b.toString('base64'), 'base64') - .indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'), - 3 - ) - - // test ascii encoding - t.equal( - Buffer.from(b.toString('ascii'), 'ascii') - .indexOf('d', 0, 'ascii'), - 3 - ) - t.equal( - Buffer.from(b.toString('ascii'), 'ascii') - .indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'), - 3 - ) - - // test optional offset with passed encoding - t.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4) - t.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4) - - { - // test usc2 encoding - const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') - - t.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')) - t.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')) - t.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')) - t.equal(4, twoByteString.indexOf( - Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2')) - t.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')) - } - - const mixedByteStringUcs2 = - Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2') - t.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')) - t.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')) - t.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')) - - t.equal( - 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2')) - t.equal( - 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')) - t.equal( - -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')) - - { - const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') - - // Test single char pattern - t.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2')) - let index = twoByteString.indexOf('\u0391', 0, 'ucs2') - t.equal(2, index, `Alpha - at index ${index}`) - index = twoByteString.indexOf('\u03a3', 0, 'ucs2') - t.equal(4, index, `First Sigma - at index ${index}`) - index = twoByteString.indexOf('\u03a3', 6, 'ucs2') - t.equal(6, index, `Second Sigma - at index ${index}`) - index = twoByteString.indexOf('\u0395', 0, 'ucs2') - t.equal(8, index, `Epsilon - at index ${index}`) - index = twoByteString.indexOf('\u0392', 0, 'ucs2') - t.equal(-1, index, `Not beta - at index ${index}`) - - // Test multi-char pattern - index = twoByteString.indexOf('\u039a\u0391', 0, 'ucs2') - t.equal(0, index, `Lambda Alpha - at index ${index}`) - index = twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2') - t.equal(2, index, `Alpha Sigma - at index ${index}`) - index = twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2') - t.equal(4, index, `Sigma Sigma - at index ${index}`) - index = twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2') - t.equal(6, index, `Sigma Epsilon - at index ${index}`) - } - - const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395') - t.equal(5, mixedByteStringUtf8.indexOf('bc')) - t.equal(5, mixedByteStringUtf8.indexOf('bc', 5)) - t.equal(5, mixedByteStringUtf8.indexOf('bc', -8)) - t.equal(7, mixedByteStringUtf8.indexOf('\u03a3')) - t.equal(-1, mixedByteStringUtf8.indexOf('\u0396')) - - - // Test complex string indexOf algorithms. Only trigger for long strings. - // Long string that isn't a simple repeat of a shorter string. - let longString = 'A' - for (let i = 66; i < 76; i++) { // from 'B' to 'K' - longString = longString + String.fromCharCode(i) + longString - } - - const longBufferString = Buffer.from(longString) - - // pattern of 15 chars, repeated every 16 chars in long - let pattern = 'ABACABADABACABA' - for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { - const index = longBufferString.indexOf(pattern, i) - t.equal((i + 15) & ~0xf, index, - `Long ABACABA...-string at index ${i}`) - } - - let index = longBufferString.indexOf('AJABACA') - t.equal(510, index, `Long AJABACA, First J - at index ${index}`) - index = longBufferString.indexOf('AJABACA', 511) - t.equal(1534, index, `Long AJABACA, Second J - at index ${index}`) - - pattern = 'JABACABADABACABA' - index = longBufferString.indexOf(pattern) - t.equal(511, index, `Long JABACABA..., First J - at index ${index}`) - index = longBufferString.indexOf(pattern, 512) - t.equal( - 1535, index, `Long JABACABA..., Second J - at index ${index}`) - - // Search for a non-ASCII string in a pure ASCII string. - const asciiString = Buffer.from( - 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf') - t.equal(-1, asciiString.indexOf('\x2061')) - t.equal(3, asciiString.indexOf('leb', 0)) - - // Search in string containing many non-ASCII chars. - const allCodePoints = [] - for (let i = 0; i < 65536; i++) allCodePoints[i] = i - const allCharsString = String.fromCharCode.apply(String, allCodePoints) - const allCharsBufferUtf8 = Buffer.from(allCharsString) - const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2') - - // Search for string long enough to trigger complex search with ASCII pattern - // and UC16 subject. - t.equal(-1, allCharsBufferUtf8.indexOf('notfound')) - t.equal(-1, allCharsBufferUcs2.indexOf('notfound')) - - // Needle is longer than haystack, but only because it's encoded as UTF-16 - t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1) - - t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'utf8'), 0) - t.equal(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1) - - // Haystack has odd length, but the needle is UCS2. - t.equal(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1) - - { - // Find substrings in Utf8. - const lengths = [1, 3, 15]; // Single char, simple and complex. - const indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b] - for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { - for (let i = 0; i < indices.length; i++) { - const index = indices[i] - let length = lengths[lengthIndex] - - if (index + length > 0x7F) { - length = 2 * length - } - - if (index + length > 0x7FF) { - length = 3 * length - } - - if (index + length > 0xFFFF) { - length = 4 * length - } - - const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length) - t.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)) - - const patternStringUtf8 = patternBufferUtf8.toString() - t.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8)) - } - } - } - - { - // Find substrings in Usc2. - const lengths = [2, 4, 16]; // Single char, simple and complex. - const indices = [0x5, 0x65, 0x105, 0x205, 0x285, 0x2005, 0x2085, 0xfff0] - for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { - for (let i = 0; i < indices.length; i++) { - const index = indices[i] * 2 - const length = lengths[lengthIndex] - - const patternBufferUcs2 = - allCharsBufferUcs2.slice(index, index + length) - t.equal( - index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')) - - const patternStringUcs2 = patternBufferUcs2.toString('ucs2') - t.equal( - index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')) - } - } - } - - [ - () => {}, - {}, - [] - ].forEach(val => { - debugger - t.throws(() => b.indexOf(val), TypeError, `"${JSON.stringify(val)}" should throw`) - }) - - // Test weird offset arguments. - // The following offsets coerce to NaN or 0, searching the whole Buffer - t.equal(b.indexOf('b', undefined), 1) - t.equal(b.indexOf('b', {}), 1) - t.equal(b.indexOf('b', 0), 1) - t.equal(b.indexOf('b', null), 1) - t.equal(b.indexOf('b', []), 1) - - // The following offset coerces to 2, in other words +[2] === 2 - t.equal(b.indexOf('b', [2]), -1) - - // Behavior should match String.indexOf() - t.equal( - b.indexOf('b', undefined), - stringComparison.indexOf('b', undefined)) - t.equal( - b.indexOf('b', {}), - stringComparison.indexOf('b', {})) - t.equal( - b.indexOf('b', 0), - stringComparison.indexOf('b', 0)) - t.equal( - b.indexOf('b', null), - stringComparison.indexOf('b', null)) - t.equal( - b.indexOf('b', []), - stringComparison.indexOf('b', [])) - t.equal( - b.indexOf('b', [2]), - stringComparison.indexOf('b', [2])) - - // test truncation of Number arguments to uint8 - { - const buf = Buffer.from('this is a test') - t.equal(buf.indexOf(0x6973), 3) - t.equal(buf.indexOf(0x697320), 4) - t.equal(buf.indexOf(0x69732069), 2) - t.equal(buf.indexOf(0x697374657374), 0) - t.equal(buf.indexOf(0x69737374), 0) - t.equal(buf.indexOf(0x69737465), 11) - t.equal(buf.indexOf(0x69737465), 11) - t.equal(buf.indexOf(-140), 0) - t.equal(buf.indexOf(-152), 1) - t.equal(buf.indexOf(0xff), -1) - t.equal(buf.indexOf(0xffff), -1) - } - - // Test that Uint8Array arguments are okay. - { - const needle = new Uint8Array([ 0x66, 0x6f, 0x6f ]) - const haystack = new BufferList(Buffer.from('a foo b foo')) - t.equal(haystack.indexOf(needle), 2) - } - t.end() -}) diff --git a/reverse_engineering/node_modules/bl/test/test.js b/reverse_engineering/node_modules/bl/test/test.js deleted file mode 100644 index 42fcad4..0000000 --- a/reverse_engineering/node_modules/bl/test/test.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict' - -var tape = require('tape') - , crypto = require('crypto') - , fs = require('fs') - , hash = require('hash_file') - , BufferList = require('../') - , Buffer = require('safe-buffer').Buffer - - , encodings = - ('hex utf8 utf-8 ascii binary base64' - + (process.browser ? '' : ' ucs2 ucs-2 utf16le utf-16le')).split(' ') - -// run the indexOf tests -require('./indexOf') - -tape('single bytes from single buffer', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abcd')) - - t.equal(bl.length, 4) - t.equal(bl.get(-1), undefined) - t.equal(bl.get(0), 97) - t.equal(bl.get(1), 98) - t.equal(bl.get(2), 99) - t.equal(bl.get(3), 100) - t.equal(bl.get(4), undefined) - - t.end() -}) - -tape('single bytes from multiple buffers', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.length, 10) - - t.equal(bl.get(0), 97) - t.equal(bl.get(1), 98) - t.equal(bl.get(2), 99) - t.equal(bl.get(3), 100) - t.equal(bl.get(4), 101) - t.equal(bl.get(5), 102) - t.equal(bl.get(6), 103) - t.equal(bl.get(7), 104) - t.equal(bl.get(8), 105) - t.equal(bl.get(9), 106) - t.end() -}) - -tape('multi bytes from single buffer', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abcd')) - - t.equal(bl.length, 4) - - t.equal(bl.slice(0, 4).toString('ascii'), 'abcd') - t.equal(bl.slice(0, 3).toString('ascii'), 'abc') - t.equal(bl.slice(1, 4).toString('ascii'), 'bcd') - t.equal(bl.slice(-4, -1).toString('ascii'), 'abc') - - t.end() -}) - -tape('multi bytes from single buffer (negative indexes)', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('buffer')) - - t.equal(bl.length, 6) - - t.equal(bl.slice(-6, -1).toString('ascii'), 'buffe') - t.equal(bl.slice(-6, -2).toString('ascii'), 'buff') - t.equal(bl.slice(-5, -2).toString('ascii'), 'uff') - - t.end() -}) - -tape('multiple bytes from multiple buffers', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') - t.equal(bl.slice(3, 6).toString('ascii'), 'def') - t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') - t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') - t.equal(bl.slice(-7, -4).toString('ascii'), 'def') - - t.end() -}) - -tape('multiple bytes from multiple buffer lists', function (t) { - var bl = new BufferList() - - bl.append(new BufferList([ Buffer.from('abcd'), Buffer.from('efg') ])) - bl.append(new BufferList([ Buffer.from('hi'), Buffer.from('j') ])) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - - t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') - t.equal(bl.slice(3, 6).toString('ascii'), 'def') - t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') - t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') - - t.end() -}) - -// same data as previous test, just using nested constructors -tape('multiple bytes from crazy nested buffer lists', function (t) { - var bl = new BufferList() - - bl.append(new BufferList([ - new BufferList([ - new BufferList(Buffer.from('abc')) - , Buffer.from('d') - , new BufferList(Buffer.from('efg')) - ]) - , new BufferList([ Buffer.from('hi') ]) - , new BufferList(Buffer.from('j')) - ])) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - - t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') - t.equal(bl.slice(3, 6).toString('ascii'), 'def') - t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') - t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') - - t.end() -}) - -tape('append accepts arrays of Buffers', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abc')) - bl.append([ Buffer.from('def') ]) - bl.append([ Buffer.from('ghi'), Buffer.from('jkl') ]) - bl.append([ Buffer.from('mnop'), Buffer.from('qrstu'), Buffer.from('vwxyz') ]) - t.equal(bl.length, 26) - t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') - t.end() -}) - -tape('append accepts arrays of BufferLists', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abc')) - bl.append([ new BufferList('def') ]) - bl.append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ])) - bl.append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ]) - t.equal(bl.length, 26) - t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') - t.end() -}) - -tape('append chainable', function (t) { - var bl = new BufferList() - t.ok(bl.append(Buffer.from('abcd')) === bl) - t.ok(bl.append([ Buffer.from('abcd') ]) === bl) - t.ok(bl.append(new BufferList(Buffer.from('abcd'))) === bl) - t.ok(bl.append([ new BufferList(Buffer.from('abcd')) ]) === bl) - t.end() -}) - -tape('append chainable (test results)', function (t) { - var bl = new BufferList('abc') - .append([ new BufferList('def') ]) - .append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ])) - .append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ]) - - t.equal(bl.length, 26) - t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') - t.end() -}) - -tape('consuming from multiple buffers', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - - bl.consume(3) - t.equal(bl.length, 7) - t.equal(bl.slice(0, 7).toString('ascii'), 'defghij') - - bl.consume(2) - t.equal(bl.length, 5) - t.equal(bl.slice(0, 5).toString('ascii'), 'fghij') - - bl.consume(1) - t.equal(bl.length, 4) - t.equal(bl.slice(0, 4).toString('ascii'), 'ghij') - - bl.consume(1) - t.equal(bl.length, 3) - t.equal(bl.slice(0, 3).toString('ascii'), 'hij') - - bl.consume(2) - t.equal(bl.length, 1) - t.equal(bl.slice(0, 1).toString('ascii'), 'j') - - t.end() -}) - -tape('complete consumption', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('a')) - bl.append(Buffer.from('b')) - - bl.consume(2) - - t.equal(bl.length, 0) - t.equal(bl._bufs.length, 0) - - t.end() -}) - -tape('test readUInt8 / readInt8', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUInt8(2), 0x3) - t.equal(bl.readInt8(2), 0x3) - t.equal(bl.readUInt8(3), 0x4) - t.equal(bl.readInt8(3), 0x4) - t.equal(bl.readUInt8(4), 0x23) - t.equal(bl.readInt8(4), 0x23) - t.equal(bl.readUInt8(5), 0x42) - t.equal(bl.readInt8(5), 0x42) - t.end() -}) - -tape('test readUInt16LE / readUInt16BE / readInt16LE / readInt16BE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUInt16BE(2), 0x0304) - t.equal(bl.readUInt16LE(2), 0x0403) - t.equal(bl.readInt16BE(2), 0x0304) - t.equal(bl.readInt16LE(2), 0x0403) - t.equal(bl.readUInt16BE(3), 0x0423) - t.equal(bl.readUInt16LE(3), 0x2304) - t.equal(bl.readInt16BE(3), 0x0423) - t.equal(bl.readInt16LE(3), 0x2304) - t.equal(bl.readUInt16BE(4), 0x2342) - t.equal(bl.readUInt16LE(4), 0x4223) - t.equal(bl.readInt16BE(4), 0x2342) - t.equal(bl.readInt16LE(4), 0x4223) - t.end() -}) - -tape('test readUInt32LE / readUInt32BE / readInt32LE / readInt32BE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUInt32BE(2), 0x03042342) - t.equal(bl.readUInt32LE(2), 0x42230403) - t.equal(bl.readInt32BE(2), 0x03042342) - t.equal(bl.readInt32LE(2), 0x42230403) - t.end() -}) - -tape('test readUIntLE / readUIntBE / readIntLE / readIntBE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[0] = 0x2 - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - buf3[2] = 0x61 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUIntBE(1, 1), 0x02) - t.equal(bl.readUIntBE(1, 2), 0x0203) - t.equal(bl.readUIntBE(1, 3), 0x020304) - t.equal(bl.readUIntBE(1, 4), 0x02030423) - t.equal(bl.readUIntBE(1, 5), 0x0203042342) - t.equal(bl.readUIntBE(1, 6), 0x020304234261) - t.equal(bl.readUIntLE(1, 1), 0x02) - t.equal(bl.readUIntLE(1, 2), 0x0302) - t.equal(bl.readUIntLE(1, 3), 0x040302) - t.equal(bl.readUIntLE(1, 4), 0x23040302) - t.equal(bl.readUIntLE(1, 5), 0x4223040302) - t.equal(bl.readUIntLE(1, 6), 0x614223040302) - t.equal(bl.readIntBE(1, 1), 0x02) - t.equal(bl.readIntBE(1, 2), 0x0203) - t.equal(bl.readIntBE(1, 3), 0x020304) - t.equal(bl.readIntBE(1, 4), 0x02030423) - t.equal(bl.readIntBE(1, 5), 0x0203042342) - t.equal(bl.readIntBE(1, 6), 0x020304234261) - t.equal(bl.readIntLE(1, 1), 0x02) - t.equal(bl.readIntLE(1, 2), 0x0302) - t.equal(bl.readIntLE(1, 3), 0x040302) - t.equal(bl.readIntLE(1, 4), 0x23040302) - t.equal(bl.readIntLE(1, 5), 0x4223040302) - t.equal(bl.readIntLE(1, 6), 0x614223040302) - t.end() -}) - -tape('test readFloatLE / readFloatBE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x00 - buf2[2] = 0x00 - buf3[0] = 0x80 - buf3[1] = 0x3f - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readFloatLE(2), 0x01) - t.end() -}) - -tape('test readDoubleLE / readDoubleBE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(10) - , bl = new BufferList() - - buf2[1] = 0x55 - buf2[2] = 0x55 - buf3[0] = 0x55 - buf3[1] = 0x55 - buf3[2] = 0x55 - buf3[3] = 0x55 - buf3[4] = 0xd5 - buf3[5] = 0x3f - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readDoubleLE(2), 0.3333333333333333) - t.end() -}) - -tape('test toString', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.toString('ascii', 0, 10), 'abcdefghij') - t.equal(bl.toString('ascii', 3, 10), 'defghij') - t.equal(bl.toString('ascii', 3, 6), 'def') - t.equal(bl.toString('ascii', 3, 8), 'defgh') - t.equal(bl.toString('ascii', 5, 10), 'fghij') - - t.end() -}) - -tape('test toString encoding', function (t) { - var bl = new BufferList() - , b = Buffer.from('abcdefghij\xff\x00') - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - bl.append(Buffer.from('\xff\x00')) - - encodings.forEach(function (enc) { - t.equal(bl.toString(enc), b.toString(enc), enc) - }) - - t.end() -}) - -tape('uninitialized memory', function (t) { - const secret = crypto.randomBytes(256) - for (let i = 0; i < 1e6; i++) { - const clone = Buffer.from(secret) - const bl = new BufferList() - bl.append(Buffer.from('a')) - bl.consume(-1024) - const buf = bl.slice(1) - if (buf.indexOf(clone) !== -1) { - t.fail(`Match (at ${i})`) - break - } - } - t.end() -}) - -!process.browser && tape('test stream', function (t) { - var random = crypto.randomBytes(65534) - , rndhash = hash(random, 'md5') - , md5sum = crypto.createHash('md5') - , bl = new BufferList(function (err, buf) { - t.ok(Buffer.isBuffer(buf)) - t.ok(err === null) - t.equal(rndhash, hash(bl.slice(), 'md5')) - t.equal(rndhash, hash(buf, 'md5')) - - bl.pipe(fs.createWriteStream('/tmp/bl_test_rnd_out.dat')) - .on('close', function () { - var s = fs.createReadStream('/tmp/bl_test_rnd_out.dat') - s.on('data', md5sum.update.bind(md5sum)) - s.on('end', function() { - t.equal(rndhash, md5sum.digest('hex'), 'woohoo! correct hash!') - t.end() - }) - }) - - }) - - fs.writeFileSync('/tmp/bl_test_rnd.dat', random) - fs.createReadStream('/tmp/bl_test_rnd.dat').pipe(bl) -}) - -tape('instantiation with Buffer', function (t) { - var buf = crypto.randomBytes(1024) - , buf2 = crypto.randomBytes(1024) - , b = BufferList(buf) - - t.equal(buf.toString('hex'), b.slice().toString('hex'), 'same buffer') - b = BufferList([ buf, buf2 ]) - t.equal(b.slice().toString('hex'), Buffer.concat([ buf, buf2 ]).toString('hex'), 'same buffer') - t.end() -}) - -tape('test String appendage', function (t) { - var bl = new BufferList() - , b = Buffer.from('abcdefghij\xff\x00') - - bl.append('abcd') - bl.append('efg') - bl.append('hi') - bl.append('j') - bl.append('\xff\x00') - - encodings.forEach(function (enc) { - t.equal(bl.toString(enc), b.toString(enc)) - }) - - t.end() -}) - -tape('test Number appendage', function (t) { - var bl = new BufferList() - , b = Buffer.from('1234567890') - - bl.append(1234) - bl.append(567) - bl.append(89) - bl.append(0) - - encodings.forEach(function (enc) { - t.equal(bl.toString(enc), b.toString(enc)) - }) - - t.end() -}) - -tape('write nothing, should get empty buffer', function (t) { - t.plan(3) - BufferList(function (err, data) { - t.notOk(err, 'no error') - t.ok(Buffer.isBuffer(data), 'got a buffer') - t.equal(0, data.length, 'got a zero-length buffer') - t.end() - }).end() -}) - -tape('unicode string', function (t) { - t.plan(2) - var inp1 = '\u2600' - , inp2 = '\u2603' - , exp = inp1 + ' and ' + inp2 - , bl = BufferList() - bl.write(inp1) - bl.write(' and ') - bl.write(inp2) - t.equal(exp, bl.toString()) - t.equal(Buffer.from(exp).toString('hex'), bl.toString('hex')) -}) - -tape('should emit finish', function (t) { - var source = BufferList() - , dest = BufferList() - - source.write('hello') - source.pipe(dest) - - dest.on('finish', function () { - t.equal(dest.toString('utf8'), 'hello') - t.end() - }) -}) - -tape('basic copy', function (t) { - var buf = crypto.randomBytes(1024) - , buf2 = Buffer.alloc(1024) - , b = BufferList(buf) - - b.copy(buf2) - t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy after many appends', function (t) { - var buf = crypto.randomBytes(512) - , buf2 = Buffer.alloc(1024) - , b = BufferList(buf) - - b.append(buf) - b.copy(buf2) - t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy at a precise position', function (t) { - var buf = crypto.randomBytes(1004) - , buf2 = Buffer.alloc(1024) - , b = BufferList(buf) - - b.copy(buf2, 20) - t.equal(b.slice().toString('hex'), buf2.slice(20).toString('hex'), 'same buffer') - t.end() -}) - -tape('copy starting from a precise location', function (t) { - var buf = crypto.randomBytes(10) - , buf2 = Buffer.alloc(5) - , b = BufferList(buf) - - b.copy(buf2, 0, 5) - t.equal(b.slice(5).toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy in an interval', function (t) { - var rnd = crypto.randomBytes(10) - , b = BufferList(rnd) // put the random bytes there - , actual = Buffer.alloc(3) - , expected = Buffer.alloc(3) - - rnd.copy(expected, 0, 5, 8) - b.copy(actual, 0, 5, 8) - - t.equal(actual.toString('hex'), expected.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy an interval between two buffers', function (t) { - var buf = crypto.randomBytes(10) - , buf2 = Buffer.alloc(10) - , b = BufferList(buf) - - b.append(buf) - b.copy(buf2, 0, 5, 15) - - t.equal(b.slice(5, 15).toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('shallow slice across buffer boundaries', function (t) { - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice(3, 13).toString(), 'stSecondTh') - t.end() -}) - -tape('shallow slice within single buffer', function (t) { - t.plan(2) - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice(5, 10).toString(), 'Secon') - t.equal(bl.shallowSlice(7, 10).toString(), 'con') - t.end() -}) - -tape('shallow slice single buffer', function (t) { - t.plan(3) - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice(0, 5).toString(), 'First') - t.equal(bl.shallowSlice(5, 11).toString(), 'Second') - t.equal(bl.shallowSlice(11, 16).toString(), 'Third') -}) - -tape('shallow slice with negative or omitted indices', function (t) { - t.plan(4) - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice().toString(), 'FirstSecondThird') - t.equal(bl.shallowSlice(5).toString(), 'SecondThird') - t.equal(bl.shallowSlice(5, -3).toString(), 'SecondTh') - t.equal(bl.shallowSlice(-8).toString(), 'ondThird') -}) - -tape('shallow slice does not make a copy', function (t) { - t.plan(1) - var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] - var bl = (new BufferList(buffers)).shallowSlice(5, -3) - - buffers[1].fill('h') - buffers[2].fill('h') - - t.equal(bl.toString(), 'hhhhhhhh') -}) - -tape('shallow slice with 0 length', function (t) { - t.plan(1) - var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] - var bl = (new BufferList(buffers)).shallowSlice(0, 0) - t.equal(bl.length, 0) -}) - -tape('shallow slice with 0 length from middle', function (t) { - t.plan(1) - var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] - var bl = (new BufferList(buffers)).shallowSlice(10, 10) - t.equal(bl.length, 0) -}) - -tape('duplicate', function (t) { - t.plan(2) - - var bl = new BufferList('abcdefghij\xff\x00') - , dup = bl.duplicate() - - t.equal(bl.prototype, dup.prototype) - t.equal(bl.toString('hex'), dup.toString('hex')) -}) - -tape('destroy no pipe', function (t) { - t.plan(2) - - var bl = new BufferList('alsdkfja;lsdkfja;lsdk') - bl.destroy() - - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) -}) - -!process.browser && tape('destroy with pipe before read end', function (t) { - t.plan(2) - - var bl = new BufferList() - fs.createReadStream(__dirname + '/test.js') - .pipe(bl) - - bl.destroy() - - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) - -}) - -!process.browser && tape('destroy with pipe before read end with race', function (t) { - t.plan(2) - - var bl = new BufferList() - fs.createReadStream(__dirname + '/test.js') - .pipe(bl) - - setTimeout(function () { - bl.destroy() - setTimeout(function () { - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) - }, 500) - }, 500) -}) - -!process.browser && tape('destroy with pipe after read end', function (t) { - t.plan(2) - - var bl = new BufferList() - fs.createReadStream(__dirname + '/test.js') - .on('end', onEnd) - .pipe(bl) - - function onEnd () { - bl.destroy() - - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) - } -}) - -!process.browser && tape('destroy with pipe while writing to a destination', function (t) { - t.plan(4) - - var bl = new BufferList() - , ds = new BufferList() - - fs.createReadStream(__dirname + '/test.js') - .on('end', onEnd) - .pipe(bl) - - function onEnd () { - bl.pipe(ds) - - setTimeout(function () { - bl.destroy() - - t.equals(bl._bufs.length, 0) - t.equals(bl.length, 0) - - ds.destroy() - - t.equals(bl._bufs.length, 0) - t.equals(bl.length, 0) - - }, 100) - } -}) - -!process.browser && tape('handle error', function (t) { - t.plan(2) - fs.createReadStream('/does/not/exist').pipe(BufferList(function (err, data) { - t.ok(err instanceof Error, 'has error') - t.notOk(data, 'no data') - })) -}) diff --git a/reverse_engineering/node_modules/bson/HISTORY.md b/reverse_engineering/node_modules/bson/HISTORY.md deleted file mode 100644 index d8d5d20..0000000 --- a/reverse_engineering/node_modules/bson/HISTORY.md +++ /dev/null @@ -1,301 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -### [1.1.6](https://github.com/mongodb/js-bson/compare/v1.1.5...v1.1.6) (2021-03-16) - - -### Bug Fixes - -* Throw error on bigint usage and add helpers to Long ([#426](https://github.com/mongodb/js-bson/issues/426)) ([375f368](https://github.com/mongodb/js-bson/commit/375f368738807f2d41c7751e618fd09c8a1b94c9)) - -### [1.1.5](https://github.com/mongodb/js-bson/compare/v1.1.4...v1.1.5) (2020-08-10) - - -### Bug Fixes - -* **object-id:** harden the duck-typing ([b526145](https://github.com/mongodb/js-bson/commit/b5261450c3bc4abb2e2fb19b5b1a7aba27982d44)) - - -## [1.1.3](https://github.com/mongodb/js-bson/compare/v1.1.2...v1.1.3) (2019-11-09) - -Reverts 1.1.2 - - -## [1.1.2](https://github.com/mongodb/js-bson/compare/v1.1.1...v1.1.2) (2019-11-08) - - -### Bug Fixes - -* **_bsontype:** only check bsontype if it is a prototype member. ([dd8a349](https://github.com/mongodb/js-bson/commit/dd8a349)) - - - - -## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08) - - -### Bug Fixes - -* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5)) - - -### Features - -* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba)) - - - - -# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) - - -### Bug Fixes - -* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) - - - - -## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) - - -### Bug Fixes - -* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) - - - - -## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) - - -### Bug Fixes - -* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) -* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) -* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) -* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) - - - - -## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) - - -### Features - -* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) - - - - -## 1.0.5 (2018-02-26) - - -### Bug Fixes - -* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) -* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) - - - -1.0.4 2016-01-11 ----------------- -- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. - -1.0.3 2016-01-03 ----------------- -- Fixed toString for ObjectId so it will work with inspect. - -1.0.2 2016-01-02 ----------------- -- Minor optimizations for ObjectID to use Buffer.from where available. - -1.0.1 2016-12-06 ----------------- -- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. - -1.0.0 2016-12-06 ----------------- -- Introduced new BSON API and documentation. - -0.5.7 2016-11-18 ------------------ -- NODE-848 BSON Regex flags must be alphabetically ordered. - -0.5.6 2016-10-19 ------------------ -- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. -- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). - -0.5.5 2016-09-15 ------------------ -- Added DBPointer up conversion to DBRef - -0.5.4 2016-08-23 ------------------ -- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. - -0.5.3 2016-07-11 ------------------ -- Throw error if ObjectId is not a string or a buffer. - -0.5.2 2016-07-11 ------------------ -- All values encoded big-endian style for ObjectId. - -0.5.1 2016-07-11 ------------------ -- Fixed encoding/decoding issue in ObjectId timestamp generation. -- Removed BinaryParser dependency from the serializer/deserializer. - -0.5.0 2016-07-05 ------------------ -- Added Decimal128 type and extended test suite to include entire bson corpus. - -0.4.23 2016-04-08 ------------------ -- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. -- Remove one package from dependency due to having been pulled from NPM. - -0.4.22 2016-03-04 ------------------ -- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). -- Fixed issue with undefined type on deserializing. - -0.4.21 2016-01-12 ------------------ -- Minor optimizations to avoid non needed object creation. - -0.4.20 2015-10-15 ------------------ -- Added bower file to repository. -- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) - -0.4.19 2015-10-15 ------------------ -- Remove all support for bson-ext. - -0.4.18 2015-10-15 ------------------ -- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 -- add option for deserializing binary into Buffer object #116 - -0.4.17 2015-10-15 ------------------ -- Validate regexp string for null bytes and throw if there is one. - -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/reverse_engineering/node_modules/bson/LICENSE.md b/reverse_engineering/node_modules/bson/LICENSE.md deleted file mode 100644 index 261eeb9..0000000 --- a/reverse_engineering/node_modules/bson/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/reverse_engineering/node_modules/bson/README.md b/reverse_engineering/node_modules/bson/README.md deleted file mode 100644 index 0688341..0000000 --- a/reverse_engineering/node_modules/bson/README.md +++ /dev/null @@ -1,170 +0,0 @@ -# BSON parser - -BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). - -This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. - -This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). - -## Usage - -To build a new version perform the following operations: - -``` -npm install -npm run build -``` - -A simple example of how to use BSON in the browser: - -```html - - - -``` - -A simple example of how to use BSON in `Node.js`: - -```js -// Get BSON parser class -var BSON = require('bson') -// Get the Long type -var Long = BSON.Long; -// Create a bson parser instance -var bson = new BSON(); - -// Serialize document -var doc = { long: Long.fromNumber(100) } - -// Serialize a document -var data = bson.serialize(doc) -console.log('data:', data) - -// Deserialize the resulting Buffer -var doc_2 = bson.deserialize(data) -console.log('doc_2:', doc_2) -``` - -## Installation - -`npm install bson` - -## API - -### BSON types - -For all BSON types documentation, please refer to the following sources: - * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) - * [BSON Spec](https://bsonspec.org/) - -### BSON serialization and deserialiation - -**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. - -#### BSON.serialize - -The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. - - * `BSON.serialize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.serializeWithBufferAndIndex - -The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. - - * `BSON.serializeWithBufferAndIndex(object, buffer, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. - * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - -#### BSON.calculateObjectSize - -The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. - - * `BSON.calculateObjectSize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.deserialize - -The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. - - * `BSON.deserialize(buffer, options)` - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - -#### BSON.deserializeStream - -The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. - - * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - -## FAQ - -#### Why does `undefined` get converted to `null`? - -The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. - -#### How do I add custom serialization logic? - -This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. - -```javascript -var bson = new BSON(); - -class CustomSerialize { - toBSON() { - return 42; - } -} - -const obj = { answer: new CustomSerialize() }; -// "{ answer: 42 }" -console.log(bson.deserialize(bson.serialize(obj))); -``` diff --git a/reverse_engineering/node_modules/bson/bower.json b/reverse_engineering/node_modules/bson/bower.json deleted file mode 100644 index eded1f8..0000000 --- a/reverse_engineering/node_modules/bson/bower.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "author": "Christian Amor Kvalheim ", - "main": "./browser_build/bson.js", - "license": "Apache-2.0", - "moduleType": [ - "globals", - "node" - ], - "ignore": [ - "**/.*", - "alternate_parsers", - "benchmarks", - "bower_components", - "node_modules", - "test", - "tools" - ], - "version": "1.1.6" -} diff --git a/reverse_engineering/node_modules/bson/browser_build/bson.js b/reverse_engineering/node_modules/bson/browser_build/bson.js deleted file mode 100644 index 9540a86..0000000 --- a/reverse_engineering/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,18218 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else { - var a = factory(); - for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; - } -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = "/"; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(1); - module.exports = __webpack_require__(332); - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - - __webpack_require__(2); - - __webpack_require__(328); - - __webpack_require__(329); - - if (global._babelPolyfill) { - throw new Error("only one instance of babel-polyfill is allowed"); - } - global._babelPolyfill = true; - - var DEFINE_PROPERTY = "defineProperty"; - function define(O, key, value) { - O[key] || Object[DEFINE_PROPERTY](O, key, { - writable: true, - configurable: true, - value: value - }); - } - - define(String.prototype, "padLeft", "".padStart); - define(String.prototype, "padRight", "".padEnd); - - "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { - [][key] && define(Array, key, Function.call.bind([][key])); - }); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(3); - __webpack_require__(53); - __webpack_require__(54); - __webpack_require__(55); - __webpack_require__(56); - __webpack_require__(58); - __webpack_require__(60); - __webpack_require__(61); - __webpack_require__(62); - __webpack_require__(63); - __webpack_require__(64); - __webpack_require__(65); - __webpack_require__(66); - __webpack_require__(67); - __webpack_require__(68); - __webpack_require__(70); - __webpack_require__(72); - __webpack_require__(74); - __webpack_require__(76); - __webpack_require__(79); - __webpack_require__(80); - __webpack_require__(81); - __webpack_require__(85); - __webpack_require__(87); - __webpack_require__(89); - __webpack_require__(92); - __webpack_require__(93); - __webpack_require__(94); - __webpack_require__(95); - __webpack_require__(97); - __webpack_require__(98); - __webpack_require__(99); - __webpack_require__(100); - __webpack_require__(101); - __webpack_require__(102); - __webpack_require__(103); - __webpack_require__(105); - __webpack_require__(106); - __webpack_require__(107); - __webpack_require__(109); - __webpack_require__(110); - __webpack_require__(111); - __webpack_require__(113); - __webpack_require__(115); - __webpack_require__(116); - __webpack_require__(117); - __webpack_require__(118); - __webpack_require__(119); - __webpack_require__(120); - __webpack_require__(121); - __webpack_require__(122); - __webpack_require__(123); - __webpack_require__(124); - __webpack_require__(125); - __webpack_require__(126); - __webpack_require__(127); - __webpack_require__(132); - __webpack_require__(133); - __webpack_require__(137); - __webpack_require__(138); - __webpack_require__(139); - __webpack_require__(140); - __webpack_require__(142); - __webpack_require__(143); - __webpack_require__(144); - __webpack_require__(145); - __webpack_require__(146); - __webpack_require__(147); - __webpack_require__(148); - __webpack_require__(149); - __webpack_require__(150); - __webpack_require__(151); - __webpack_require__(152); - __webpack_require__(153); - __webpack_require__(154); - __webpack_require__(155); - __webpack_require__(156); - __webpack_require__(158); - __webpack_require__(159); - __webpack_require__(161); - __webpack_require__(162); - __webpack_require__(168); - __webpack_require__(169); - __webpack_require__(171); - __webpack_require__(172); - __webpack_require__(173); - __webpack_require__(177); - __webpack_require__(178); - __webpack_require__(179); - __webpack_require__(180); - __webpack_require__(181); - __webpack_require__(183); - __webpack_require__(184); - __webpack_require__(185); - __webpack_require__(186); - __webpack_require__(189); - __webpack_require__(191); - __webpack_require__(192); - __webpack_require__(193); - __webpack_require__(195); - __webpack_require__(197); - __webpack_require__(199); - __webpack_require__(201); - __webpack_require__(202); - __webpack_require__(203); - __webpack_require__(207); - __webpack_require__(208); - __webpack_require__(209); - __webpack_require__(211); - __webpack_require__(221); - __webpack_require__(225); - __webpack_require__(226); - __webpack_require__(228); - __webpack_require__(229); - __webpack_require__(233); - __webpack_require__(234); - __webpack_require__(236); - __webpack_require__(237); - __webpack_require__(238); - __webpack_require__(239); - __webpack_require__(240); - __webpack_require__(241); - __webpack_require__(242); - __webpack_require__(243); - __webpack_require__(244); - __webpack_require__(245); - __webpack_require__(246); - __webpack_require__(247); - __webpack_require__(248); - __webpack_require__(249); - __webpack_require__(250); - __webpack_require__(251); - __webpack_require__(252); - __webpack_require__(253); - __webpack_require__(254); - __webpack_require__(256); - __webpack_require__(257); - __webpack_require__(258); - __webpack_require__(259); - __webpack_require__(260); - __webpack_require__(262); - __webpack_require__(263); - __webpack_require__(264); - __webpack_require__(266); - __webpack_require__(267); - __webpack_require__(268); - __webpack_require__(269); - __webpack_require__(270); - __webpack_require__(271); - __webpack_require__(272); - __webpack_require__(273); - __webpack_require__(275); - __webpack_require__(276); - __webpack_require__(278); - __webpack_require__(279); - __webpack_require__(280); - __webpack_require__(281); - __webpack_require__(284); - __webpack_require__(285); - __webpack_require__(287); - __webpack_require__(288); - __webpack_require__(289); - __webpack_require__(290); - __webpack_require__(292); - __webpack_require__(293); - __webpack_require__(294); - __webpack_require__(295); - __webpack_require__(296); - __webpack_require__(297); - __webpack_require__(298); - __webpack_require__(299); - __webpack_require__(300); - __webpack_require__(301); - __webpack_require__(303); - __webpack_require__(304); - __webpack_require__(305); - __webpack_require__(306); - __webpack_require__(307); - __webpack_require__(308); - __webpack_require__(309); - __webpack_require__(310); - __webpack_require__(311); - __webpack_require__(312); - __webpack_require__(313); - __webpack_require__(315); - __webpack_require__(316); - __webpack_require__(317); - __webpack_require__(318); - __webpack_require__(319); - __webpack_require__(320); - __webpack_require__(321); - __webpack_require__(322); - __webpack_require__(323); - __webpack_require__(324); - __webpack_require__(325); - __webpack_require__(326); - __webpack_require__(327); - module.exports = __webpack_require__(9); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // ECMAScript 6 symbols shim - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var DESCRIPTORS = __webpack_require__(6); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var META = __webpack_require__(25).KEY; - var $fails = __webpack_require__(7); - var shared = __webpack_require__(21); - var setToStringTag = __webpack_require__(26); - var uid = __webpack_require__(19); - var wks = __webpack_require__(27); - var wksExt = __webpack_require__(28); - var wksDefine = __webpack_require__(29); - var enumKeys = __webpack_require__(30); - var isArray = __webpack_require__(45); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var toObject = __webpack_require__(46); - var toIObject = __webpack_require__(33); - var toPrimitive = __webpack_require__(16); - var createDesc = __webpack_require__(17); - var _create = __webpack_require__(47); - var gOPNExt = __webpack_require__(50); - var $GOPD = __webpack_require__(52); - var $GOPS = __webpack_require__(43); - var $DP = __webpack_require__(11); - var $keys = __webpack_require__(31); - var gOPD = $GOPD.f; - var dP = $DP.f; - var gOPN = gOPNExt.f; - var $Symbol = global.Symbol; - var $JSON = global.JSON; - var _stringify = $JSON && $JSON.stringify; - var PROTOTYPE = 'prototype'; - var HIDDEN = wks('_hidden'); - var TO_PRIMITIVE = wks('toPrimitive'); - var isEnum = {}.propertyIsEnumerable; - var SymbolRegistry = shared('symbol-registry'); - var AllSymbols = shared('symbols'); - var OPSymbols = shared('op-symbols'); - var ObjectProto = Object[PROTOTYPE]; - var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f; - var QObject = global.QObject; - // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; - - // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 - var setSymbolDesc = DESCRIPTORS && $fails(function () { - return _create(dP({}, 'a', { - get: function () { return dP(this, 'a', { value: 7 }).a; } - })).a != 7; - }) ? function (it, key, D) { - var protoDesc = gOPD(ObjectProto, key); - if (protoDesc) delete ObjectProto[key]; - dP(it, key, D); - if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); - } : dP; - - var wrap = function (tag) { - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; - }; - - var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { - return typeof it == 'symbol'; - } : function (it) { - return it instanceof $Symbol; - }; - - var $defineProperty = function defineProperty(it, key, D) { - if (it === ObjectProto) $defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if (has(AllSymbols, key)) { - if (!D.enumerable) { - if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; - D = _create(D, { enumerable: createDesc(0, false) }); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); - }; - var $defineProperties = function defineProperties(it, P) { - anObject(it); - var keys = enumKeys(P = toIObject(P)); - var i = 0; - var l = keys.length; - var key; - while (l > i) $defineProperty(it, key = keys[i++], P[key]); - return it; - }; - var $create = function create(it, P) { - return P === undefined ? _create(it) : $defineProperties(_create(it), P); - }; - var $propertyIsEnumerable = function propertyIsEnumerable(key) { - var E = isEnum.call(this, key = toPrimitive(key, true)); - if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; - }; - var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { - it = toIObject(it); - key = toPrimitive(key, true); - if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; - var D = gOPD(it, key); - if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; - return D; - }; - var $getOwnPropertyNames = function getOwnPropertyNames(it) { - var names = gOPN(toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); - } return result; - }; - var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { - var IS_OP = it === ObjectProto; - var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); - } return result; - }; - - // 19.4.1.1 Symbol([description]) - if (!USE_NATIVE) { - $Symbol = function Symbol() { - if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function (value) { - if (this === ObjectProto) $set.call(OPSymbols, value); - if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString() { - return this._k; - }); - - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - __webpack_require__(51).f = gOPNExt.f = $getOwnPropertyNames; - __webpack_require__(44).f = $propertyIsEnumerable; - $GOPS.f = $getOwnPropertySymbols; - - if (DESCRIPTORS && !__webpack_require__(22)) { - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } - - wksExt.f = function (name) { - return wrap(wks(name)); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); - - for (var es6Symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' - ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); - - for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); - - $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function (key) { - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(sym) { - if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); - for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; - }, - useSetter: function () { setter = true; }, - useSimple: function () { setter = false; } - }); - - $export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols - }); - - // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives - // https://bugs.chromium.org/p/v8/issues/detail?id=3443 - var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); }); - - $export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', { - getOwnPropertySymbols: function getOwnPropertySymbols(it) { - return $GOPS.f(toObject(it)); - } - }); - - // 24.3.2 JSON.stringify(value [, replacer [, space]]) - $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; - })), 'JSON', { - stringify: function stringify(it) { - var args = [it]; - var i = 1; - var replacer, $replacer; - while (arguments.length > i) args.push(arguments[i++]); - $replacer = replacer = args[1]; - if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined - if (!isArray(replacer)) replacer = function (key, value) { - if (typeof $replacer == 'function') value = $replacer.call(this, key, value); - if (!isSymbol(value)) return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); - } - }); - - // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) - $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); - // 19.4.3.5 Symbol.prototype[@@toStringTag] - setToStringTag($Symbol, 'Symbol'); - // 20.2.1.9 Math[@@toStringTag] - setToStringTag(Math, 'Math', true); - // 24.3.3 JSON[@@toStringTag] - setToStringTag(global.JSON, 'JSON', true); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self - // eslint-disable-next-line no-new-func - : Function('return this')(); - if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef - - -/***/ }), -/* 5 */ -/***/ (function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function (it, key) { - return hasOwnProperty.call(it, key); - }; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(7)(function () { - return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return !!exec(); - } catch (e) { - return true; - } - }; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var ctx = __webpack_require__(23); - var PROTOTYPE = 'prototype'; - - var $export = function (type, name, source) { - var IS_FORCED = type & $export.F; - var IS_GLOBAL = type & $export.G; - var IS_STATIC = type & $export.S; - var IS_PROTO = type & $export.P; - var IS_BIND = type & $export.B; - var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; - var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); - var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); - var key, own, out, exp; - if (IS_GLOBAL) source = name; - for (key in source) { - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - // export native or passed - out = (own ? target : source)[key]; - // bind timers to global for call from export context - exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // extend global - if (target) redefine(target, key, out, type & $export.U); - // export - if (exports[key] != out) hide(exports, key, exp); - if (IS_PROTO && expProto[key] != out) expProto[key] = out; - } - }; - global.core = core; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - var core = module.exports = { version: '2.6.10' }; - if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var createDesc = __webpack_require__(17); - module.exports = __webpack_require__(6) ? function (object, key, value) { - return dP.f(object, key, createDesc(1, value)); - } : function (object, key, value) { - object[key] = value; - return object; - }; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var IE8_DOM_DEFINE = __webpack_require__(14); - var toPrimitive = __webpack_require__(16); - var dP = Object.defineProperty; - - exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; - }; - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; - }; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - - module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { - return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var document = __webpack_require__(4).document; - // typeof document.createElement is 'object' in old IE - var is = isObject(document) && isObject(document.createElement); - module.exports = function (it) { - return is ? document.createElement(it) : {}; - }; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(13); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function (it, S) { - if (!isObject(it)) return it; - var fn, val; - if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; - if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - throw TypeError("Can't convert object to primitive value"); - }; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; - }; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var has = __webpack_require__(5); - var SRC = __webpack_require__(19)('src'); - var $toString = __webpack_require__(20); - var TO_STRING = 'toString'; - var TPL = ('' + $toString).split(TO_STRING); - - __webpack_require__(9).inspectSource = function (it) { - return $toString.call(it); - }; - - (module.exports = function (O, key, val, safe) { - var isFunction = typeof val == 'function'; - if (isFunction) has(val, 'name') || hide(val, 'name', key); - if (O[key] === val) return; - if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); - if (O === global) { - O[key] = val; - } else if (!safe) { - delete O[key]; - hide(O, key, val); - } else if (O[key]) { - O[key] = val; - } else { - hide(O, key, val); - } - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, TO_STRING, function toString() { - return typeof this == 'function' && this[SRC] || $toString.call(this); - }); - - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - - var id = 0; - var px = Math.random(); - module.exports = function (key) { - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); - }; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - - module.exports = __webpack_require__(21)('native-function-to-string', Function.toString); - - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var SHARED = '__core-js_shared__'; - var store = global[SHARED] || (global[SHARED] = {}); - - (module.exports = function (key, value) { - return store[key] || (store[key] = value !== undefined ? value : {}); - })('versions', []).push({ - version: core.version, - mode: __webpack_require__(22) ? 'pure' : 'global', - copyright: '© 2019 Denis Pushkarev (zloirock.ru)' - }); - - -/***/ }), -/* 22 */ -/***/ (function(module, exports) { - - module.exports = false; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(24); - module.exports = function (fn, that, length) { - aFunction(fn); - if (that === undefined) return fn; - switch (length) { - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; - } - return function (/* ...args */) { - return fn.apply(that, arguments); - }; - }; - - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - if (typeof it != 'function') throw TypeError(it + ' is not a function!'); - return it; - }; - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - - var META = __webpack_require__(19)('meta'); - var isObject = __webpack_require__(13); - var has = __webpack_require__(5); - var setDesc = __webpack_require__(11).f; - var id = 0; - var isExtensible = Object.isExtensible || function () { - return true; - }; - var FREEZE = !__webpack_require__(7)(function () { - return isExtensible(Object.preventExtensions({})); - }); - var setMeta = function (it) { - setDesc(it, META, { value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - } }); - }; - var fastKey = function (it, create) { - // return primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; - // not necessary to add metadata - if (!create) return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; - }; - var getWeak = function (it, create) { - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; - // not necessary to add metadata - if (!create) return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; - }; - // add metadata on freeze-family methods calling - var onFreeze = function (it) { - if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); - return it; - }; - var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze - }; - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - - var def = __webpack_require__(11).f; - var has = __webpack_require__(5); - var TAG = __webpack_require__(27)('toStringTag'); - - module.exports = function (it, tag, stat) { - if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); - }; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - - var store = __webpack_require__(21)('wks'); - var uid = __webpack_require__(19); - var Symbol = __webpack_require__(4).Symbol; - var USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function (name) { - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - - exports.f = __webpack_require__(27); - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var LIBRARY = __webpack_require__(22); - var wksExt = __webpack_require__(28); - var defineProperty = __webpack_require__(11).f; - module.exports = function (name) { - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); - }; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - - // all enumerable object keys, includes symbols - var getKeys = __webpack_require__(31); - var gOPS = __webpack_require__(43); - var pIE = __webpack_require__(44); - module.exports = function (it) { - var result = getKeys(it); - var getSymbols = gOPS.f; - if (getSymbols) { - var symbols = getSymbols(it); - var isEnum = pIE.f; - var i = 0; - var key; - while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); - } return result; - }; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 / 15.2.3.14 Object.keys(O) - var $keys = __webpack_require__(32); - var enumBugKeys = __webpack_require__(42); - - module.exports = Object.keys || function keys(O) { - return $keys(O, enumBugKeys); - }; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - - var has = __webpack_require__(5); - var toIObject = __webpack_require__(33); - var arrayIndexOf = __webpack_require__(37)(false); - var IE_PROTO = __webpack_require__(41)('IE_PROTO'); - - module.exports = function (object, names) { - var O = toIObject(object); - var i = 0; - var result = []; - var key; - for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~arrayIndexOf(result, key) || result.push(key); - } - return result; - }; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(34); - var defined = __webpack_require__(36); - module.exports = function (it) { - return IObject(defined(it)); - }; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var cof = __webpack_require__(35); - // eslint-disable-next-line no-prototype-builtins - module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { - return cof(it) == 'String' ? it.split('') : Object(it); - }; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = function (it) { - return toString.call(it).slice(8, -1); - }; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; - }; - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - - // false -> Array#indexOf - // true -> Array#includes - var toIObject = __webpack_require__(33); - var toLength = __webpack_require__(38); - var toAbsoluteIndex = __webpack_require__(40); - module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; - }; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(39); - var min = Math.min; - module.exports = function (it) { - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil; - var floor = Math.floor; - module.exports = function (it) { - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(39); - var max = Math.max; - var min = Math.min; - module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); - }; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - - var shared = __webpack_require__(21)('keys'); - var uid = __webpack_require__(19); - module.exports = function (key) { - return shared[key] || (shared[key] = uid(key)); - }; - - -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - - // IE 8- don't enum bug keys - module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' - ).split(','); - - -/***/ }), -/* 43 */ -/***/ (function(module, exports) { - - exports.f = Object.getOwnPropertySymbols; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports) { - - exports.f = {}.propertyIsEnumerable; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.2 IsArray(argument) - var cof = __webpack_require__(35); - module.exports = Array.isArray || function isArray(arg) { - return cof(arg) == 'Array'; - }; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.13 ToObject(argument) - var defined = __webpack_require__(36); - module.exports = function (it) { - return Object(defined(it)); - }; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - var anObject = __webpack_require__(12); - var dPs = __webpack_require__(48); - var enumBugKeys = __webpack_require__(42); - var IE_PROTO = __webpack_require__(41)('IE_PROTO'); - var Empty = function () { /* empty */ }; - var PROTOTYPE = 'prototype'; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(15)('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(49).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); - }; - - module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); - }; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var anObject = __webpack_require__(12); - var getKeys = __webpack_require__(31); - - module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; - }; - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - - var document = __webpack_require__(4).document; - module.exports = document && document.documentElement; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window - var toIObject = __webpack_require__(33); - var gOPN = __webpack_require__(51).f; - var toString = {}.toString; - - var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - - var getWindowNames = function (it) { - try { - return gOPN(it); - } catch (e) { - return windowNames.slice(); - } - }; - - module.exports.f = function getOwnPropertyNames(it) { - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); - }; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) - var $keys = __webpack_require__(32); - var hiddenKeys = __webpack_require__(42).concat('length', 'prototype'); - - exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); - }; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - - var pIE = __webpack_require__(44); - var createDesc = __webpack_require__(17); - var toIObject = __webpack_require__(33); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var IE8_DOM_DEFINE = __webpack_require__(14); - var gOPD = Object.getOwnPropertyDescriptor; - - exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { - O = toIObject(O); - P = toPrimitive(P, true); - if (IE8_DOM_DEFINE) try { - return gOPD(O, P); - } catch (e) { /* empty */ } - if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); - }; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - $export($export.S, 'Object', { create: __webpack_require__(47) }); - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(48) }); - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - var toIObject = __webpack_require__(33); - var $getOwnPropertyDescriptor = __webpack_require__(52).f; - - __webpack_require__(57)('getOwnPropertyDescriptor', function () { - return function getOwnPropertyDescriptor(it, key) { - return $getOwnPropertyDescriptor(toIObject(it), key); - }; - }); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - - // most Object methods by ES6 should accept primitives - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var fails = __webpack_require__(7); - module.exports = function (KEY, exec) { - var fn = (core.Object || {})[KEY] || Object[KEY]; - var exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); - }; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 Object.getPrototypeOf(O) - var toObject = __webpack_require__(46); - var $getPrototypeOf = __webpack_require__(59); - - __webpack_require__(57)('getPrototypeOf', function () { - return function getPrototypeOf(it) { - return $getPrototypeOf(toObject(it)); - }; - }); - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) - var has = __webpack_require__(5); - var toObject = __webpack_require__(46); - var IE_PROTO = __webpack_require__(41)('IE_PROTO'); - var ObjectProto = Object.prototype; - - module.exports = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; - }; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 Object.keys(O) - var toObject = __webpack_require__(46); - var $keys = __webpack_require__(31); - - __webpack_require__(57)('keys', function () { - return function keys(it) { - return $keys(toObject(it)); - }; - }); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 Object.getOwnPropertyNames(O) - __webpack_require__(57)('getOwnPropertyNames', function () { - return __webpack_require__(50).f; - }); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.5 Object.freeze(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(25).onFreeze; - - __webpack_require__(57)('freeze', function ($freeze) { - return function freeze(it) { - return $freeze && isObject(it) ? $freeze(meta(it)) : it; - }; - }); - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.17 Object.seal(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(25).onFreeze; - - __webpack_require__(57)('seal', function ($seal) { - return function seal(it) { - return $seal && isObject(it) ? $seal(meta(it)) : it; - }; - }); - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.15 Object.preventExtensions(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(25).onFreeze; - - __webpack_require__(57)('preventExtensions', function ($preventExtensions) { - return function preventExtensions(it) { - return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; - }; - }); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.12 Object.isFrozen(O) - var isObject = __webpack_require__(13); - - __webpack_require__(57)('isFrozen', function ($isFrozen) { - return function isFrozen(it) { - return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; - }; - }); - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.13 Object.isSealed(O) - var isObject = __webpack_require__(13); - - __webpack_require__(57)('isSealed', function ($isSealed) { - return function isSealed(it) { - return isObject(it) ? $isSealed ? $isSealed(it) : false : true; - }; - }); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.11 Object.isExtensible(O) - var isObject = __webpack_require__(13); - - __webpack_require__(57)('isExtensible', function ($isExtensible) { - return function isExtensible(it) { - return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; - }; - }); - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.1 Object.assign(target, source) - var $export = __webpack_require__(8); - - $export($export.S + $export.F, 'Object', { assign: __webpack_require__(69) }); - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.2.1 Object.assign(target, source, ...) - var DESCRIPTORS = __webpack_require__(6); - var getKeys = __webpack_require__(31); - var gOPS = __webpack_require__(43); - var pIE = __webpack_require__(44); - var toObject = __webpack_require__(46); - var IObject = __webpack_require__(34); - var $assign = Object.assign; - - // should work with symbols and should have deterministic property order (V8 bug) - module.exports = !$assign || __webpack_require__(7)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; - }) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) { - key = keys[j++]; - if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key]; - } - } return T; - } : $assign; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.10 Object.is(value1, value2) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { is: __webpack_require__(71) }); - - -/***/ }), -/* 71 */ -/***/ (function(module, exports) { - - // 7.2.9 SameValue(x, y) - module.exports = Object.is || function is(x, y) { - // eslint-disable-next-line no-self-compare - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; - }; - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.19 Object.setPrototypeOf(O, proto) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(73).set }); - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - - // Works with __proto__ only. Old v8 can't work with null proto objects. - /* eslint-disable no-proto */ - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - var check = function (O, proto) { - anObject(O); - if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); - }; - module.exports = { - set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line - function (test, buggy, set) { - try { - set = __webpack_require__(23)(Function.call, __webpack_require__(52).f(Object.prototype, '__proto__').set, 2); - set(test, []); - buggy = !(test instanceof Array); - } catch (e) { buggy = true; } - return function setPrototypeOf(O, proto) { - check(O, proto); - if (buggy) O.__proto__ = proto; - else set(O, proto); - return O; - }; - }({}, false) : undefined), - check: check - }; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.3.6 Object.prototype.toString() - var classof = __webpack_require__(75); - var test = {}; - test[__webpack_require__(27)('toStringTag')] = 'z'; - if (test + '' != '[object z]') { - __webpack_require__(18)(Object.prototype, 'toString', function toString() { - return '[object ' + classof(this) + ']'; - }, true); - } - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - - // getting tag from 19.1.3.6 Object.prototype.toString() - var cof = __webpack_require__(35); - var TAG = __webpack_require__(27)('toStringTag'); - // ES3 wrong here - var ARG = cof(function () { return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function (it, key) { - try { - return it[key]; - } catch (e) { /* empty */ } - }; - - module.exports = function (it) { - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; - }; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) - var $export = __webpack_require__(8); - - $export($export.P, 'Function', { bind: __webpack_require__(77) }); - - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var aFunction = __webpack_require__(24); - var isObject = __webpack_require__(13); - var invoke = __webpack_require__(78); - var arraySlice = [].slice; - var factories = {}; - - var construct = function (F, len, args) { - if (!(len in factories)) { - for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; - // eslint-disable-next-line no-new-func - factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); - } return factories[len](F, args); - }; - - module.exports = Function.bind || function bind(that /* , ...args */) { - var fn = aFunction(this); - var partArgs = arraySlice.call(arguments, 1); - var bound = function (/* args... */) { - var args = partArgs.concat(arraySlice.call(arguments)); - return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); - }; - if (isObject(fn.prototype)) bound.prototype = fn.prototype; - return bound; - }; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports) { - - // fast apply, http://jsperf.lnkit.com/fast-apply/5 - module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); - }; - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11).f; - var FProto = Function.prototype; - var nameRE = /^\s*function ([^ (]*)/; - var NAME = 'name'; - - // 19.2.4.2 name - NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { - configurable: true, - get: function () { - try { - return ('' + this).match(nameRE)[1]; - } catch (e) { - return ''; - } - } - }); - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var isObject = __webpack_require__(13); - var getPrototypeOf = __webpack_require__(59); - var HAS_INSTANCE = __webpack_require__(27)('hasInstance'); - var FunctionProto = Function.prototype; - // 19.2.3.6 Function.prototype[@@hasInstance](V) - if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { - if (typeof this != 'function' || !isObject(O)) return false; - if (!isObject(this.prototype)) return O instanceof this; - // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: - while (O = getPrototypeOf(O)) if (this.prototype === O) return true; - return false; - } }); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(82); - // 18.2.5 parseInt(string, radix) - $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseInt = __webpack_require__(4).parseInt; - var $trim = __webpack_require__(83).trim; - var ws = __webpack_require__(84); - var hex = /^[-+]?0[xX]/; - - module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { - var string = $trim(String(str), 3); - return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); - } : $parseInt; - - -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var defined = __webpack_require__(36); - var fails = __webpack_require__(7); - var spaces = __webpack_require__(84); - var space = '[' + spaces + ']'; - var non = '\u200b\u0085'; - var ltrim = RegExp('^' + space + space + '*'); - var rtrim = RegExp(space + space + '*$'); - - var exporter = function (KEY, exec, ALIAS) { - var exp = {}; - var FORCE = fails(function () { - return !!spaces[KEY]() || non[KEY]() != non; - }); - var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; - if (ALIAS) exp[ALIAS] = fn; - $export($export.P + $export.F * FORCE, 'String', exp); - }; - - // 1 -> String#trimLeft - // 2 -> String#trimRight - // 3 -> String#trim - var trim = exporter.trim = function (string, TYPE) { - string = String(defined(string)); - if (TYPE & 1) string = string.replace(ltrim, ''); - if (TYPE & 2) string = string.replace(rtrim, ''); - return string; - }; - - module.exports = exporter; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports) { - - module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(86); - // 18.2.4 parseFloat(string) - $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseFloat = __webpack_require__(4).parseFloat; - var $trim = __webpack_require__(83).trim; - - module.exports = 1 / $parseFloat(__webpack_require__(84) + '-0') !== -Infinity ? function parseFloat(str) { - var string = $trim(String(str), 3); - var result = $parseFloat(string); - return result === 0 && string.charAt(0) == '-' ? -0 : result; - } : $parseFloat; - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var cof = __webpack_require__(35); - var inheritIfRequired = __webpack_require__(88); - var toPrimitive = __webpack_require__(16); - var fails = __webpack_require__(7); - var gOPN = __webpack_require__(51).f; - var gOPD = __webpack_require__(52).f; - var dP = __webpack_require__(11).f; - var $trim = __webpack_require__(83).trim; - var NUMBER = 'Number'; - var $Number = global[NUMBER]; - var Base = $Number; - var proto = $Number.prototype; - // Opera ~12 has broken Object#toString - var BROKEN_COF = cof(__webpack_require__(47)(proto)) == NUMBER; - var TRIM = 'trim' in String.prototype; - - // 7.1.3 ToNumber(argument) - var toNumber = function (argument) { - var it = toPrimitive(argument, false); - if (typeof it == 'string' && it.length > 2) { - it = TRIM ? it.trim() : $trim(it, 3); - var first = it.charCodeAt(0); - var third, radix, maxCode; - if (first === 43 || first === 45) { - third = it.charCodeAt(2); - if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix - } else if (first === 48) { - switch (it.charCodeAt(1)) { - case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i - case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i - default: return +it; - } - for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { - code = digits.charCodeAt(i); - // parseInt parses a string to a first unavailable symbol - // but ToNumber should return NaN if a string contains unavailable symbols - if (code < 48 || code > maxCode) return NaN; - } return parseInt(digits, radix); - } - } return +it; - }; - - if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { - $Number = function Number(value) { - var it = arguments.length < 1 ? 0 : value; - var that = this; - return that instanceof $Number - // check on 1..constructor(foo) case - && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) - ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); - }; - for (var keys = __webpack_require__(6) ? gOPN(Base) : ( - // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + - // ES6 (in case, if modules with ES6 Number statics required before): - 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + - 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' - ).split(','), j = 0, key; keys.length > j; j++) { - if (has(Base, key = keys[j]) && !has($Number, key)) { - dP($Number, key, gOPD(Base, key)); - } - } - $Number.prototype = proto; - proto.constructor = $Number; - __webpack_require__(18)(global, NUMBER, $Number); - } - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var setPrototypeOf = __webpack_require__(73).set; - module.exports = function (that, target, C) { - var S = target.constructor; - var P; - if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { - setPrototypeOf(that, P); - } return that; - }; - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toInteger = __webpack_require__(39); - var aNumberValue = __webpack_require__(90); - var repeat = __webpack_require__(91); - var $toFixed = 1.0.toFixed; - var floor = Math.floor; - var data = [0, 0, 0, 0, 0, 0]; - var ERROR = 'Number.toFixed: incorrect invocation!'; - var ZERO = '0'; - - var multiply = function (n, c) { - var i = -1; - var c2 = c; - while (++i < 6) { - c2 += n * data[i]; - data[i] = c2 % 1e7; - c2 = floor(c2 / 1e7); - } - }; - var divide = function (n) { - var i = 6; - var c = 0; - while (--i >= 0) { - c += data[i]; - data[i] = floor(c / n); - c = (c % n) * 1e7; - } - }; - var numToString = function () { - var i = 6; - var s = ''; - while (--i >= 0) { - if (s !== '' || i === 0 || data[i] !== 0) { - var t = String(data[i]); - s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; - } - } return s; - }; - var pow = function (x, n, acc) { - return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); - }; - var log = function (x) { - var n = 0; - var x2 = x; - while (x2 >= 4096) { - n += 12; - x2 /= 4096; - } - while (x2 >= 2) { - n += 1; - x2 /= 2; - } return n; - }; - - $export($export.P + $export.F * (!!$toFixed && ( - 0.00008.toFixed(3) !== '0.000' || - 0.9.toFixed(0) !== '1' || - 1.255.toFixed(2) !== '1.25' || - 1000000000000000128.0.toFixed(0) !== '1000000000000000128' - ) || !__webpack_require__(7)(function () { - // V8 ~ Android 4.3- - $toFixed.call({}); - })), 'Number', { - toFixed: function toFixed(fractionDigits) { - var x = aNumberValue(this, ERROR); - var f = toInteger(fractionDigits); - var s = ''; - var m = ZERO; - var e, z, j, k; - if (f < 0 || f > 20) throw RangeError(ERROR); - // eslint-disable-next-line no-self-compare - if (x != x) return 'NaN'; - if (x <= -1e21 || x >= 1e21) return String(x); - if (x < 0) { - s = '-'; - x = -x; - } - if (x > 1e-21) { - e = log(x * pow(2, 69, 1)) - 69; - z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); - z *= 0x10000000000000; - e = 52 - e; - if (e > 0) { - multiply(0, z); - j = f; - while (j >= 7) { - multiply(1e7, 0); - j -= 7; - } - multiply(pow(10, j, 1), 0); - j = e - 1; - while (j >= 23) { - divide(1 << 23); - j -= 23; - } - divide(1 << j); - multiply(1, 1); - divide(2); - m = numToString(); - } else { - multiply(0, z); - multiply(1 << -e, 0); - m = numToString() + repeat.call(ZERO, f); - } - } - if (f > 0) { - k = m.length; - m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); - } else { - m = s + m; - } return m; - } - }); - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - - var cof = __webpack_require__(35); - module.exports = function (it, msg) { - if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); - return +it; - }; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var toInteger = __webpack_require__(39); - var defined = __webpack_require__(36); - - module.exports = function repeat(count) { - var str = String(defined(this)); - var res = ''; - var n = toInteger(count); - if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); - for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; - return res; - }; - - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $fails = __webpack_require__(7); - var aNumberValue = __webpack_require__(90); - var $toPrecision = 1.0.toPrecision; - - $export($export.P + $export.F * ($fails(function () { - // IE7- - return $toPrecision.call(1, undefined) !== '1'; - }) || !$fails(function () { - // V8 ~ Android 4.3- - $toPrecision.call({}); - })), 'Number', { - toPrecision: function toPrecision(precision) { - var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); - return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); - } - }); - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.1 Number.EPSILON - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.2 Number.isFinite(number) - var $export = __webpack_require__(8); - var _isFinite = __webpack_require__(4).isFinite; - - $export($export.S, 'Number', { - isFinite: function isFinite(it) { - return typeof it == 'number' && _isFinite(it); - } - }); - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { isInteger: __webpack_require__(96) }); - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var isObject = __webpack_require__(13); - var floor = Math.floor; - module.exports = function isInteger(it) { - return !isObject(it) && isFinite(it) && floor(it) === it; - }; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.4 Number.isNaN(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { - isNaN: function isNaN(number) { - // eslint-disable-next-line no-self-compare - return number != number; - } - }); - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.5 Number.isSafeInteger(number) - var $export = __webpack_require__(8); - var isInteger = __webpack_require__(96); - var abs = Math.abs; - - $export($export.S, 'Number', { - isSafeInteger: function isSafeInteger(number) { - return isInteger(number) && abs(number) <= 0x1fffffffffffff; - } - }); - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.6 Number.MAX_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.10 Number.MIN_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(86); - // 20.1.2.12 Number.parseFloat(string) - $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(82); - // 20.1.2.13 Number.parseInt(string, radix) - $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.3 Math.acosh(x) - var $export = __webpack_require__(8); - var log1p = __webpack_require__(104); - var sqrt = Math.sqrt; - var $acosh = Math.acosh; - - $export($export.S + $export.F * !($acosh - // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 - && Math.floor($acosh(Number.MAX_VALUE)) == 710 - // Tor Browser bug: Math.acosh(Infinity) -> NaN - && $acosh(Infinity) == Infinity - ), 'Math', { - acosh: function acosh(x) { - return (x = +x) < 1 ? NaN : x > 94906265.62425156 - ? Math.log(x) + Math.LN2 - : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); - } - }); - - -/***/ }), -/* 104 */ -/***/ (function(module, exports) { - - // 20.2.2.20 Math.log1p(x) - module.exports = Math.log1p || function log1p(x) { - return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); - }; - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.5 Math.asinh(x) - var $export = __webpack_require__(8); - var $asinh = Math.asinh; - - function asinh(x) { - return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); - } - - // Tor Browser bug: Math.asinh(0) -> -0 - $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); - - -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.7 Math.atanh(x) - var $export = __webpack_require__(8); - var $atanh = Math.atanh; - - // Tor Browser bug: Math.atanh(-0) -> 0 - $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { - atanh: function atanh(x) { - return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; - } - }); - - -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.9 Math.cbrt(x) - var $export = __webpack_require__(8); - var sign = __webpack_require__(108); - - $export($export.S, 'Math', { - cbrt: function cbrt(x) { - return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); - } - }); - - -/***/ }), -/* 108 */ -/***/ (function(module, exports) { - - // 20.2.2.28 Math.sign(x) - module.exports = Math.sign || function sign(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; - }; - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.11 Math.clz32(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clz32: function clz32(x) { - return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; - } - }); - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.12 Math.cosh(x) - var $export = __webpack_require__(8); - var exp = Math.exp; - - $export($export.S, 'Math', { - cosh: function cosh(x) { - return (exp(x = +x) + exp(-x)) / 2; - } - }); - - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.14 Math.expm1(x) - var $export = __webpack_require__(8); - var $expm1 = __webpack_require__(112); - - $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); - - -/***/ }), -/* 112 */ -/***/ (function(module, exports) { - - // 20.2.2.14 Math.expm1(x) - var $expm1 = Math.expm1; - module.exports = (!$expm1 - // Old FF bug - || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 - // Tor Browser bug - || $expm1(-2e-17) != -2e-17 - ) ? function expm1(x) { - return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; - } : $expm1; - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { fround: __webpack_require__(114) }); - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var sign = __webpack_require__(108); - var pow = Math.pow; - var EPSILON = pow(2, -52); - var EPSILON32 = pow(2, -23); - var MAX32 = pow(2, 127) * (2 - EPSILON32); - var MIN32 = pow(2, -126); - - var roundTiesToEven = function (n) { - return n + 1 / EPSILON - 1 / EPSILON; - }; - - module.exports = Math.fround || function fround(x) { - var $abs = Math.abs(x); - var $sign = sign(x); - var a, result; - if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; - a = (1 + EPSILON32 / EPSILON) * $abs; - result = a - (a - $abs); - // eslint-disable-next-line no-self-compare - if (result > MAX32 || result != result) return $sign * Infinity; - return $sign * result; - }; - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) - var $export = __webpack_require__(8); - var abs = Math.abs; - - $export($export.S, 'Math', { - hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars - var sum = 0; - var i = 0; - var aLen = arguments.length; - var larg = 0; - var arg, div; - while (i < aLen) { - arg = abs(arguments[i++]); - if (larg < arg) { - div = larg / arg; - sum = sum * div * div + 1; - larg = arg; - } else if (arg > 0) { - div = arg / larg; - sum += div * div; - } else sum += arg; - } - return larg === Infinity ? Infinity : larg * Math.sqrt(sum); - } - }); - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.18 Math.imul(x, y) - var $export = __webpack_require__(8); - var $imul = Math.imul; - - // some WebKit versions fails with big numbers, some has wrong arity - $export($export.S + $export.F * __webpack_require__(7)(function () { - return $imul(0xffffffff, 5) != -5 || $imul.length != 2; - }), 'Math', { - imul: function imul(x, y) { - var UINT16 = 0xffff; - var xn = +x; - var yn = +y; - var xl = UINT16 & xn; - var yl = UINT16 & yn; - return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); - } - }); - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.21 Math.log10(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log10: function log10(x) { - return Math.log(x) * Math.LOG10E; - } - }); - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.20 Math.log1p(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { log1p: __webpack_require__(104) }); - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.22 Math.log2(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log2: function log2(x) { - return Math.log(x) / Math.LN2; - } - }); - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.28 Math.sign(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { sign: __webpack_require__(108) }); - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.30 Math.sinh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(112); - var exp = Math.exp; - - // V8 near Chromium 38 has a problem with very small numbers - $export($export.S + $export.F * __webpack_require__(7)(function () { - return !Math.sinh(-2e-17) != -2e-17; - }), 'Math', { - sinh: function sinh(x) { - return Math.abs(x = +x) < 1 - ? (expm1(x) - expm1(-x)) / 2 - : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); - } - }); - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.33 Math.tanh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(112); - var exp = Math.exp; - - $export($export.S, 'Math', { - tanh: function tanh(x) { - var a = expm1(x = +x); - var b = expm1(-x); - return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); - } - }); - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.34 Math.trunc(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - trunc: function trunc(it) { - return (it > 0 ? Math.floor : Math.ceil)(it); - } - }); - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toAbsoluteIndex = __webpack_require__(40); - var fromCharCode = String.fromCharCode; - var $fromCodePoint = String.fromCodePoint; - - // length should be 1, old FF problem - $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { - // 21.1.2.2 String.fromCodePoint(...codePoints) - fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars - var res = []; - var aLen = arguments.length; - var i = 0; - var code; - while (aLen > i) { - code = +arguments[i++]; - if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); - res.push(code < 0x10000 - ? fromCharCode(code) - : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) - ); - } return res.join(''); - } - }); - - -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(33); - var toLength = __webpack_require__(38); - - $export($export.S, 'String', { - // 21.1.2.4 String.raw(callSite, ...substitutions) - raw: function raw(callSite) { - var tpl = toIObject(callSite.raw); - var len = toLength(tpl.length); - var aLen = arguments.length; - var res = []; - var i = 0; - while (len > i) { - res.push(String(tpl[i++])); - if (i < aLen) res.push(String(arguments[i])); - } return res.join(''); - } - }); - - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.1.3.25 String.prototype.trim() - __webpack_require__(83)('trim', function ($trim) { - return function trim() { - return $trim(this, 3); - }; - }); - - -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $at = __webpack_require__(128)(true); - - // 21.1.3.27 String.prototype[@@iterator]() - __webpack_require__(129)(String, 'String', function (iterated) { - this._t = String(iterated); // target - this._i = 0; // next index - // 21.1.5.2.1 %StringIteratorPrototype%.next() - }, function () { - var O = this._t; - var index = this._i; - var point; - if (index >= O.length) return { value: undefined, done: true }; - point = $at(O, index); - this._i += point.length; - return { value: point, done: false }; - }); - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(39); - var defined = __webpack_require__(36); - // true -> String#at - // false -> String#codePointAt - module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; - }; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(22); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(130); - var $iterCreate = __webpack_require__(131); - var setToStringTag = __webpack_require__(26); - var getPrototypeOf = __webpack_require__(59); - var ITERATOR = __webpack_require__(27)('iterator'); - var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` - var FF_ITERATOR = '@@iterator'; - var KEYS = 'keys'; - var VALUES = 'values'; - - var returnThis = function () { return this; }; - - module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { - $iterCreate(Constructor, NAME, next); - var getMethod = function (kind) { - if (!BUGGY && kind in proto) return proto[kind]; - switch (kind) { - case KEYS: return function keys() { return new Constructor(this, kind); }; - case VALUES: return function values() { return new Constructor(this, kind); }; - } return function entries() { return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator'; - var DEF_VALUES = DEFAULT == VALUES; - var VALUES_BUG = false; - var proto = Base.prototype; - var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; - var $default = $native || getMethod(DEFAULT); - var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; - var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; - var methods, key, IteratorPrototype; - // Fix native - if ($anyNative) { - IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); - if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEF_VALUES && $native && $native.name !== VALUES) { - VALUES_BUG = true; - $default = function values() { return $native.call(this); }; - } - // Define iterator - if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if (DEFAULT) { - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if (FORCED) for (key in methods) { - if (!(key in proto)) redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; - }; - - -/***/ }), -/* 130 */ -/***/ (function(module, exports) { - - module.exports = {}; - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var create = __webpack_require__(47); - var descriptor = __webpack_require__(17); - var setToStringTag = __webpack_require__(26); - var IteratorPrototype = {}; - - // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() - __webpack_require__(10)(IteratorPrototype, __webpack_require__(27)('iterator'), function () { return this; }); - - module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); - }; - - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $at = __webpack_require__(128)(false); - $export($export.P, 'String', { - // 21.1.3.3 String.prototype.codePointAt(pos) - codePointAt: function codePointAt(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(38); - var context = __webpack_require__(134); - var ENDS_WITH = 'endsWith'; - var $endsWith = ''[ENDS_WITH]; - - $export($export.P + $export.F * __webpack_require__(136)(ENDS_WITH), 'String', { - endsWith: function endsWith(searchString /* , endPosition = @length */) { - var that = context(this, searchString, ENDS_WITH); - var endPosition = arguments.length > 1 ? arguments[1] : undefined; - var len = toLength(that.length); - var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); - var search = String(searchString); - return $endsWith - ? $endsWith.call(that, search, end) - : that.slice(end - search.length, end) === search; - } - }); - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - - // helper for String#{startsWith, endsWith, includes} - var isRegExp = __webpack_require__(135); - var defined = __webpack_require__(36); - - module.exports = function (that, searchString, NAME) { - if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); - return String(defined(that)); - }; - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.8 IsRegExp(argument) - var isObject = __webpack_require__(13); - var cof = __webpack_require__(35); - var MATCH = __webpack_require__(27)('match'); - module.exports = function (it) { - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); - }; - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - - var MATCH = __webpack_require__(27)('match'); - module.exports = function (KEY) { - var re = /./; - try { - '/./'[KEY](re); - } catch (e) { - try { - re[MATCH] = false; - return !'/./'[KEY](re); - } catch (f) { /* empty */ } - } return true; - }; - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.7 String.prototype.includes(searchString, position = 0) - 'use strict'; - var $export = __webpack_require__(8); - var context = __webpack_require__(134); - var INCLUDES = 'includes'; - - $export($export.P + $export.F * __webpack_require__(136)(INCLUDES), 'String', { - includes: function includes(searchString /* , position = 0 */) { - return !!~context(this, searchString, INCLUDES) - .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - - $export($export.P, 'String', { - // 21.1.3.13 String.prototype.repeat(count) - repeat: __webpack_require__(91) - }); - - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(38); - var context = __webpack_require__(134); - var STARTS_WITH = 'startsWith'; - var $startsWith = ''[STARTS_WITH]; - - $export($export.P + $export.F * __webpack_require__(136)(STARTS_WITH), 'String', { - startsWith: function startsWith(searchString /* , position = 0 */) { - var that = context(this, searchString, STARTS_WITH); - var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); - var search = String(searchString); - return $startsWith - ? $startsWith.call(that, search, index) - : that.slice(index, index + search.length) === search; - } - }); - - -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.2 String.prototype.anchor(name) - __webpack_require__(141)('anchor', function (createHTML) { - return function anchor(name) { - return createHTML(this, 'a', 'name', name); - }; - }); - - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var fails = __webpack_require__(7); - var defined = __webpack_require__(36); - var quot = /"/g; - // B.2.3.2.1 CreateHTML(string, tag, attribute, value) - var createHTML = function (string, tag, attribute, value) { - var S = String(defined(string)); - var p1 = '<' + tag; - if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; - return p1 + '>' + S + ''; - }; - module.exports = function (NAME, exec) { - var O = {}; - O[NAME] = exec(createHTML); - $export($export.P + $export.F * fails(function () { - var test = ''[NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }), 'String', O); - }; - - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.3 String.prototype.big() - __webpack_require__(141)('big', function (createHTML) { - return function big() { - return createHTML(this, 'big', '', ''); - }; - }); - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.4 String.prototype.blink() - __webpack_require__(141)('blink', function (createHTML) { - return function blink() { - return createHTML(this, 'blink', '', ''); - }; - }); - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.5 String.prototype.bold() - __webpack_require__(141)('bold', function (createHTML) { - return function bold() { - return createHTML(this, 'b', '', ''); - }; - }); - - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.6 String.prototype.fixed() - __webpack_require__(141)('fixed', function (createHTML) { - return function fixed() { - return createHTML(this, 'tt', '', ''); - }; - }); - - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.7 String.prototype.fontcolor(color) - __webpack_require__(141)('fontcolor', function (createHTML) { - return function fontcolor(color) { - return createHTML(this, 'font', 'color', color); - }; - }); - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.8 String.prototype.fontsize(size) - __webpack_require__(141)('fontsize', function (createHTML) { - return function fontsize(size) { - return createHTML(this, 'font', 'size', size); - }; - }); - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.9 String.prototype.italics() - __webpack_require__(141)('italics', function (createHTML) { - return function italics() { - return createHTML(this, 'i', '', ''); - }; - }); - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.10 String.prototype.link(url) - __webpack_require__(141)('link', function (createHTML) { - return function link(url) { - return createHTML(this, 'a', 'href', url); - }; - }); - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.11 String.prototype.small() - __webpack_require__(141)('small', function (createHTML) { - return function small() { - return createHTML(this, 'small', '', ''); - }; - }); - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.12 String.prototype.strike() - __webpack_require__(141)('strike', function (createHTML) { - return function strike() { - return createHTML(this, 'strike', '', ''); - }; - }); - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.13 String.prototype.sub() - __webpack_require__(141)('sub', function (createHTML) { - return function sub() { - return createHTML(this, 'sub', '', ''); - }; - }); - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.14 String.prototype.sup() - __webpack_require__(141)('sup', function (createHTML) { - return function sup() { - return createHTML(this, 'sup', '', ''); - }; - }); - - -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.3.1 / 15.9.4.4 Date.now() - var $export = __webpack_require__(8); - - $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); - - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var toPrimitive = __webpack_require__(16); - - $export($export.P + $export.F * __webpack_require__(7)(function () { - return new Date(NaN).toJSON() !== null - || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; - }), 'Date', { - // eslint-disable-next-line no-unused-vars - toJSON: function toJSON(key) { - var O = toObject(this); - var pv = toPrimitive(O); - return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); - } - }); - - -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var $export = __webpack_require__(8); - var toISOString = __webpack_require__(157); - - // PhantomJS / old WebKit has a broken implementations - $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { - toISOString: toISOString - }); - - -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var fails = __webpack_require__(7); - var getTime = Date.prototype.getTime; - var $toISOString = Date.prototype.toISOString; - - var lz = function (num) { - return num > 9 ? num : '0' + num; - }; - - // PhantomJS / old WebKit has a broken implementations - module.exports = (fails(function () { - return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; - }) || !fails(function () { - $toISOString.call(new Date(NaN)); - })) ? function toISOString() { - if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); - var d = this; - var y = d.getUTCFullYear(); - var m = d.getUTCMilliseconds(); - var s = y < 0 ? '-' : y > 9999 ? '+' : ''; - return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + - '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + - 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + - ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; - } : $toISOString; - - -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - - var DateProto = Date.prototype; - var INVALID_DATE = 'Invalid Date'; - var TO_STRING = 'toString'; - var $toString = DateProto[TO_STRING]; - var getTime = DateProto.getTime; - if (new Date(NaN) + '' != INVALID_DATE) { - __webpack_require__(18)(DateProto, TO_STRING, function toString() { - var value = getTime.call(this); - // eslint-disable-next-line no-self-compare - return value === value ? $toString.call(this) : INVALID_DATE; - }); - } - - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - - var TO_PRIMITIVE = __webpack_require__(27)('toPrimitive'); - var proto = Date.prototype; - - if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(160)); - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - var NUMBER = 'number'; - - module.exports = function (hint) { - if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); - return toPrimitive(anObject(this), hint != NUMBER); - }; - - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) - var $export = __webpack_require__(8); - - $export($export.S, 'Array', { isArray: __webpack_require__(45) }); - - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var ctx = __webpack_require__(23); - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var call = __webpack_require__(163); - var isArrayIter = __webpack_require__(164); - var toLength = __webpack_require__(38); - var createProperty = __webpack_require__(165); - var getIterFn = __webpack_require__(166); - - $export($export.S + $export.F * !__webpack_require__(167)(function (iter) { Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var C = typeof this == 'function' ? this : Array; - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var index = 0; - var iterFn = getIterFn(O); - var length, result, step, iterator; - if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { - for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = toLength(O.length); - for (result = new C(length); length > index; index++) { - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; - } - }); - - -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { - - // call something on iterator step with safe closing on error - var anObject = __webpack_require__(12); - module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; - } - }; - - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - - // check on default Array iterator - var Iterators = __webpack_require__(130); - var ITERATOR = __webpack_require__(27)('iterator'); - var ArrayProto = Array.prototype; - - module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); - }; - - -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $defineProperty = __webpack_require__(11); - var createDesc = __webpack_require__(17); - - module.exports = function (object, index, value) { - if (index in object) $defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; - }; - - -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { - - var classof = __webpack_require__(75); - var ITERATOR = __webpack_require__(27)('iterator'); - var Iterators = __webpack_require__(130); - module.exports = __webpack_require__(9).getIteratorMethod = function (it) { - if (it != undefined) return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; - }; - - -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - - var ITERATOR = __webpack_require__(27)('iterator'); - var SAFE_CLOSING = false; - - try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); - } catch (e) { /* empty */ } - - module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; - }; - - -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var createProperty = __webpack_require__(165); - - // WebKit Array.of isn't generic - $export($export.S + $export.F * __webpack_require__(7)(function () { - function F() { /* empty */ } - return !(Array.of.call(F) instanceof F); - }), 'Array', { - // 22.1.2.3 Array.of( ...items) - of: function of(/* ...args */) { - var index = 0; - var aLen = arguments.length; - var result = new (typeof this == 'function' ? this : Array)(aLen); - while (aLen > index) createProperty(result, index, arguments[index++]); - result.length = aLen; - return result; - } - }); - - -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.13 Array.prototype.join(separator) - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(33); - var arrayJoin = [].join; - - // fallback for not array-like strings - $export($export.P + $export.F * (__webpack_require__(34) != Object || !__webpack_require__(170)(arrayJoin)), 'Array', { - join: function join(separator) { - return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); - } - }); - - -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var fails = __webpack_require__(7); - - module.exports = function (method, arg) { - return !!method && fails(function () { - // eslint-disable-next-line no-useless-call - arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); - }); - }; - - -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var html = __webpack_require__(49); - var cof = __webpack_require__(35); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - var arraySlice = [].slice; - - // fallback for not array-like ES3 strings and DOM objects - $export($export.P + $export.F * __webpack_require__(7)(function () { - if (html) arraySlice.call(html); - }), 'Array', { - slice: function slice(begin, end) { - var len = toLength(this.length); - var klass = cof(this); - end = end === undefined ? len : end; - if (klass == 'Array') return arraySlice.call(this, begin, end); - var start = toAbsoluteIndex(begin, len); - var upTo = toAbsoluteIndex(end, len); - var size = toLength(upTo - start); - var cloned = new Array(size); - var i = 0; - for (; i < size; i++) cloned[i] = klass == 'String' - ? this.charAt(start + i) - : this[start + i]; - return cloned; - } - }); - - -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(24); - var toObject = __webpack_require__(46); - var fails = __webpack_require__(7); - var $sort = [].sort; - var test = [1, 2, 3]; - - $export($export.P + $export.F * (fails(function () { - // IE8- - test.sort(undefined); - }) || !fails(function () { - // V8 bug - test.sort(null); - // Old WebKit - }) || !__webpack_require__(170)($sort)), 'Array', { - // 22.1.3.25 Array.prototype.sort(comparefn) - sort: function sort(comparefn) { - return comparefn === undefined - ? $sort.call(toObject(this)) - : $sort.call(toObject(this), aFunction(comparefn)); - } - }); - - -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $forEach = __webpack_require__(174)(0); - var STRICT = __webpack_require__(170)([].forEach, true); - - $export($export.P + $export.F * !STRICT, 'Array', { - // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) - forEach: function forEach(callbackfn /* , thisArg */) { - return $forEach(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { - - // 0 -> Array#forEach - // 1 -> Array#map - // 2 -> Array#filter - // 3 -> Array#some - // 4 -> Array#every - // 5 -> Array#find - // 6 -> Array#findIndex - var ctx = __webpack_require__(23); - var IObject = __webpack_require__(34); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var asc = __webpack_require__(175); - module.exports = function (TYPE, $create) { - var IS_MAP = TYPE == 1; - var IS_FILTER = TYPE == 2; - var IS_SOME = TYPE == 3; - var IS_EVERY = TYPE == 4; - var IS_FIND_INDEX = TYPE == 6; - var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; - var create = $create || asc; - return function ($this, callbackfn, that) { - var O = toObject($this); - var self = IObject(O); - var f = ctx(callbackfn, that, 3); - var length = toLength(self.length); - var index = 0; - var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; - var val, res; - for (;length > index; index++) if (NO_HOLES || index in self) { - val = self[index]; - res = f(val, index, O); - if (TYPE) { - if (IS_MAP) result[index] = res; // map - else if (res) switch (TYPE) { - case 3: return true; // some - case 5: return val; // find - case 6: return index; // findIndex - case 2: result.push(val); // filter - } else if (IS_EVERY) return false; // every - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; - }; - }; - - -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { - - // 9.4.2.3 ArraySpeciesCreate(originalArray, length) - var speciesConstructor = __webpack_require__(176); - - module.exports = function (original, length) { - return new (speciesConstructor(original))(length); - }; - - -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var isArray = __webpack_require__(45); - var SPECIES = __webpack_require__(27)('species'); - - module.exports = function (original) { - var C; - if (isArray(original)) { - C = original.constructor; - // cross-realm fallback - if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; - if (isObject(C)) { - C = C[SPECIES]; - if (C === null) C = undefined; - } - } return C === undefined ? Array : C; - }; - - -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $map = __webpack_require__(174)(1); - - $export($export.P + $export.F * !__webpack_require__(170)([].map, true), 'Array', { - // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) - map: function map(callbackfn /* , thisArg */) { - return $map(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $filter = __webpack_require__(174)(2); - - $export($export.P + $export.F * !__webpack_require__(170)([].filter, true), 'Array', { - // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) - filter: function filter(callbackfn /* , thisArg */) { - return $filter(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $some = __webpack_require__(174)(3); - - $export($export.P + $export.F * !__webpack_require__(170)([].some, true), 'Array', { - // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) - some: function some(callbackfn /* , thisArg */) { - return $some(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $every = __webpack_require__(174)(4); - - $export($export.P + $export.F * !__webpack_require__(170)([].every, true), 'Array', { - // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) - every: function every(callbackfn /* , thisArg */) { - return $every(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(182); - - $export($export.P + $export.F * !__webpack_require__(170)([].reduce, true), 'Array', { - // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) - reduce: function reduce(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], false); - } - }); - - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - - var aFunction = __webpack_require__(24); - var toObject = __webpack_require__(46); - var IObject = __webpack_require__(34); - var toLength = __webpack_require__(38); - - module.exports = function (that, callbackfn, aLen, memo, isRight) { - aFunction(callbackfn); - var O = toObject(that); - var self = IObject(O); - var length = toLength(O.length); - var index = isRight ? length - 1 : 0; - var i = isRight ? -1 : 1; - if (aLen < 2) for (;;) { - if (index in self) { - memo = self[index]; - index += i; - break; - } - index += i; - if (isRight ? index < 0 : length <= index) { - throw TypeError('Reduce of empty array with no initial value'); - } - } - for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; - - -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(182); - - $export($export.P + $export.F * !__webpack_require__(170)([].reduceRight, true), 'Array', { - // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) - reduceRight: function reduceRight(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], true); - } - }); - - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $indexOf = __webpack_require__(37)(false); - var $native = [].indexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(170)($native)), 'Array', { - // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) - indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { - return NEGATIVE_ZERO - // convert -0 to +0 - ? $native.apply(this, arguments) || 0 - : $indexOf(this, searchElement, arguments[1]); - } - }); - - -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(33); - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - var $native = [].lastIndexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(170)($native)), 'Array', { - // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { - // convert -0 to +0 - if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; - var O = toIObject(this); - var length = toLength(O.length); - var index = length - 1; - if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); - if (index < 0) index = length + index; - for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; - return -1; - } - }); - - -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { copyWithin: __webpack_require__(187) }); - - __webpack_require__(188)('copyWithin'); - - -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - 'use strict'; - var toObject = __webpack_require__(46); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - - module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { - var O = toObject(this); - var len = toLength(O.length); - var to = toAbsoluteIndex(target, len); - var from = toAbsoluteIndex(start, len); - var end = arguments.length > 2 ? arguments[2] : undefined; - var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); - var inc = 1; - if (from < to && to < from + count) { - inc = -1; - from += count - 1; - to += count - 1; - } - while (count-- > 0) { - if (from in O) O[to] = O[from]; - else delete O[to]; - to += inc; - from += inc; - } return O; - }; - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.31 Array.prototype[@@unscopables] - var UNSCOPABLES = __webpack_require__(27)('unscopables'); - var ArrayProto = Array.prototype; - if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); - module.exports = function (key) { - ArrayProto[UNSCOPABLES][key] = true; - }; - - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { fill: __webpack_require__(190) }); - - __webpack_require__(188)('fill'); - - -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - 'use strict'; - var toObject = __webpack_require__(46); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - module.exports = function fill(value /* , start = 0, end = @length */) { - var O = toObject(this); - var length = toLength(O.length); - var aLen = arguments.length; - var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); - var end = aLen > 2 ? arguments[2] : undefined; - var endPos = end === undefined ? length : toAbsoluteIndex(end, length); - while (endPos > index) O[index++] = value; - return O; - }; - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(174)(5); - var KEY = 'find'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - find: function find(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(188)(KEY); - - -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(174)(6); - var KEY = 'findIndex'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - findIndex: function findIndex(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(188)(KEY); - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(194)('Array'); - - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var dP = __webpack_require__(11); - var DESCRIPTORS = __webpack_require__(6); - var SPECIES = __webpack_require__(27)('species'); - - module.exports = function (KEY) { - var C = global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } - }); - }; - - -/***/ }), -/* 195 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var addToUnscopables = __webpack_require__(188); - var step = __webpack_require__(196); - var Iterators = __webpack_require__(130); - var toIObject = __webpack_require__(33); - - // 22.1.3.4 Array.prototype.entries() - // 22.1.3.13 Array.prototype.keys() - // 22.1.3.29 Array.prototype.values() - // 22.1.3.30 Array.prototype[@@iterator]() - module.exports = __webpack_require__(129)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind - // 22.1.5.2.1 %ArrayIteratorPrototype%.next() - }, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); - }, 'values'); - - // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) - Iterators.Arguments = Iterators.Array; - - addToUnscopables('keys'); - addToUnscopables('values'); - addToUnscopables('entries'); - - -/***/ }), -/* 196 */ -/***/ (function(module, exports) { - - module.exports = function (done, value) { - return { value: value, done: !!done }; - }; - - -/***/ }), -/* 197 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var inheritIfRequired = __webpack_require__(88); - var dP = __webpack_require__(11).f; - var gOPN = __webpack_require__(51).f; - var isRegExp = __webpack_require__(135); - var $flags = __webpack_require__(198); - var $RegExp = global.RegExp; - var Base = $RegExp; - var proto = $RegExp.prototype; - var re1 = /a/g; - var re2 = /a/g; - // "new" creates a new object, old webkit buggy here - var CORRECT_NEW = new $RegExp(re1) !== re1; - - if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { - re2[__webpack_require__(27)('match')] = false; - // RegExp constructor can alter flags and IsRegExp works correct with @@match - return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; - }))) { - $RegExp = function RegExp(p, f) { - var tiRE = this instanceof $RegExp; - var piRE = isRegExp(p); - var fiU = f === undefined; - return !tiRE && piRE && p.constructor === $RegExp && fiU ? p - : inheritIfRequired(CORRECT_NEW - ? new Base(piRE && !fiU ? p.source : p, f) - : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) - , tiRE ? this : proto, $RegExp); - }; - var proxy = function (key) { - key in $RegExp || dP($RegExp, key, { - configurable: true, - get: function () { return Base[key]; }, - set: function (it) { Base[key] = it; } - }); - }; - for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); - proto.constructor = $RegExp; - $RegExp.prototype = proto; - __webpack_require__(18)(global, 'RegExp', $RegExp); - } - - __webpack_require__(194)('RegExp'); - - -/***/ }), -/* 198 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.2.5.3 get RegExp.prototype.flags - var anObject = __webpack_require__(12); - module.exports = function () { - var that = anObject(this); - var result = ''; - if (that.global) result += 'g'; - if (that.ignoreCase) result += 'i'; - if (that.multiline) result += 'm'; - if (that.unicode) result += 'u'; - if (that.sticky) result += 'y'; - return result; - }; - - -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var regexpExec = __webpack_require__(200); - __webpack_require__(8)({ - target: 'RegExp', - proto: true, - forced: regexpExec !== /./.exec - }, { - exec: regexpExec - }); - - -/***/ }), -/* 200 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var regexpFlags = __webpack_require__(198); - - var nativeExec = RegExp.prototype.exec; - // This always refers to the native implementation, because the - // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, - // which loads this file before patching the method. - var nativeReplace = String.prototype.replace; - - var patchedExec = nativeExec; - - var LAST_INDEX = 'lastIndex'; - - var UPDATES_LAST_INDEX_WRONG = (function () { - var re1 = /a/, - re2 = /b*/g; - nativeExec.call(re1, 'a'); - nativeExec.call(re2, 'a'); - return re1[LAST_INDEX] !== 0 || re2[LAST_INDEX] !== 0; - })(); - - // nonparticipating capturing group, copied from es5-shim's String#split patch. - var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; - - var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED; - - if (PATCH) { - patchedExec = function exec(str) { - var re = this; - var lastIndex, reCopy, match, i; - - if (NPCG_INCLUDED) { - reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re)); - } - if (UPDATES_LAST_INDEX_WRONG) lastIndex = re[LAST_INDEX]; - - match = nativeExec.call(re, str); - - if (UPDATES_LAST_INDEX_WRONG && match) { - re[LAST_INDEX] = re.global ? match.index + match[0].length : lastIndex; - } - if (NPCG_INCLUDED && match && match.length > 1) { - // Fix browsers whose `exec` methods don't consistently return `undefined` - // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ - // eslint-disable-next-line no-loop-func - nativeReplace.call(match[0], reCopy, function () { - for (i = 1; i < arguments.length - 2; i++) { - if (arguments[i] === undefined) match[i] = undefined; - } - }); - } - - return match; - }; - } - - module.exports = patchedExec; - - -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(202); - var anObject = __webpack_require__(12); - var $flags = __webpack_require__(198); - var DESCRIPTORS = __webpack_require__(6); - var TO_STRING = 'toString'; - var $toString = /./[TO_STRING]; - - var define = function (fn) { - __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); - }; - - // 21.2.5.14 RegExp.prototype.toString() - if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { - define(function toString() { - var R = anObject(this); - return '/'.concat(R.source, '/', - 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); - }); - // FF44- RegExp#toString has a wrong name - } else if ($toString.name != TO_STRING) { - define(function toString() { - return $toString.call(this); - }); - } - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.2.5.3 get RegExp.prototype.flags() - if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { - configurable: true, - get: __webpack_require__(198) - }); - - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var anObject = __webpack_require__(12); - var toLength = __webpack_require__(38); - var advanceStringIndex = __webpack_require__(204); - var regExpExec = __webpack_require__(205); - - // @@match logic - __webpack_require__(206)('match', 1, function (defined, MATCH, $match, maybeCallNative) { - return [ - // `String.prototype.match` method - // https://tc39.github.io/ecma262/#sec-string.prototype.match - function match(regexp) { - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[MATCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); - }, - // `RegExp.prototype[@@match]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match - function (regexp) { - var res = maybeCallNative($match, regexp, this); - if (res.done) return res.value; - var rx = anObject(regexp); - var S = String(this); - if (!rx.global) return regExpExec(rx, S); - var fullUnicode = rx.unicode; - rx.lastIndex = 0; - var A = []; - var n = 0; - var result; - while ((result = regExpExec(rx, S)) !== null) { - var matchStr = String(result[0]); - A[n] = matchStr; - if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); - n++; - } - return n === 0 ? null : A; - } - ]; - }); - - -/***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var at = __webpack_require__(128)(true); - - // `AdvanceStringIndex` abstract operation - // https://tc39.github.io/ecma262/#sec-advancestringindex - module.exports = function (S, index, unicode) { - return index + (unicode ? at(S, index).length : 1); - }; - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var classof = __webpack_require__(75); - var builtinExec = RegExp.prototype.exec; - - // `RegExpExec` abstract operation - // https://tc39.github.io/ecma262/#sec-regexpexec - module.exports = function (R, S) { - var exec = R.exec; - if (typeof exec === 'function') { - var result = exec.call(R, S); - if (typeof result !== 'object') { - throw new TypeError('RegExp exec method returned something other than an Object or null'); - } - return result; - } - if (classof(R) !== 'RegExp') { - throw new TypeError('RegExp#exec called on incompatible receiver'); - } - return builtinExec.call(R, S); - }; - - -/***/ }), -/* 206 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(199); - var redefine = __webpack_require__(18); - var hide = __webpack_require__(10); - var fails = __webpack_require__(7); - var defined = __webpack_require__(36); - var wks = __webpack_require__(27); - var regexpExec = __webpack_require__(200); - - var SPECIES = wks('species'); - - var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () { - // #replace needs built-in support for named groups. - // #match works fine because it just return the exec results, even if it has - // a "grops" property. - var re = /./; - re.exec = function () { - var result = []; - result.groups = { a: '7' }; - return result; - }; - return ''.replace(re, '$') !== '7'; - }); - - var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = (function () { - // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec - var re = /(?:)/; - var originalExec = re.exec; - re.exec = function () { return originalExec.apply(this, arguments); }; - var result = 'ab'.split(re); - return result.length === 2 && result[0] === 'a' && result[1] === 'b'; - })(); - - module.exports = function (KEY, length, exec) { - var SYMBOL = wks(KEY); - - var DELEGATES_TO_SYMBOL = !fails(function () { - // String methods call symbol-named RegEp methods - var O = {}; - O[SYMBOL] = function () { return 7; }; - return ''[KEY](O) != 7; - }); - - var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL ? !fails(function () { - // Symbol-named RegExp methods call .exec - var execCalled = false; - var re = /a/; - re.exec = function () { execCalled = true; return null; }; - if (KEY === 'split') { - // RegExp[@@split] doesn't call the regex's exec method, but first creates - // a new one. We need to return the patched regex when creating the new one. - re.constructor = {}; - re.constructor[SPECIES] = function () { return re; }; - } - re[SYMBOL](''); - return !execCalled; - }) : undefined; - - if ( - !DELEGATES_TO_SYMBOL || - !DELEGATES_TO_EXEC || - (KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) || - (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) - ) { - var nativeRegExpMethod = /./[SYMBOL]; - var fns = exec( - defined, - SYMBOL, - ''[KEY], - function maybeCallNative(nativeMethod, regexp, str, arg2, forceStringMethod) { - if (regexp.exec === regexpExec) { - if (DELEGATES_TO_SYMBOL && !forceStringMethod) { - // The native String method already delegates to @@method (this - // polyfilled function), leasing to infinite recursion. - // We avoid it by directly calling the native @@method method. - return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) }; - } - return { done: true, value: nativeMethod.call(str, regexp, arg2) }; - } - return { done: false }; - } - ); - var strfn = fns[0]; - var rxfn = fns[1]; - - redefine(String.prototype, KEY, strfn); - hide(RegExp.prototype, SYMBOL, length == 2 - // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) - // 21.2.5.11 RegExp.prototype[@@split](string, limit) - ? function (string, arg) { return rxfn.call(string, this, arg); } - // 21.2.5.6 RegExp.prototype[@@match](string) - // 21.2.5.9 RegExp.prototype[@@search](string) - : function (string) { return rxfn.call(string, this); } - ); - } - }; - - -/***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var anObject = __webpack_require__(12); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var toInteger = __webpack_require__(39); - var advanceStringIndex = __webpack_require__(204); - var regExpExec = __webpack_require__(205); - var max = Math.max; - var min = Math.min; - var floor = Math.floor; - var SUBSTITUTION_SYMBOLS = /\$([$&`']|\d\d?|<[^>]*>)/g; - var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&`']|\d\d?)/g; - - var maybeToString = function (it) { - return it === undefined ? it : String(it); - }; - - // @@replace logic - __webpack_require__(206)('replace', 2, function (defined, REPLACE, $replace, maybeCallNative) { - return [ - // `String.prototype.replace` method - // https://tc39.github.io/ecma262/#sec-string.prototype.replace - function replace(searchValue, replaceValue) { - var O = defined(this); - var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; - return fn !== undefined - ? fn.call(searchValue, O, replaceValue) - : $replace.call(String(O), searchValue, replaceValue); - }, - // `RegExp.prototype[@@replace]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace - function (regexp, replaceValue) { - var res = maybeCallNative($replace, regexp, this, replaceValue); - if (res.done) return res.value; - - var rx = anObject(regexp); - var S = String(this); - var functionalReplace = typeof replaceValue === 'function'; - if (!functionalReplace) replaceValue = String(replaceValue); - var global = rx.global; - if (global) { - var fullUnicode = rx.unicode; - rx.lastIndex = 0; - } - var results = []; - while (true) { - var result = regExpExec(rx, S); - if (result === null) break; - results.push(result); - if (!global) break; - var matchStr = String(result[0]); - if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); - } - var accumulatedResult = ''; - var nextSourcePosition = 0; - for (var i = 0; i < results.length; i++) { - result = results[i]; - var matched = String(result[0]); - var position = max(min(toInteger(result.index), S.length), 0); - var captures = []; - // NOTE: This is equivalent to - // captures = result.slice(1).map(maybeToString) - // but for some reason `nativeSlice.call(result, 1, result.length)` (called in - // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and - // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. - for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); - var namedCaptures = result.groups; - if (functionalReplace) { - var replacerArgs = [matched].concat(captures, position, S); - if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); - var replacement = String(replaceValue.apply(undefined, replacerArgs)); - } else { - replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); - } - if (position >= nextSourcePosition) { - accumulatedResult += S.slice(nextSourcePosition, position) + replacement; - nextSourcePosition = position + matched.length; - } - } - return accumulatedResult + S.slice(nextSourcePosition); - } - ]; - - // https://tc39.github.io/ecma262/#sec-getsubstitution - function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { - var tailPos = position + matched.length; - var m = captures.length; - var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; - if (namedCaptures !== undefined) { - namedCaptures = toObject(namedCaptures); - symbols = SUBSTITUTION_SYMBOLS; - } - return $replace.call(replacement, symbols, function (match, ch) { - var capture; - switch (ch.charAt(0)) { - case '$': return '$'; - case '&': return matched; - case '`': return str.slice(0, position); - case "'": return str.slice(tailPos); - case '<': - capture = namedCaptures[ch.slice(1, -1)]; - break; - default: // \d\d? - var n = +ch; - if (n === 0) return match; - if (n > m) { - var f = floor(n / 10); - if (f === 0) return match; - if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); - return match; - } - capture = captures[n - 1]; - } - return capture === undefined ? '' : capture; - }); - } - }); - - -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var anObject = __webpack_require__(12); - var sameValue = __webpack_require__(71); - var regExpExec = __webpack_require__(205); - - // @@search logic - __webpack_require__(206)('search', 1, function (defined, SEARCH, $search, maybeCallNative) { - return [ - // `String.prototype.search` method - // https://tc39.github.io/ecma262/#sec-string.prototype.search - function search(regexp) { - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[SEARCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); - }, - // `RegExp.prototype[@@search]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search - function (regexp) { - var res = maybeCallNative($search, regexp, this); - if (res.done) return res.value; - var rx = anObject(regexp); - var S = String(this); - var previousLastIndex = rx.lastIndex; - if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0; - var result = regExpExec(rx, S); - if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex; - return result === null ? -1 : result.index; - } - ]; - }); - - -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var isRegExp = __webpack_require__(135); - var anObject = __webpack_require__(12); - var speciesConstructor = __webpack_require__(210); - var advanceStringIndex = __webpack_require__(204); - var toLength = __webpack_require__(38); - var callRegExpExec = __webpack_require__(205); - var regexpExec = __webpack_require__(200); - var fails = __webpack_require__(7); - var $min = Math.min; - var $push = [].push; - var $SPLIT = 'split'; - var LENGTH = 'length'; - var LAST_INDEX = 'lastIndex'; - var MAX_UINT32 = 0xffffffff; - - // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError - var SUPPORTS_Y = !fails(function () { RegExp(MAX_UINT32, 'y'); }); - - // @@split logic - __webpack_require__(206)('split', 2, function (defined, SPLIT, $split, maybeCallNative) { - var internalSplit; - if ( - 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || - 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || - 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || - '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || - '.'[$SPLIT](/()()/)[LENGTH] > 1 || - ''[$SPLIT](/.?/)[LENGTH] - ) { - // based on es5-shim implementation, need to rework it - internalSplit = function (separator, limit) { - var string = String(this); - if (separator === undefined && limit === 0) return []; - // If `separator` is not a regex, use native split - if (!isRegExp(separator)) return $split.call(string, separator, limit); - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + - (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; - var splitLimit = limit === undefined ? MAX_UINT32 : limit >>> 0; - // Make `global` and avoid `lastIndex` issues by working with a copy - var separatorCopy = new RegExp(separator.source, flags + 'g'); - var match, lastIndex, lastLength; - while (match = regexpExec.call(separatorCopy, string)) { - lastIndex = separatorCopy[LAST_INDEX]; - if (lastIndex > lastLastIndex) { - output.push(string.slice(lastLastIndex, match.index)); - if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); - lastLength = match[0][LENGTH]; - lastLastIndex = lastIndex; - if (output[LENGTH] >= splitLimit) break; - } - if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop - } - if (lastLastIndex === string[LENGTH]) { - if (lastLength || !separatorCopy.test('')) output.push(''); - } else output.push(string.slice(lastLastIndex)); - return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; - }; - // Chakra, V8 - } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { - internalSplit = function (separator, limit) { - return separator === undefined && limit === 0 ? [] : $split.call(this, separator, limit); - }; - } else { - internalSplit = $split; - } - - return [ - // `String.prototype.split` method - // https://tc39.github.io/ecma262/#sec-string.prototype.split - function split(separator, limit) { - var O = defined(this); - var splitter = separator == undefined ? undefined : separator[SPLIT]; - return splitter !== undefined - ? splitter.call(separator, O, limit) - : internalSplit.call(String(O), separator, limit); - }, - // `RegExp.prototype[@@split]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split - // - // NOTE: This cannot be properly polyfilled in engines that don't support - // the 'y' flag. - function (regexp, limit) { - var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== $split); - if (res.done) return res.value; - - var rx = anObject(regexp); - var S = String(this); - var C = speciesConstructor(rx, RegExp); - - var unicodeMatching = rx.unicode; - var flags = (rx.ignoreCase ? 'i' : '') + - (rx.multiline ? 'm' : '') + - (rx.unicode ? 'u' : '') + - (SUPPORTS_Y ? 'y' : 'g'); - - // ^(? + rx + ) is needed, in combination with some S slicing, to - // simulate the 'y' flag. - var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); - var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; - if (lim === 0) return []; - if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : []; - var p = 0; - var q = 0; - var A = []; - while (q < S.length) { - splitter.lastIndex = SUPPORTS_Y ? q : 0; - var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q)); - var e; - if ( - z === null || - (e = $min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p - ) { - q = advanceStringIndex(S, q, unicodeMatching); - } else { - A.push(S.slice(p, q)); - if (A.length === lim) return A; - for (var i = 1; i <= z.length - 1; i++) { - A.push(z[i]); - if (A.length === lim) return A; - } - q = p = e; - } - } - A.push(S.slice(p)); - return A; - } - ]; - }); - - -/***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.3.20 SpeciesConstructor(O, defaultConstructor) - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(24); - var SPECIES = __webpack_require__(27)('species'); - module.exports = function (O, D) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); - }; - - -/***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(22); - var global = __webpack_require__(4); - var ctx = __webpack_require__(23); - var classof = __webpack_require__(75); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var aFunction = __webpack_require__(24); - var anInstance = __webpack_require__(212); - var forOf = __webpack_require__(213); - var speciesConstructor = __webpack_require__(210); - var task = __webpack_require__(214).set; - var microtask = __webpack_require__(215)(); - var newPromiseCapabilityModule = __webpack_require__(216); - var perform = __webpack_require__(217); - var userAgent = __webpack_require__(218); - var promiseResolve = __webpack_require__(219); - var PROMISE = 'Promise'; - var TypeError = global.TypeError; - var process = global.process; - var versions = process && process.versions; - var v8 = versions && versions.v8 || ''; - var $Promise = global[PROMISE]; - var isNode = classof(process) == 'process'; - var empty = function () { /* empty */ }; - var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; - var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - - var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(27)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } - }(); - - // helpers - var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; - }; - var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); - }; - var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); - }; - var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; - }; - var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); - }; - var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); - }; - var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } - }; - - // constructor polyfill - if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(220)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); - __webpack_require__(26)($Promise, PROMISE); - __webpack_require__(194)(PROMISE); - Wrapper = __webpack_require__(9)[PROMISE]; - - // statics - $export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } - }); - $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } - }); - $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(167)(function (iter) { - $Promise.all(iter)['catch'](empty); - })), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } - }); - - -/***/ }), -/* 212 */ -/***/ (function(module, exports) { - - module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; - }; - - -/***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(23); - var call = __webpack_require__(163); - var isArrayIter = __webpack_require__(164); - var anObject = __webpack_require__(12); - var toLength = __webpack_require__(38); - var getIterFn = __webpack_require__(166); - var BREAK = {}; - var RETURN = {}; - var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; - } - }; - exports.BREAK = BREAK; - exports.RETURN = RETURN; - - -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(23); - var invoke = __webpack_require__(78); - var html = __webpack_require__(49); - var cel = __webpack_require__(15); - var global = __webpack_require__(4); - var process = global.process; - var setTask = global.setImmediate; - var clearTask = global.clearImmediate; - var MessageChannel = global.MessageChannel; - var Dispatch = global.Dispatch; - var counter = 0; - var queue = {}; - var ONREADYSTATECHANGE = 'onreadystatechange'; - var defer, channel, port; - var run = function () { - var id = +this; - // eslint-disable-next-line no-prototype-builtins - if (queue.hasOwnProperty(id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } - }; - var listener = function (event) { - run.call(event.data); - }; - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if (!setTask || !clearTask) { - setTask = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue[++counter] = function () { - // eslint-disable-next-line no-new-func - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (__webpack_require__(35)(process) == 'process') { - defer = function (id) { - process.nextTick(ctx(run, id, 1)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if (MessageChannel) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { - defer = function (id) { - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in cel('script')) { - defer = function (id) { - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(ctx(run, id, 1), 0); - }; - } - } - module.exports = { - set: setTask, - clear: clearTask - }; - - -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var macrotask = __webpack_require__(214).set; - var Observer = global.MutationObserver || global.WebKitMutationObserver; - var process = global.process; - var Promise = global.Promise; - var isNode = __webpack_require__(35)(process) == 'process'; - - module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } - - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; - }; - - -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 25.4.1.5 NewPromiseCapability(C) - var aFunction = __webpack_require__(24); - - function PromiseCapability(C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); - } - - module.exports.f = function (C) { - return new PromiseCapability(C); - }; - - -/***/ }), -/* 217 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return { e: false, v: exec() }; - } catch (e) { - return { e: true, v: e }; - } - }; - - -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var navigator = global.navigator; - - module.exports = navigator && navigator.userAgent || ''; - - -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var newPromiseCapability = __webpack_require__(216); - - module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; - }; - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - - var redefine = __webpack_require__(18); - module.exports = function (target, src, safe) { - for (var key in src) redefine(target, key, src[key], safe); - return target; - }; - - -/***/ }), -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(222); - var validate = __webpack_require__(223); - var MAP = 'Map'; - - // 23.1 Map Objects - module.exports = __webpack_require__(224)(MAP, function (get) { - return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key) { - var entry = strong.getEntry(validate(this, MAP), key); - return entry && entry.v; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value) { - return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); - } - }, strong, true); - - -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var dP = __webpack_require__(11).f; - var create = __webpack_require__(47); - var redefineAll = __webpack_require__(220); - var ctx = __webpack_require__(23); - var anInstance = __webpack_require__(212); - var forOf = __webpack_require__(213); - var $iterDefine = __webpack_require__(129); - var step = __webpack_require__(196); - var setSpecies = __webpack_require__(194); - var DESCRIPTORS = __webpack_require__(6); - var fastKey = __webpack_require__(25).fastKey; - var validate = __webpack_require__(223); - var SIZE = DESCRIPTORS ? '_s' : 'size'; - - var getEntry = function (that, key) { - // fast case - var index = fastKey(key); - var entry; - if (index !== 'F') return that._i[index]; - // frozen object case - for (entry = that._f; entry; entry = entry.n) { - if (entry.k == key) return entry; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = create(null); // index - that._f = undefined; // first entry - that._l = undefined; // last entry - that[SIZE] = 0; // size - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear() { - for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { - entry.r = true; - if (entry.p) entry.p = entry.p.n = undefined; - delete data[entry.i]; - } - that._f = that._l = undefined; - that[SIZE] = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function (key) { - var that = validate(this, NAME); - var entry = getEntry(that, key); - if (entry) { - var next = entry.n; - var prev = entry.p; - delete that._i[entry.i]; - entry.r = true; - if (prev) prev.n = next; - if (next) next.p = prev; - if (that._f == entry) that._f = next; - if (that._l == entry) that._l = prev; - that[SIZE]--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /* , that = undefined */) { - validate(this, NAME); - var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); - var entry; - while (entry = entry ? entry.n : this._f) { - f(entry.v, entry.k, this); - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key) { - return !!getEntry(validate(this, NAME), key); - } - }); - if (DESCRIPTORS) dP(C.prototype, 'size', { - get: function () { - return validate(this, NAME)[SIZE]; - } - }); - return C; - }, - def: function (that, key, value) { - var entry = getEntry(that, key); - var prev, index; - // change existing entry - if (entry) { - entry.v = value; - // create new entry - } else { - that._l = entry = { - i: index = fastKey(key, true), // <- index - k: key, // <- key - v: value, // <- value - p: prev = that._l, // <- previous entry - n: undefined, // <- next entry - r: false // <- removed - }; - if (!that._f) that._f = entry; - if (prev) prev.n = entry; - that[SIZE]++; - // add to index - if (index !== 'F') that._i[index] = entry; - } return that; - }, - getEntry: getEntry, - setStrong: function (C, NAME, IS_MAP) { - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - $iterDefine(C, NAME, function (iterated, kind) { - this._t = validate(iterated, NAME); // target - this._k = kind; // kind - this._l = undefined; // previous - }, function () { - var that = this; - var kind = that._k; - var entry = that._l; - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - // get next entry - if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { - // or finish the iteration - that._t = undefined; - return step(1); - } - // return step by kind - if (kind == 'keys') return step(0, entry.k); - if (kind == 'values') return step(0, entry.v); - return step(0, [entry.k, entry.v]); - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); - - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(NAME); - } - }; - - -/***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it, TYPE) { - if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); - return it; - }; - - -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var redefineAll = __webpack_require__(220); - var meta = __webpack_require__(25); - var forOf = __webpack_require__(213); - var anInstance = __webpack_require__(212); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var $iterDetect = __webpack_require__(167); - var setToStringTag = __webpack_require__(26); - var inheritIfRequired = __webpack_require__(88); - - module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { - var Base = global[NAME]; - var C = Base; - var ADDER = IS_MAP ? 'set' : 'add'; - var proto = C && C.prototype; - var O = {}; - var fixMethod = function (KEY) { - var fn = proto[KEY]; - redefine(proto, KEY, - KEY == 'delete' ? function (a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'has' ? function has(a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'get' ? function get(a) { - return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } - : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } - ); - }; - if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { - new C().entries().next(); - }))) { - // create collection constructor - C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); - redefineAll(C.prototype, methods); - meta.NEED = true; - } else { - var instance = new C(); - // early implementations not supports chaining - var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); - // most early implementations doesn't supports iterables, most modern - not close it correctly - var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new - // for early implementations -0 and +0 not the same - var BUGGY_ZERO = !IS_WEAK && fails(function () { - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new C(); - var index = 5; - while (index--) $instance[ADDER](index, index); - return !$instance.has(-0); - }); - if (!ACCEPT_ITERABLES) { - C = wrapper(function (target, iterable) { - anInstance(target, C, NAME); - var that = inheritIfRequired(new Base(), target, C); - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - return that; - }); - C.prototype = proto; - proto.constructor = C; - } - if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); - // weak collections should not contains .clear method - if (IS_WEAK && proto.clear) delete proto.clear; - } - - setToStringTag(C, NAME); - - O[NAME] = C; - $export($export.G + $export.W + $export.F * (C != Base), O); - - if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); - - return C; - }; - - -/***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(222); - var validate = __webpack_require__(223); - var SET = 'Set'; - - // 23.2 Set Objects - module.exports = __webpack_require__(224)(SET, function (get) { - return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value) { - return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); - } - }, strong); - - -/***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var each = __webpack_require__(174)(0); - var redefine = __webpack_require__(18); - var meta = __webpack_require__(25); - var assign = __webpack_require__(69); - var weak = __webpack_require__(227); - var isObject = __webpack_require__(13); - var validate = __webpack_require__(223); - var NATIVE_WEAK_MAP = __webpack_require__(223); - var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global; - var WEAK_MAP = 'WeakMap'; - var getWeak = meta.getWeak; - var isExtensible = Object.isExtensible; - var uncaughtFrozenStore = weak.ufstore; - var InternalMap; - - var wrapper = function (get) { - return function WeakMap() { - return get(this, arguments.length > 0 ? arguments[0] : undefined); - }; - }; - - var methods = { - // 23.3.3.3 WeakMap.prototype.get(key) - get: function get(key) { - if (isObject(key)) { - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); - return data ? data[this._i] : undefined; - } - }, - // 23.3.3.5 WeakMap.prototype.set(key, value) - set: function set(key, value) { - return weak.def(validate(this, WEAK_MAP), key, value); - } - }; - - // 23.3 WeakMap Objects - var $WeakMap = module.exports = __webpack_require__(224)(WEAK_MAP, wrapper, methods, weak, true, true); - - // IE11 WeakMap frozen keys fix - if (NATIVE_WEAK_MAP && IS_IE11) { - InternalMap = weak.getConstructor(wrapper, WEAK_MAP); - assign(InternalMap.prototype, methods); - meta.NEED = true; - each(['delete', 'has', 'get', 'set'], function (key) { - var proto = $WeakMap.prototype; - var method = proto[key]; - redefine(proto, key, function (a, b) { - // store frozen objects on internal weakmap shim - if (isObject(a) && !isExtensible(a)) { - if (!this._f) this._f = new InternalMap(); - var result = this._f[key](a, b); - return key == 'set' ? this : result; - // store all the rest on native weakmap - } return method.call(this, a, b); - }); - }); - } - - -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var redefineAll = __webpack_require__(220); - var getWeak = __webpack_require__(25).getWeak; - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var anInstance = __webpack_require__(212); - var forOf = __webpack_require__(213); - var createArrayMethod = __webpack_require__(174); - var $has = __webpack_require__(5); - var validate = __webpack_require__(223); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var id = 0; - - // fallback for uncaught frozen keys - var uncaughtFrozenStore = function (that) { - return that._l || (that._l = new UncaughtFrozenStore()); - }; - var UncaughtFrozenStore = function () { - this.a = []; - }; - var findUncaughtFrozen = function (store, key) { - return arrayFind(store.a, function (it) { - return it[0] === key; - }); - }; - UncaughtFrozenStore.prototype = { - get: function (key) { - var entry = findUncaughtFrozen(this, key); - if (entry) return entry[1]; - }, - has: function (key) { - return !!findUncaughtFrozen(this, key); - }, - set: function (key, value) { - var entry = findUncaughtFrozen(this, key); - if (entry) entry[1] = value; - else this.a.push([key, value]); - }, - 'delete': function (key) { - var index = arrayFindIndex(this.a, function (it) { - return it[0] === key; - }); - if (~index) this.a.splice(index, 1); - return !!~index; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = id++; // collection id - that._l = undefined; // leak store for uncaught frozen objects - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.3.3.2 WeakMap.prototype.delete(key) - // 23.4.3.3 WeakSet.prototype.delete(value) - 'delete': function (key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); - return data && $has(data, this._i) && delete data[this._i]; - }, - // 23.3.3.4 WeakMap.prototype.has(key) - // 23.4.3.4 WeakSet.prototype.has(value) - has: function has(key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); - return data && $has(data, this._i); - } - }); - return C; - }, - def: function (that, key, value) { - var data = getWeak(anObject(key), true); - if (data === true) uncaughtFrozenStore(that).set(key, value); - else data[that._i] = value; - return that; - }, - ufstore: uncaughtFrozenStore - }; - - -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var weak = __webpack_require__(227); - var validate = __webpack_require__(223); - var WEAK_SET = 'WeakSet'; - - // 23.4 WeakSet Objects - __webpack_require__(224)(WEAK_SET, function (get) { - return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.4.3.1 WeakSet.prototype.add(value) - add: function add(value) { - return weak.def(validate(this, WEAK_SET), value, true); - } - }, weak, false, true); - - -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $typed = __webpack_require__(230); - var buffer = __webpack_require__(231); - var anObject = __webpack_require__(12); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - var isObject = __webpack_require__(13); - var ArrayBuffer = __webpack_require__(4).ArrayBuffer; - var speciesConstructor = __webpack_require__(210); - var $ArrayBuffer = buffer.ArrayBuffer; - var $DataView = buffer.DataView; - var $isView = $typed.ABV && ArrayBuffer.isView; - var $slice = $ArrayBuffer.prototype.slice; - var VIEW = $typed.VIEW; - var ARRAY_BUFFER = 'ArrayBuffer'; - - $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); - - $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { - // 24.1.3.1 ArrayBuffer.isView(arg) - isView: function isView(it) { - return $isView && $isView(it) || isObject(it) && VIEW in it; - } - }); - - $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { - return !new $ArrayBuffer(2).slice(1, undefined).byteLength; - }), ARRAY_BUFFER, { - // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) - slice: function slice(start, end) { - if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix - var len = anObject(this).byteLength; - var first = toAbsoluteIndex(start, len); - var fin = toAbsoluteIndex(end === undefined ? len : end, len); - var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); - var viewS = new $DataView(this); - var viewT = new $DataView(result); - var index = 0; - while (first < fin) { - viewT.setUint8(index++, viewS.getUint8(first++)); - } return result; - } - }); - - __webpack_require__(194)(ARRAY_BUFFER); - - -/***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var uid = __webpack_require__(19); - var TYPED = uid('typed_array'); - var VIEW = uid('view'); - var ABV = !!(global.ArrayBuffer && global.DataView); - var CONSTR = ABV; - var i = 0; - var l = 9; - var Typed; - - var TypedArrayConstructors = ( - 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' - ).split(','); - - while (i < l) { - if (Typed = global[TypedArrayConstructors[i++]]) { - hide(Typed.prototype, TYPED, true); - hide(Typed.prototype, VIEW, true); - } else CONSTR = false; - } - - module.exports = { - ABV: ABV, - CONSTR: CONSTR, - TYPED: TYPED, - VIEW: VIEW - }; - - -/***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var DESCRIPTORS = __webpack_require__(6); - var LIBRARY = __webpack_require__(22); - var $typed = __webpack_require__(230); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(220); - var fails = __webpack_require__(7); - var anInstance = __webpack_require__(212); - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - var toIndex = __webpack_require__(232); - var gOPN = __webpack_require__(51).f; - var dP = __webpack_require__(11).f; - var arrayFill = __webpack_require__(190); - var setToStringTag = __webpack_require__(26); - var ARRAY_BUFFER = 'ArrayBuffer'; - var DATA_VIEW = 'DataView'; - var PROTOTYPE = 'prototype'; - var WRONG_LENGTH = 'Wrong length!'; - var WRONG_INDEX = 'Wrong index!'; - var $ArrayBuffer = global[ARRAY_BUFFER]; - var $DataView = global[DATA_VIEW]; - var Math = global.Math; - var RangeError = global.RangeError; - // eslint-disable-next-line no-shadow-restricted-names - var Infinity = global.Infinity; - var BaseBuffer = $ArrayBuffer; - var abs = Math.abs; - var pow = Math.pow; - var floor = Math.floor; - var log = Math.log; - var LN2 = Math.LN2; - var BUFFER = 'buffer'; - var BYTE_LENGTH = 'byteLength'; - var BYTE_OFFSET = 'byteOffset'; - var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; - var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; - var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; - - // IEEE754 conversions based on https://github.com/feross/ieee754 - function packIEEE754(value, mLen, nBytes) { - var buffer = new Array(nBytes); - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; - var i = 0; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - var e, m, c; - value = abs(value); - // eslint-disable-next-line no-self-compare - if (value != value || value === Infinity) { - // eslint-disable-next-line no-self-compare - m = value != value ? 1 : 0; - e = eMax; - } else { - e = floor(log(value) / LN2); - if (value * (c = pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * 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) * pow(2, mLen); - e = e + eBias; - } else { - m = value * pow(2, eBias - 1) * pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); - buffer[--i] |= s * 128; - return buffer; - } - function unpackIEEE754(buffer, mLen, nBytes) { - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = eLen - 7; - var i = nBytes - 1; - var s = buffer[i--]; - var e = s & 127; - var m; - s >>= 7; - for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : s ? -Infinity : Infinity; - } else { - m = m + pow(2, mLen); - e = e - eBias; - } return (s ? -1 : 1) * m * pow(2, e - mLen); - } - - function unpackI32(bytes) { - return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; - } - function packI8(it) { - return [it & 0xff]; - } - function packI16(it) { - return [it & 0xff, it >> 8 & 0xff]; - } - function packI32(it) { - return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; - } - function packF64(it) { - return packIEEE754(it, 52, 8); - } - function packF32(it) { - return packIEEE754(it, 23, 4); - } - - function addGetter(C, key, internal) { - dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); - } - - function get(view, bytes, index, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = store.slice(start, start + bytes); - return isLittleEndian ? pack : pack.reverse(); - } - function set(view, bytes, index, conversion, value, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = conversion(+value); - for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; - } - - if (!$typed.ABV) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer, ARRAY_BUFFER); - var byteLength = toIndex(length); - this._b = arrayFill.call(new Array(byteLength), 0); - this[$LENGTH] = byteLength; - }; - - $DataView = function DataView(buffer, byteOffset, byteLength) { - anInstance(this, $DataView, DATA_VIEW); - anInstance(buffer, $ArrayBuffer, DATA_VIEW); - var bufferLength = buffer[$LENGTH]; - var offset = toInteger(byteOffset); - if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); - this[$BUFFER] = buffer; - this[$OFFSET] = offset; - this[$LENGTH] = byteLength; - }; - - if (DESCRIPTORS) { - addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); - addGetter($DataView, BUFFER, '_b'); - addGetter($DataView, BYTE_LENGTH, '_l'); - addGetter($DataView, BYTE_OFFSET, '_o'); - } - - redefineAll($DataView[PROTOTYPE], { - getInt8: function getInt8(byteOffset) { - return get(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset) { - return get(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])); - }, - getUint32: function getUint32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); - }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); - }, - setInt8: function setInt8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setUint8: function setUint8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packF32, value, arguments[2]); - }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { - set(this, 8, byteOffset, packF64, value, arguments[2]); - } - }); - } else { - if (!fails(function () { - $ArrayBuffer(1); - }) || !fails(function () { - new $ArrayBuffer(-1); // eslint-disable-line no-new - }) || fails(function () { - new $ArrayBuffer(); // eslint-disable-line no-new - new $ArrayBuffer(1.5); // eslint-disable-line no-new - new $ArrayBuffer(NaN); // eslint-disable-line no-new - return $ArrayBuffer.name != ARRAY_BUFFER; - })) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer); - return new BaseBuffer(toIndex(length)); - }; - var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; - for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { - if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); - } - if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; - } - // iOS Safari 7.x bug - var view = new $DataView(new $ArrayBuffer(2)); - var $setInt8 = $DataView[PROTOTYPE].setInt8; - view.setInt8(0, 2147483648); - view.setInt8(1, 2147483649); - if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { - setInt8: function setInt8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - } - }, true); - } - setToStringTag($ArrayBuffer, ARRAY_BUFFER); - setToStringTag($DataView, DATA_VIEW); - hide($DataView[PROTOTYPE], $typed.VIEW, true); - exports[ARRAY_BUFFER] = $ArrayBuffer; - exports[DATA_VIEW] = $DataView; - - -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/ecma262/#sec-toindex - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - module.exports = function (it) { - if (it === undefined) return 0; - var number = toInteger(it); - var length = toLength(number); - if (number !== length) throw RangeError('Wrong length!'); - return length; - }; - - -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - $export($export.G + $export.W + $export.F * !__webpack_require__(230).ABV, { - DataView: __webpack_require__(231).DataView - }); - - -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Int8', 1, function (init) { - return function Int8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - if (__webpack_require__(6)) { - var LIBRARY = __webpack_require__(22); - var global = __webpack_require__(4); - var fails = __webpack_require__(7); - var $export = __webpack_require__(8); - var $typed = __webpack_require__(230); - var $buffer = __webpack_require__(231); - var ctx = __webpack_require__(23); - var anInstance = __webpack_require__(212); - var propertyDesc = __webpack_require__(17); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(220); - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - var toIndex = __webpack_require__(232); - var toAbsoluteIndex = __webpack_require__(40); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var classof = __webpack_require__(75); - var isObject = __webpack_require__(13); - var toObject = __webpack_require__(46); - var isArrayIter = __webpack_require__(164); - var create = __webpack_require__(47); - var getPrototypeOf = __webpack_require__(59); - var gOPN = __webpack_require__(51).f; - var getIterFn = __webpack_require__(166); - var uid = __webpack_require__(19); - var wks = __webpack_require__(27); - var createArrayMethod = __webpack_require__(174); - var createArrayIncludes = __webpack_require__(37); - var speciesConstructor = __webpack_require__(210); - var ArrayIterators = __webpack_require__(195); - var Iterators = __webpack_require__(130); - var $iterDetect = __webpack_require__(167); - var setSpecies = __webpack_require__(194); - var arrayFill = __webpack_require__(190); - var arrayCopyWithin = __webpack_require__(187); - var $DP = __webpack_require__(11); - var $GOPD = __webpack_require__(52); - var dP = $DP.f; - var gOPD = $GOPD.f; - var RangeError = global.RangeError; - var TypeError = global.TypeError; - var Uint8Array = global.Uint8Array; - var ARRAY_BUFFER = 'ArrayBuffer'; - var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; - var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; - var PROTOTYPE = 'prototype'; - var ArrayProto = Array[PROTOTYPE]; - var $ArrayBuffer = $buffer.ArrayBuffer; - var $DataView = $buffer.DataView; - var arrayForEach = createArrayMethod(0); - var arrayFilter = createArrayMethod(2); - var arraySome = createArrayMethod(3); - var arrayEvery = createArrayMethod(4); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var arrayIncludes = createArrayIncludes(true); - var arrayIndexOf = createArrayIncludes(false); - var arrayValues = ArrayIterators.values; - var arrayKeys = ArrayIterators.keys; - var arrayEntries = ArrayIterators.entries; - var arrayLastIndexOf = ArrayProto.lastIndexOf; - var arrayReduce = ArrayProto.reduce; - var arrayReduceRight = ArrayProto.reduceRight; - var arrayJoin = ArrayProto.join; - var arraySort = ArrayProto.sort; - var arraySlice = ArrayProto.slice; - var arrayToString = ArrayProto.toString; - var arrayToLocaleString = ArrayProto.toLocaleString; - var ITERATOR = wks('iterator'); - var TAG = wks('toStringTag'); - var TYPED_CONSTRUCTOR = uid('typed_constructor'); - var DEF_CONSTRUCTOR = uid('def_constructor'); - var ALL_CONSTRUCTORS = $typed.CONSTR; - var TYPED_ARRAY = $typed.TYPED; - var VIEW = $typed.VIEW; - var WRONG_LENGTH = 'Wrong length!'; - - var $map = createArrayMethod(1, function (O, length) { - return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); - }); - - var LITTLE_ENDIAN = fails(function () { - // eslint-disable-next-line no-undef - return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - }); - - var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { - new Uint8Array(1).set({}); - }); - - var toOffset = function (it, BYTES) { - var offset = toInteger(it); - if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); - return offset; - }; - - var validate = function (it) { - if (isObject(it) && TYPED_ARRAY in it) return it; - throw TypeError(it + ' is not a typed array!'); - }; - - var allocate = function (C, length) { - if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { - throw TypeError('It is not a typed array constructor!'); - } return new C(length); - }; - - var speciesFromList = function (O, list) { - return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); - }; - - var fromList = function (C, list) { - var index = 0; - var length = list.length; - var result = allocate(C, length); - while (length > index) result[index] = list[index++]; - return result; - }; - - var addGetter = function (it, key, internal) { - dP(it, key, { get: function () { return this._d[internal]; } }); - }; - - var $from = function from(source /* , mapfn, thisArg */) { - var O = toObject(source); - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iterFn = getIterFn(O); - var i, length, values, result, step, iterator; - if (iterFn != undefined && !isArrayIter(iterFn)) { - for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { - values.push(step.value); - } O = values; - } - if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); - for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var $of = function of(/* ...items */) { - var index = 0; - var length = arguments.length; - var result = allocate(this, length); - while (length > index) result[index] = arguments[index++]; - return result; - }; - - // iOS Safari 6.x fails here - var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); - - var $toLocaleString = function toLocaleString() { - return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); - }; - - var proto = { - copyWithin: function copyWithin(target, start /* , end */) { - return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }, - every: function every(callbackfn /* , thisArg */) { - return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars - return arrayFill.apply(validate(this), arguments); - }, - filter: function filter(callbackfn /* , thisArg */) { - return speciesFromList(this, arrayFilter(validate(this), callbackfn, - arguments.length > 1 ? arguments[1] : undefined)); - }, - find: function find(predicate /* , thisArg */) { - return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - findIndex: function findIndex(predicate /* , thisArg */) { - return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - forEach: function forEach(callbackfn /* , thisArg */) { - arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - indexOf: function indexOf(searchElement /* , fromIndex */) { - return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - includes: function includes(searchElement /* , fromIndex */) { - return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - join: function join(separator) { // eslint-disable-line no-unused-vars - return arrayJoin.apply(validate(this), arguments); - }, - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars - return arrayLastIndexOf.apply(validate(this), arguments); - }, - map: function map(mapfn /* , thisArg */) { - return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); - }, - reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduce.apply(validate(this), arguments); - }, - reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduceRight.apply(validate(this), arguments); - }, - reverse: function reverse() { - var that = this; - var length = validate(that).length; - var middle = Math.floor(length / 2); - var index = 0; - var value; - while (index < middle) { - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }, - some: function some(callbackfn /* , thisArg */) { - return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - sort: function sort(comparefn) { - return arraySort.call(validate(this), comparefn); - }, - subarray: function subarray(begin, end) { - var O = validate(this); - var length = O.length; - var $begin = toAbsoluteIndex(begin, length); - return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( - O.buffer, - O.byteOffset + $begin * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) - ); - } - }; - - var $slice = function slice(start, end) { - return speciesFromList(this, arraySlice.call(validate(this), start, end)); - }; - - var $set = function set(arrayLike /* , offset */) { - validate(this); - var offset = toOffset(arguments[1], 1); - var length = this.length; - var src = toObject(arrayLike); - var len = toLength(src.length); - var index = 0; - if (len + offset > length) throw RangeError(WRONG_LENGTH); - while (index < len) this[offset + index] = src[index++]; - }; - - var $iterators = { - entries: function entries() { - return arrayEntries.call(validate(this)); - }, - keys: function keys() { - return arrayKeys.call(validate(this)); - }, - values: function values() { - return arrayValues.call(validate(this)); - } - }; - - var isTAIndex = function (target, key) { - return isObject(target) - && target[TYPED_ARRAY] - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - var $getDesc = function getOwnPropertyDescriptor(target, key) { - return isTAIndex(target, key = toPrimitive(key, true)) - ? propertyDesc(2, target[key]) - : gOPD(target, key); - }; - var $setDesc = function defineProperty(target, key, desc) { - if (isTAIndex(target, key = toPrimitive(key, true)) - && isObject(desc) - && has(desc, 'value') - && !has(desc, 'get') - && !has(desc, 'set') - // TODO: add validation descriptor w/o calling accessors - && !desc.configurable - && (!has(desc, 'writable') || desc.writable) - && (!has(desc, 'enumerable') || desc.enumerable) - ) { - target[key] = desc.value; - return target; - } return dP(target, key, desc); - }; - - if (!ALL_CONSTRUCTORS) { - $GOPD.f = $getDesc; - $DP.f = $setDesc; - } - - $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { - getOwnPropertyDescriptor: $getDesc, - defineProperty: $setDesc - }); - - if (fails(function () { arrayToString.call({}); })) { - arrayToString = arrayToLocaleString = function toString() { - return arrayJoin.call(this); - }; - } - - var $TypedArrayPrototype$ = redefineAll({}, proto); - redefineAll($TypedArrayPrototype$, $iterators); - hide($TypedArrayPrototype$, ITERATOR, $iterators.values); - redefineAll($TypedArrayPrototype$, { - slice: $slice, - set: $set, - constructor: function () { /* noop */ }, - toString: arrayToString, - toLocaleString: $toLocaleString - }); - addGetter($TypedArrayPrototype$, 'buffer', 'b'); - addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); - addGetter($TypedArrayPrototype$, 'byteLength', 'l'); - addGetter($TypedArrayPrototype$, 'length', 'e'); - dP($TypedArrayPrototype$, TAG, { - get: function () { return this[TYPED_ARRAY]; } - }); - - // eslint-disable-next-line max-statements - module.exports = function (KEY, BYTES, wrapper, CLAMPED) { - CLAMPED = !!CLAMPED; - var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; - var GETTER = 'get' + KEY; - var SETTER = 'set' + KEY; - var TypedArray = global[NAME]; - var Base = TypedArray || {}; - var TAC = TypedArray && getPrototypeOf(TypedArray); - var FORCED = !TypedArray || !$typed.ABV; - var O = {}; - var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; - var getter = function (that, index) { - var data = that._d; - return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); - }; - var setter = function (that, index, value) { - var data = that._d; - if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; - data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); - }; - var addElement = function (that, index) { - dP(that, index, { - get: function () { - return getter(this, index); - }, - set: function (value) { - return setter(this, index, value); - }, - enumerable: true - }); - }; - if (FORCED) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME, '_d'); - var index = 0; - var offset = 0; - var buffer, byteLength, length, klass; - if (!isObject(data)) { - length = toIndex(data); - byteLength = length * BYTES; - buffer = new $ArrayBuffer(byteLength); - } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - buffer = data; - offset = toOffset($offset, BYTES); - var $len = data.byteLength; - if ($length === undefined) { - if ($len % BYTES) throw RangeError(WRONG_LENGTH); - byteLength = $len - offset; - if (byteLength < 0) throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if (TYPED_ARRAY in data) { - return fromList(TypedArray, data); - } else { - return $from.call(TypedArray, data); - } - hide(that, '_d', { - b: buffer, - o: offset, - l: byteLength, - e: length, - v: new $DataView(buffer) - }); - while (index < length) addElement(that, index++); - }); - TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); - hide(TypedArrayPrototype, 'constructor', TypedArray); - } else if (!fails(function () { - TypedArray(1); - }) || !fails(function () { - new TypedArray(-1); // eslint-disable-line no-new - }) || !$iterDetect(function (iter) { - new TypedArray(); // eslint-disable-line no-new - new TypedArray(null); // eslint-disable-line no-new - new TypedArray(1.5); // eslint-disable-line no-new - new TypedArray(iter); // eslint-disable-line no-new - }, true)) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME); - var klass; - // `ws` module bug, temporarily remove validation length for Uint8Array - // https://github.com/websockets/ws/pull/645 - if (!isObject(data)) return new Base(toIndex(data)); - if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - return $length !== undefined - ? new Base(data, toOffset($offset, BYTES), $length) - : $offset !== undefined - ? new Base(data, toOffset($offset, BYTES)) - : new Base(data); - } - if (TYPED_ARRAY in data) return fromList(TypedArray, data); - return $from.call(TypedArray, data); - }); - arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { - if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); - }); - TypedArray[PROTOTYPE] = TypedArrayPrototype; - if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; - } - var $nativeIterator = TypedArrayPrototype[ITERATOR]; - var CORRECT_ITER_NAME = !!$nativeIterator - && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); - var $iterator = $iterators.values; - hide(TypedArray, TYPED_CONSTRUCTOR, true); - hide(TypedArrayPrototype, TYPED_ARRAY, NAME); - hide(TypedArrayPrototype, VIEW, true); - hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); - - if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { - dP(TypedArrayPrototype, TAG, { - get: function () { return NAME; } - }); - } - - O[NAME] = TypedArray; - - $export($export.G + $export.W + $export.F * (TypedArray != Base), O); - - $export($export.S, NAME, { - BYTES_PER_ELEMENT: BYTES - }); - - $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { - from: $from, - of: $of - }); - - if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); - - $export($export.P, NAME, proto); - - setSpecies(NAME); - - $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); - - $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); - - if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; - - $export($export.P + $export.F * fails(function () { - new TypedArray(1).slice(); - }), NAME, { slice: $slice }); - - $export($export.P + $export.F * (fails(function () { - return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); - }) || !fails(function () { - TypedArrayPrototype.toLocaleString.call([1, 2]); - })), NAME, { toLocaleString: $toLocaleString }); - - Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; - if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); - }; - } else module.exports = function () { /* empty */ }; - - -/***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint8', 1, function (init) { - return function Uint8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 237 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint8', 1, function (init) { - return function Uint8ClampedArray(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }, true); - - -/***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Int16', 2, function (init) { - return function Int16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 239 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint16', 2, function (init) { - return function Uint16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 240 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Int32', 4, function (init) { - return function Int32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 241 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint32', 4, function (init) { - return function Uint32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Float32', 4, function (init) { - return function Float32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 243 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Float64', 8, function (init) { - return function Float64Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(24); - var anObject = __webpack_require__(12); - var rApply = (__webpack_require__(4).Reflect || {}).apply; - var fApply = Function.apply; - // MS Edge argumentsList argument is optional - $export($export.S + $export.F * !__webpack_require__(7)(function () { - rApply(function () { /* empty */ }); - }), 'Reflect', { - apply: function apply(target, thisArgument, argumentsList) { - var T = aFunction(target); - var L = anObject(argumentsList); - return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); - } - }); - - -/***/ }), -/* 245 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) - var $export = __webpack_require__(8); - var create = __webpack_require__(47); - var aFunction = __webpack_require__(24); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var bind = __webpack_require__(77); - var rConstruct = (__webpack_require__(4).Reflect || {}).construct; - - // MS Edge supports only 2 arguments and argumentsList argument is optional - // FF Nightly sets third argument as `new.target`, but does not create `this` from it - var NEW_TARGET_BUG = fails(function () { - function F() { /* empty */ } - return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); - }); - var ARGS_BUG = !fails(function () { - rConstruct(function () { /* empty */ }); - }); - - $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { - construct: function construct(Target, args /* , newTarget */) { - aFunction(Target); - anObject(args); - var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); - if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); - if (Target == newTarget) { - // w/o altered newTarget, optimization for 0-4 arguments - switch (args.length) { - case 0: return new Target(); - case 1: return new Target(args[0]); - case 2: return new Target(args[0], args[1]); - case 3: return new Target(args[0], args[1], args[2]); - case 4: return new Target(args[0], args[1], args[2], args[3]); - } - // w/o altered newTarget, lot of arguments case - var $args = [null]; - $args.push.apply($args, args); - return new (bind.apply(Target, $args))(); - } - // with altered newTarget, not support built-in constructors - var proto = newTarget.prototype; - var instance = create(isObject(proto) ? proto : Object.prototype); - var result = Function.apply.call(Target, instance, args); - return isObject(result) ? result : instance; - } - }); - - -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) - var dP = __webpack_require__(11); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - - // MS Edge has broken Reflect.defineProperty - throwing instead of returning false - $export($export.S + $export.F * __webpack_require__(7)(function () { - // eslint-disable-next-line no-undef - Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); - }), 'Reflect', { - defineProperty: function defineProperty(target, propertyKey, attributes) { - anObject(target); - propertyKey = toPrimitive(propertyKey, true); - anObject(attributes); - try { - dP.f(target, propertyKey, attributes); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.4 Reflect.deleteProperty(target, propertyKey) - var $export = __webpack_require__(8); - var gOPD = __webpack_require__(52).f; - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - deleteProperty: function deleteProperty(target, propertyKey) { - var desc = gOPD(anObject(target), propertyKey); - return desc && !desc.configurable ? false : delete target[propertyKey]; - } - }); - - -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 26.1.5 Reflect.enumerate(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var Enumerate = function (iterated) { - this._t = anObject(iterated); // target - this._i = 0; // next index - var keys = this._k = []; // keys - var key; - for (key in iterated) keys.push(key); - }; - __webpack_require__(131)(Enumerate, 'Object', function () { - var that = this; - var keys = that._k; - var key; - do { - if (that._i >= keys.length) return { value: undefined, done: true }; - } while (!((key = keys[that._i++]) in that._t)); - return { value: key, done: false }; - }); - - $export($export.S, 'Reflect', { - enumerate: function enumerate(target) { - return new Enumerate(target); - } - }); - - -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.6 Reflect.get(target, propertyKey [, receiver]) - var gOPD = __webpack_require__(52); - var getPrototypeOf = __webpack_require__(59); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - - function get(target, propertyKey /* , receiver */) { - var receiver = arguments.length < 3 ? target : arguments[2]; - var desc, proto; - if (anObject(target) === receiver) return target[propertyKey]; - if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') - ? desc.value - : desc.get !== undefined - ? desc.get.call(receiver) - : undefined; - if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); - } - - $export($export.S, 'Reflect', { get: get }); - - -/***/ }), -/* 250 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) - var gOPD = __webpack_require__(52); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { - return gOPD.f(anObject(target), propertyKey); - } - }); - - -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.8 Reflect.getPrototypeOf(target) - var $export = __webpack_require__(8); - var getProto = __webpack_require__(59); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getPrototypeOf: function getPrototypeOf(target) { - return getProto(anObject(target)); - } - }); - - -/***/ }), -/* 252 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.9 Reflect.has(target, propertyKey) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { - has: function has(target, propertyKey) { - return propertyKey in target; - } - }); - - -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.10 Reflect.isExtensible(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $isExtensible = Object.isExtensible; - - $export($export.S, 'Reflect', { - isExtensible: function isExtensible(target) { - anObject(target); - return $isExtensible ? $isExtensible(target) : true; - } - }); - - -/***/ }), -/* 254 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.11 Reflect.ownKeys(target) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { ownKeys: __webpack_require__(255) }); - - -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { - - // all object keys, includes non-enumerable and symbols - var gOPN = __webpack_require__(51); - var gOPS = __webpack_require__(43); - var anObject = __webpack_require__(12); - var Reflect = __webpack_require__(4).Reflect; - module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { - var keys = gOPN.f(anObject(it)); - var getSymbols = gOPS.f; - return getSymbols ? keys.concat(getSymbols(it)) : keys; - }; - - -/***/ }), -/* 256 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.12 Reflect.preventExtensions(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $preventExtensions = Object.preventExtensions; - - $export($export.S, 'Reflect', { - preventExtensions: function preventExtensions(target) { - anObject(target); - try { - if ($preventExtensions) $preventExtensions(target); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 257 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) - var dP = __webpack_require__(11); - var gOPD = __webpack_require__(52); - var getPrototypeOf = __webpack_require__(59); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var createDesc = __webpack_require__(17); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - - function set(target, propertyKey, V /* , receiver */) { - var receiver = arguments.length < 4 ? target : arguments[3]; - var ownDesc = gOPD.f(anObject(target), propertyKey); - var existingDescriptor, proto; - if (!ownDesc) { - if (isObject(proto = getPrototypeOf(target))) { - return set(proto, propertyKey, V, receiver); - } - ownDesc = createDesc(0); - } - if (has(ownDesc, 'value')) { - if (ownDesc.writable === false || !isObject(receiver)) return false; - if (existingDescriptor = gOPD.f(receiver, propertyKey)) { - if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; - existingDescriptor.value = V; - dP.f(receiver, propertyKey, existingDescriptor); - } else dP.f(receiver, propertyKey, createDesc(0, V)); - return true; - } - return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); - } - - $export($export.S, 'Reflect', { set: set }); - - -/***/ }), -/* 258 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.14 Reflect.setPrototypeOf(target, proto) - var $export = __webpack_require__(8); - var setProto = __webpack_require__(73); - - if (setProto) $export($export.S, 'Reflect', { - setPrototypeOf: function setPrototypeOf(target, proto) { - setProto.check(target, proto); - try { - setProto.set(target, proto); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 259 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/Array.prototype.includes - var $export = __webpack_require__(8); - var $includes = __webpack_require__(37)(true); - - $export($export.P, 'Array', { - includes: function includes(el /* , fromIndex = 0 */) { - return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - __webpack_require__(188)('includes'); - - -/***/ }), -/* 260 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(261); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var aFunction = __webpack_require__(24); - var arraySpeciesCreate = __webpack_require__(175); - - $export($export.P, 'Array', { - flatMap: function flatMap(callbackfn /* , thisArg */) { - var O = toObject(this); - var sourceLen, A; - aFunction(callbackfn); - sourceLen = toLength(O.length); - A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); - return A; - } - }); - - __webpack_require__(188)('flatMap'); - - -/***/ }), -/* 261 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray - var isArray = __webpack_require__(45); - var isObject = __webpack_require__(13); - var toLength = __webpack_require__(38); - var ctx = __webpack_require__(23); - var IS_CONCAT_SPREADABLE = __webpack_require__(27)('isConcatSpreadable'); - - function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { - var targetIndex = start; - var sourceIndex = 0; - var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; - var element, spreadable; - - while (sourceIndex < sourceLen) { - if (sourceIndex in source) { - element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; - - spreadable = false; - if (isObject(element)) { - spreadable = element[IS_CONCAT_SPREADABLE]; - spreadable = spreadable !== undefined ? !!spreadable : isArray(element); - } - - if (spreadable && depth > 0) { - targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; - } else { - if (targetIndex >= 0x1fffffffffffff) throw TypeError(); - target[targetIndex] = element; - } - - targetIndex++; - } - sourceIndex++; - } - return targetIndex; - } - - module.exports = flattenIntoArray; - - -/***/ }), -/* 262 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(261); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var toInteger = __webpack_require__(39); - var arraySpeciesCreate = __webpack_require__(175); - - $export($export.P, 'Array', { - flatten: function flatten(/* depthArg = 1 */) { - var depthArg = arguments[0]; - var O = toObject(this); - var sourceLen = toLength(O.length); - var A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); - return A; - } - }); - - __webpack_require__(188)('flatten'); - - -/***/ }), -/* 263 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/mathiasbynens/String.prototype.at - var $export = __webpack_require__(8); - var $at = __webpack_require__(128)(true); - - $export($export.P, 'String', { - at: function at(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 264 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(265); - var userAgent = __webpack_require__(218); - - // https://github.com/zloirock/core-js/issues/280 - var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent); - - $export($export.P + $export.F * WEBKIT_BUG, 'String', { - padStart: function padStart(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); - } - }); - - -/***/ }), -/* 265 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-string-pad-start-end - var toLength = __webpack_require__(38); - var repeat = __webpack_require__(91); - var defined = __webpack_require__(36); - - module.exports = function (that, maxLength, fillString, left) { - var S = String(defined(that)); - var stringLength = S.length; - var fillStr = fillString === undefined ? ' ' : String(fillString); - var intMaxLength = toLength(maxLength); - if (intMaxLength <= stringLength || fillStr == '') return S; - var fillLen = intMaxLength - stringLength; - var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); - if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); - return left ? stringFiller + S : S + stringFiller; - }; - - -/***/ }), -/* 266 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(265); - var userAgent = __webpack_require__(218); - - // https://github.com/zloirock/core-js/issues/280 - var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent); - - $export($export.P + $export.F * WEBKIT_BUG, 'String', { - padEnd: function padEnd(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); - } - }); - - -/***/ }), -/* 267 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(83)('trimLeft', function ($trim) { - return function trimLeft() { - return $trim(this, 1); - }; - }, 'trimStart'); - - -/***/ }), -/* 268 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(83)('trimRight', function ($trim) { - return function trimRight() { - return $trim(this, 2); - }; - }, 'trimEnd'); - - -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/String.prototype.matchAll/ - var $export = __webpack_require__(8); - var defined = __webpack_require__(36); - var toLength = __webpack_require__(38); - var isRegExp = __webpack_require__(135); - var getFlags = __webpack_require__(198); - var RegExpProto = RegExp.prototype; - - var $RegExpStringIterator = function (regexp, string) { - this._r = regexp; - this._s = string; - }; - - __webpack_require__(131)($RegExpStringIterator, 'RegExp String', function next() { - var match = this._r.exec(this._s); - return { value: match, done: match === null }; - }); - - $export($export.P, 'String', { - matchAll: function matchAll(regexp) { - defined(this); - if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); - var S = String(this); - var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); - var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); - rx.lastIndex = toLength(regexp.lastIndex); - return new $RegExpStringIterator(rx, S); - } - }); - - -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(29)('asyncIterator'); - - -/***/ }), -/* 271 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(29)('observable'); - - -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-getownpropertydescriptors - var $export = __webpack_require__(8); - var ownKeys = __webpack_require__(255); - var toIObject = __webpack_require__(33); - var gOPD = __webpack_require__(52); - var createProperty = __webpack_require__(165); - - $export($export.S, 'Object', { - getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { - var O = toIObject(object); - var getDesc = gOPD.f; - var keys = ownKeys(O); - var result = {}; - var i = 0; - var key, desc; - while (keys.length > i) { - desc = getDesc(O, key = keys[i++]); - if (desc !== undefined) createProperty(result, key, desc); - } - return result; - } - }); - - -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $values = __webpack_require__(274)(false); - - $export($export.S, 'Object', { - values: function values(it) { - return $values(it); - } - }); - - -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { - - var DESCRIPTORS = __webpack_require__(6); - var getKeys = __webpack_require__(31); - var toIObject = __webpack_require__(33); - var isEnum = __webpack_require__(44).f; - module.exports = function (isEntries) { - return function (it) { - var O = toIObject(it); - var keys = getKeys(O); - var length = keys.length; - var i = 0; - var result = []; - var key; - while (length > i) { - key = keys[i++]; - if (!DESCRIPTORS || isEnum.call(O, key)) { - result.push(isEntries ? [key, O[key]] : O[key]); - } - } - return result; - }; - }; - - -/***/ }), -/* 275 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $entries = __webpack_require__(274)(true); - - $export($export.S, 'Object', { - entries: function entries(it) { - return $entries(it); - } - }); - - -/***/ }), -/* 276 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var aFunction = __webpack_require__(24); - var $defineProperty = __webpack_require__(11); - - // B.2.2.2 Object.prototype.__defineGetter__(P, getter) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __defineGetter__: function __defineGetter__(P, getter) { - $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // Forced replacement prototype accessors methods - module.exports = __webpack_require__(22) || !__webpack_require__(7)(function () { - var K = Math.random(); - // In FF throws only define methods - // eslint-disable-next-line no-undef, no-useless-call - __defineSetter__.call(null, K, function () { /* empty */ }); - delete __webpack_require__(4)[K]; - }); - - -/***/ }), -/* 278 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var aFunction = __webpack_require__(24); - var $defineProperty = __webpack_require__(11); - - // B.2.2.3 Object.prototype.__defineSetter__(P, setter) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __defineSetter__: function __defineSetter__(P, setter) { - $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 279 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(59); - var getOwnPropertyDescriptor = __webpack_require__(52).f; - - // B.2.2.4 Object.prototype.__lookupGetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __lookupGetter__: function __lookupGetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.get; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 280 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(59); - var getOwnPropertyDescriptor = __webpack_require__(52).f; - - // B.2.2.5 Object.prototype.__lookupSetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __lookupSetter__: function __lookupSetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.set; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 281 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(282)('Map') }); - - -/***/ }), -/* 282 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var classof = __webpack_require__(75); - var from = __webpack_require__(283); - module.exports = function (NAME) { - return function toJSON() { - if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); - return from(this); - }; - }; - - -/***/ }), -/* 283 */ -/***/ (function(module, exports, __webpack_require__) { - - var forOf = __webpack_require__(213); - - module.exports = function (iter, ITERATOR) { - var result = []; - forOf(iter, false, result.push, result, ITERATOR); - return result; - }; - - -/***/ }), -/* 284 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(282)('Set') }); - - -/***/ }), -/* 285 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of - __webpack_require__(286)('Map'); - - -/***/ }), -/* 286 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { of: function of() { - var length = arguments.length; - var A = new Array(length); - while (length--) A[length] = arguments[length]; - return new this(A); - } }); - }; - - -/***/ }), -/* 287 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of - __webpack_require__(286)('Set'); - - -/***/ }), -/* 288 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of - __webpack_require__(286)('WeakMap'); - - -/***/ }), -/* 289 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of - __webpack_require__(286)('WeakSet'); - - -/***/ }), -/* 290 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from - __webpack_require__(291)('Map'); - - -/***/ }), -/* 291 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(24); - var ctx = __webpack_require__(23); - var forOf = __webpack_require__(213); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { - var mapFn = arguments[1]; - var mapping, A, n, cb; - aFunction(this); - mapping = mapFn !== undefined; - if (mapping) aFunction(mapFn); - if (source == undefined) return new this(); - A = []; - if (mapping) { - n = 0; - cb = ctx(mapFn, arguments[2], 2); - forOf(source, false, function (nextItem) { - A.push(cb(nextItem, n++)); - }); - } else { - forOf(source, false, A.push, A); - } - return new this(A); - } }); - }; - - -/***/ }), -/* 292 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from - __webpack_require__(291)('Set'); - - -/***/ }), -/* 293 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from - __webpack_require__(291)('WeakMap'); - - -/***/ }), -/* 294 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from - __webpack_require__(291)('WeakSet'); - - -/***/ }), -/* 295 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.G, { global: __webpack_require__(4) }); - - -/***/ }), -/* 296 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.S, 'System', { global: __webpack_require__(4) }); - - -/***/ }), -/* 297 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/ljharb/proposal-is-error - var $export = __webpack_require__(8); - var cof = __webpack_require__(35); - - $export($export.S, 'Error', { - isError: function isError(it) { - return cof(it) === 'Error'; - } - }); - - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clamp: function clamp(x, lower, upper) { - return Math.min(upper, Math.max(lower, x)); - } - }); - - -/***/ }), -/* 299 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); - - -/***/ }), -/* 300 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var RAD_PER_DEG = 180 / Math.PI; - - $export($export.S, 'Math', { - degrees: function degrees(radians) { - return radians * RAD_PER_DEG; - } - }); - - -/***/ }), -/* 301 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var scale = __webpack_require__(302); - var fround = __webpack_require__(114); - - $export($export.S, 'Math', { - fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { - return fround(scale(x, inLow, inHigh, outLow, outHigh)); - } - }); - - -/***/ }), -/* 302 */ -/***/ (function(module, exports) { - - // https://rwaldron.github.io/proposal-math-extensions/ - module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { - if ( - arguments.length === 0 - // eslint-disable-next-line no-self-compare - || x != x - // eslint-disable-next-line no-self-compare - || inLow != inLow - // eslint-disable-next-line no-self-compare - || inHigh != inHigh - // eslint-disable-next-line no-self-compare - || outLow != outLow - // eslint-disable-next-line no-self-compare - || outHigh != outHigh - ) return NaN; - if (x === Infinity || x === -Infinity) return x; - return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; - }; - - -/***/ }), -/* 303 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - iaddh: function iaddh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; - } - }); - - -/***/ }), -/* 304 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - isubh: function isubh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; - } - }); - - -/***/ }), -/* 305 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - imulh: function imulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >> 16; - var v1 = $v >> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); - } - }); - - -/***/ }), -/* 306 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); - - -/***/ }), -/* 307 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var DEG_PER_RAD = Math.PI / 180; - - $export($export.S, 'Math', { - radians: function radians(degrees) { - return degrees * DEG_PER_RAD; - } - }); - - -/***/ }), -/* 308 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { scale: __webpack_require__(302) }); - - -/***/ }), -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - umulh: function umulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >>> 16; - var v1 = $v >>> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); - } - }); - - -/***/ }), -/* 310 */ -/***/ (function(module, exports, __webpack_require__) { - - // http://jfbastien.github.io/papers/Math.signbit.html - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { signbit: function signbit(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; - } }); - - -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-promise-finally - 'use strict'; - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var speciesConstructor = __webpack_require__(210); - var promiseResolve = __webpack_require__(219); - - $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); - } }); - - -/***/ }), -/* 312 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-promise-try - var $export = __webpack_require__(8); - var newPromiseCapability = __webpack_require__(216); - var perform = __webpack_require__(217); - - $export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; - } }); - - -/***/ }), -/* 313 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var ordinaryDefineOwnMetadata = metadata.set; - - metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { - ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); - } }); - - -/***/ }), -/* 314 */ -/***/ (function(module, exports, __webpack_require__) { - - var Map = __webpack_require__(221); - var $export = __webpack_require__(8); - var shared = __webpack_require__(21)('metadata'); - var store = shared.store || (shared.store = new (__webpack_require__(226))()); - - var getOrCreateMetadataMap = function (target, targetKey, create) { - var targetMetadata = store.get(target); - if (!targetMetadata) { - if (!create) return undefined; - store.set(target, targetMetadata = new Map()); - } - var keyMetadata = targetMetadata.get(targetKey); - if (!keyMetadata) { - if (!create) return undefined; - targetMetadata.set(targetKey, keyMetadata = new Map()); - } return keyMetadata; - }; - var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? false : metadataMap.has(MetadataKey); - }; - var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); - }; - var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { - getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); - }; - var ordinaryOwnMetadataKeys = function (target, targetKey) { - var metadataMap = getOrCreateMetadataMap(target, targetKey, false); - var keys = []; - if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); - return keys; - }; - var toMetaKey = function (it) { - return it === undefined || typeof it == 'symbol' ? it : String(it); - }; - var exp = function (O) { - $export($export.S, 'Reflect', O); - }; - - module.exports = { - store: store, - map: getOrCreateMetadataMap, - has: ordinaryHasOwnMetadata, - get: ordinaryGetOwnMetadata, - set: ordinaryDefineOwnMetadata, - keys: ordinaryOwnMetadataKeys, - key: toMetaKey, - exp: exp - }; - - -/***/ }), -/* 315 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var getOrCreateMetadataMap = metadata.map; - var store = metadata.store; - - metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { - var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); - var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); - if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; - if (metadataMap.size) return true; - var targetMetadata = store.get(target); - targetMetadata['delete'](targetKey); - return !!targetMetadata.size || store['delete'](target); - } }); - - -/***/ }), -/* 316 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(59); - var ordinaryHasOwnMetadata = metadata.has; - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - var ordinaryGetMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; - }; - - metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 317 */ -/***/ (function(module, exports, __webpack_require__) { - - var Set = __webpack_require__(225); - var from = __webpack_require__(283); - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(59); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - var ordinaryMetadataKeys = function (O, P) { - var oKeys = ordinaryOwnMetadataKeys(O, P); - var parent = getPrototypeOf(O); - if (parent === null) return oKeys; - var pKeys = ordinaryMetadataKeys(parent, P); - return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; - }; - - metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { - return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 318 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 319 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { - return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 320 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(59); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - var ordinaryHasMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return true; - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; - }; - - metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 321 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 322 */ -/***/ (function(module, exports, __webpack_require__) { - - var $metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(24); - var toMetaKey = $metadata.key; - var ordinaryDefineOwnMetadata = $metadata.set; - - $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { - return function decorator(target, targetKey) { - ordinaryDefineOwnMetadata( - metadataKey, metadataValue, - (targetKey !== undefined ? anObject : aFunction)(target), - toMetaKey(targetKey) - ); - }; - } }); - - -/***/ }), -/* 323 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask - var $export = __webpack_require__(8); - var microtask = __webpack_require__(215)(); - var process = __webpack_require__(4).process; - var isNode = __webpack_require__(35)(process) == 'process'; - - $export($export.G, { - asap: function asap(fn) { - var domain = isNode && process.domain; - microtask(domain ? domain.bind(fn) : fn); - } - }); - - -/***/ }), -/* 324 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/zenparsing/es-observable - var $export = __webpack_require__(8); - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var microtask = __webpack_require__(215)(); - var OBSERVABLE = __webpack_require__(27)('observable'); - var aFunction = __webpack_require__(24); - var anObject = __webpack_require__(12); - var anInstance = __webpack_require__(212); - var redefineAll = __webpack_require__(220); - var hide = __webpack_require__(10); - var forOf = __webpack_require__(213); - var RETURN = forOf.RETURN; - - var getMethod = function (fn) { - return fn == null ? undefined : aFunction(fn); - }; - - var cleanupSubscription = function (subscription) { - var cleanup = subscription._c; - if (cleanup) { - subscription._c = undefined; - cleanup(); - } - }; - - var subscriptionClosed = function (subscription) { - return subscription._o === undefined; - }; - - var closeSubscription = function (subscription) { - if (!subscriptionClosed(subscription)) { - subscription._o = undefined; - cleanupSubscription(subscription); - } - }; - - var Subscription = function (observer, subscriber) { - anObject(observer); - this._c = undefined; - this._o = observer; - observer = new SubscriptionObserver(this); - try { - var cleanup = subscriber(observer); - var subscription = cleanup; - if (cleanup != null) { - if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; - else aFunction(cleanup); - this._c = cleanup; - } - } catch (e) { - observer.error(e); - return; - } if (subscriptionClosed(this)) cleanupSubscription(this); - }; - - Subscription.prototype = redefineAll({}, { - unsubscribe: function unsubscribe() { closeSubscription(this); } - }); - - var SubscriptionObserver = function (subscription) { - this._s = subscription; - }; - - SubscriptionObserver.prototype = redefineAll({}, { - next: function next(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - try { - var m = getMethod(observer.next); - if (m) return m.call(observer, value); - } catch (e) { - try { - closeSubscription(subscription); - } finally { - throw e; - } - } - } - }, - error: function error(value) { - var subscription = this._s; - if (subscriptionClosed(subscription)) throw value; - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.error); - if (!m) throw value; - value = m.call(observer, value); - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - }, - complete: function complete(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.complete); - value = m ? m.call(observer, value) : undefined; - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - } - } - }); - - var $Observable = function Observable(subscriber) { - anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); - }; - - redefineAll($Observable.prototype, { - subscribe: function subscribe(observer) { - return new Subscription(observer, this._f); - }, - forEach: function forEach(fn) { - var that = this; - return new (core.Promise || global.Promise)(function (resolve, reject) { - aFunction(fn); - var subscription = that.subscribe({ - next: function (value) { - try { - return fn(value); - } catch (e) { - reject(e); - subscription.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - }); - } - }); - - redefineAll($Observable, { - from: function from(x) { - var C = typeof this === 'function' ? this : $Observable; - var method = getMethod(anObject(x)[OBSERVABLE]); - if (method) { - var observable = anObject(method.call(x)); - return observable.constructor === C ? observable : new C(function (observer) { - return observable.subscribe(observer); - }); - } - return new C(function (observer) { - var done = false; - microtask(function () { - if (!done) { - try { - if (forOf(x, false, function (it) { - observer.next(it); - if (done) return RETURN; - }) === RETURN) return; - } catch (e) { - if (done) throw e; - observer.error(e); - return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - }, - of: function of() { - for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; - return new (typeof this === 'function' ? this : $Observable)(function (observer) { - var done = false; - microtask(function () { - if (!done) { - for (var j = 0; j < items.length; ++j) { - observer.next(items[j]); - if (done) return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - } - }); - - hide($Observable.prototype, OBSERVABLE, function () { return this; }); - - $export($export.G, { Observable: $Observable }); - - __webpack_require__(194)('Observable'); - - -/***/ }), -/* 325 */ -/***/ (function(module, exports, __webpack_require__) { - - // ie9- setTimeout & setInterval additional parameters fix - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var userAgent = __webpack_require__(218); - var slice = [].slice; - var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check - var wrap = function (set) { - return function (fn, time /* , ...args */) { - var boundArgs = arguments.length > 2; - var args = boundArgs ? slice.call(arguments, 2) : false; - return set(boundArgs ? function () { - // eslint-disable-next-line no-new-func - (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); - } : fn, time); - }; - }; - $export($export.G + $export.B + $export.F * MSIE, { - setTimeout: wrap(global.setTimeout), - setInterval: wrap(global.setInterval) - }); - - -/***/ }), -/* 326 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $task = __webpack_require__(214); - $export($export.G + $export.B, { - setImmediate: $task.set, - clearImmediate: $task.clear - }); - - -/***/ }), -/* 327 */ -/***/ (function(module, exports, __webpack_require__) { - - var $iterators = __webpack_require__(195); - var getKeys = __webpack_require__(31); - var redefine = __webpack_require__(18); - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(130); - var wks = __webpack_require__(27); - var ITERATOR = wks('iterator'); - var TO_STRING_TAG = wks('toStringTag'); - var ArrayValues = Iterators.Array; - - var DOMIterables = { - CSSRuleList: true, // TODO: Not spec compliant, should be false. - CSSStyleDeclaration: false, - CSSValueList: false, - ClientRectList: false, - DOMRectList: false, - DOMStringList: false, - DOMTokenList: true, - DataTransferItemList: false, - FileList: false, - HTMLAllCollection: false, - HTMLCollection: false, - HTMLFormElement: false, - HTMLSelectElement: false, - MediaList: true, // TODO: Not spec compliant, should be false. - MimeTypeArray: false, - NamedNodeMap: false, - NodeList: true, - PaintRequestList: false, - Plugin: false, - PluginArray: false, - SVGLengthList: false, - SVGNumberList: false, - SVGPathSegList: false, - SVGPointList: false, - SVGStringList: false, - SVGTransformList: false, - SourceBufferList: false, - StyleSheetList: true, // TODO: Not spec compliant, should be false. - TextTrackCueList: false, - TextTrackList: false, - TouchList: false - }; - - for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { - var NAME = collections[i]; - var explicit = DOMIterables[NAME]; - var Collection = global[NAME]; - var proto = Collection && Collection.prototype; - var key; - if (proto) { - if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); - if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = ArrayValues; - if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); - } - } - - -/***/ }), -/* 328 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - - !(function(global) { - "use strict"; - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - if (typeof global.process === "object" && global.process.domain) { - invoke = global.process.domain.bind(invoke); - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - })( - // Among the various tricks for obtaining a reference to the global - // object, this seems to be the most reliable technique that does not - // use indirect eval (which violates Content Security Policy). - typeof global === "object" ? global : - typeof window === "object" ? window : - typeof self === "object" ? self : this - ); - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 329 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(330); - module.exports = __webpack_require__(9).RegExp.escape; - - -/***/ }), -/* 330 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/benjamingr/RexExp.escape - var $export = __webpack_require__(8); - var $re = __webpack_require__(331)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); - - $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); - - -/***/ }), -/* 331 */ -/***/ (function(module, exports) { - - module.exports = function (regExp, replace) { - var replacer = replace === Object(replace) ? function (part) { - return replace[part]; - } : replace; - return function (it) { - return String(it).replace(regExp, replacer); - }; - }; - - -/***/ }), -/* 332 */ -/***/ (function(module, exports, __webpack_require__) { - - var BSON = __webpack_require__(333), - Binary = __webpack_require__(356), - Code = __webpack_require__(351), - DBRef = __webpack_require__(355), - Decimal128 = __webpack_require__(352), - Double = __webpack_require__(336), - Int32 = __webpack_require__(350), - Long = __webpack_require__(335), - Map = __webpack_require__(334), - MaxKey = __webpack_require__(354), - MinKey = __webpack_require__(353), - ObjectId = __webpack_require__(338), - BSONRegExp = __webpack_require__(348), - Symbol = __webpack_require__(349), - Timestamp = __webpack_require__(337); - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Add BSON types to function creation - BSON.Binary = Binary; - BSON.Code = Code; - BSON.DBRef = DBRef; - BSON.Decimal128 = Decimal128; - BSON.Double = Double; - BSON.Int32 = Int32; - BSON.Long = Long; - BSON.Map = Map; - BSON.MaxKey = MaxKey; - BSON.MinKey = MinKey; - BSON.ObjectId = ObjectId; - BSON.ObjectID = ObjectId; - BSON.BSONRegExp = BSONRegExp; - BSON.Symbol = Symbol; - BSON.Timestamp = Timestamp; - - // Return the BSON - module.exports = BSON; - -/***/ }), -/* 333 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Map = __webpack_require__(334), - Long = __webpack_require__(335), - Double = __webpack_require__(336), - Timestamp = __webpack_require__(337), - ObjectID = __webpack_require__(338), - BSONRegExp = __webpack_require__(348), - Symbol = __webpack_require__(349), - Int32 = __webpack_require__(350), - Code = __webpack_require__(351), - Decimal128 = __webpack_require__(352), - MinKey = __webpack_require__(353), - MaxKey = __webpack_require__(354), - DBRef = __webpack_require__(355), - Binary = __webpack_require__(356); - - // Parts of the parser - var deserialize = __webpack_require__(357), - serializer = __webpack_require__(358), - calculateObjectSize = __webpack_require__(360), - utils = __webpack_require__(344); - - /** - * @ignore - * @api private - */ - // Default Max Size - var MAXSIZE = 1024 * 1024 * 17; - - // Current Internal Temporary Serialization Buffer - var buffer = utils.allocBuffer(MAXSIZE); - - var BSON = function () {}; - - /** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ - BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - }; - - /** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ - BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - - // Return the index - return serializationIndex - 1; - }; - - /** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ - BSON.prototype.deserialize = function (buffer, options) { - return deserialize(buffer, options); - }; - - /** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ - BSON.prototype.calculateObjectSize = function (object, options) { - options = options || {}; - - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); - }; - - /** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ - BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; - }; - - /** - * @ignore - * @api private - */ - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // Return BSON - module.exports = BSON; - module.exports.Code = Code; - module.exports.Map = Map; - module.exports.Symbol = Symbol; - module.exports.BSON = BSON; - module.exports.DBRef = DBRef; - module.exports.Binary = Binary; - module.exports.ObjectID = ObjectID; - module.exports.Long = Long; - module.exports.Timestamp = Timestamp; - module.exports.Double = Double; - module.exports.Int32 = Int32; - module.exports.MinKey = MinKey; - module.exports.MaxKey = MaxKey; - module.exports.BSONRegExp = BSONRegExp; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 334 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {'use strict'; - - // We have an ES6 Map available, return the native instance - - if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; - } else { - // We will return a polyfill - var Map = function (array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function (callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function () { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; - } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 335 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ - function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ - Long.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Long.prototype.toNumber = function () { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Long.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Long.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Long.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Long.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Long.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Long.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Long.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ - Long.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ - Long.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ - Long.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ - Long.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ - Long.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Long.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ - Long.prototype.negate = function () { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } - }; - - /** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ - Long.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ - Long.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ - Long.prototype.multiply = function (other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ - Long.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ - Long.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ - Long.prototype.not = function () { - return Long.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ - Long.prototype.and = function (other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ - Long.prototype.or = function (other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ - Long.prototype.xor = function (other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ - Long.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Long.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ - Long.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ - Long.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ - Long.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ - Long.fromBits = function (lowBits, highBits) { - return new Long(lowBits, highBits); - }; - - /** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ - Long.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ - Long.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Long.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - - /** @type {Long} */ - Long.ZERO = Long.fromInt(0); - - /** @type {Long} */ - Long.ONE = Long.fromInt(1); - - /** @type {Long} */ - Long.NEG_ONE = Long.fromInt(-1); - - /** @type {Long} */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Long} */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - - /** - * @type {Long} - * @ignore - */ - Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Long; - module.exports.Long = Long; - -/***/ }), -/* 336 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ - function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; - } - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Double.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Double; - module.exports.Double = Double; - -/***/ }), -/* 337 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ - function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ - Timestamp.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Timestamp.prototype.toNumber = function () { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Timestamp.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Timestamp.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Timestamp.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Timestamp.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Timestamp.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ - Timestamp.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Timestamp.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Timestamp.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Timestamp.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ - Timestamp.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ - Timestamp.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ - Timestamp.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ - Timestamp.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ - Timestamp.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ - Timestamp.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Timestamp.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ - Timestamp.prototype.negate = function () { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } - }; - - /** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ - Timestamp.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ - Timestamp.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ - Timestamp.prototype.multiply = function (other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ - Timestamp.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ - Timestamp.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ - Timestamp.prototype.not = function () { - return Timestamp.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ - Timestamp.prototype.and = function (other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ - Timestamp.prototype.or = function (other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ - Timestamp.prototype.xor = function (other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ - Timestamp.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Timestamp.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ - Timestamp.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Timestamp.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - - /** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ - Timestamp.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - - /** @type {Timestamp} */ - Timestamp.ZERO = Timestamp.fromInt(0); - - /** @type {Timestamp} */ - Timestamp.ONE = Timestamp.fromInt(1); - - /** @type {Timestamp} */ - Timestamp.NEG_ONE = Timestamp.fromInt(-1); - - /** @type {Timestamp} */ - Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Timestamp} */ - Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - - /** - * @type {Timestamp} - * @ignore - */ - Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Timestamp; - module.exports.Timestamp = Timestamp; - -/***/ }), -/* 338 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. - var inspect = 'inspect'; - - var utils = __webpack_require__(344); - - /** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ - var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - - // Regular expression that checks for hex value - var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - - // Check if buffer exists - try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = __webpack_require__(345).inspect.custom || 'inspect'; - } - } catch (err) { - hasBufferType = false; - } - - /** - * Create a new ObjectID instance - * - * @class - * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. - * @property {number} generationTime The generation time of this ObjectId instance - * @return {ObjectID} instance of ObjectID. - */ - var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - }; - - // Allow usage of ObjectId as well as ObjectID - // var ObjectId = ObjectID; - - // Precomputed hex table enables speedy hex string conversion - var hexTable = []; - for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); - } - - /** - * Return the ObjectID id as a 24 byte hex string representation - * - * @method - * @return {string} return the 24 byte hex string representation. - */ - ObjectID.prototype.toHexString = function () { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.get_inc = function () { - return ObjectID.index = (ObjectID.index + 1) % 0xffffff; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.getInc = function () { - return this.get_inc(); - }; - - /** - * Generate a 12 byte id buffer used in ObjectID's - * - * @method - * @param {number} [time] optional parameter allowing to pass in a second based timestamp. - * @return {Buffer} return the 12 byte id buffer string. - */ - ObjectID.prototype.generate = function (time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = MACHINE_ID >> 8 & 0xff; - buffer[4] = MACHINE_ID >> 16 & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = pid >> 8 & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = inc >> 8 & 0xff; - buffer[9] = inc >> 16 & 0xff; - // Return the buffer - return buffer; - }; - - /** - * Converts the id into a 24 byte hex string for printing - * - * @param {String} format The Buffer toString format parameter. - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); - }; - - /** - * Converts to a string representation of this Id. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype[inspect] = ObjectID.prototype.toString; - - /** - * Converts to its JSON representation. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toJSON = function () { - return this.toHexString(); - }; - - /** - * Compares the equality of this ObjectID with `otherID`. - * - * @method - * @param {object} otherID ObjectID instance to compare against. - * @return {boolean} the result of comparing two ObjectID's - */ - ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } - }; - - /** - * Returns the generation date (accurate up to the second) that this ID was generated. - * - * @method - * @return {date} the generation date - */ - ObjectID.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - - /** - * @ignore - */ - ObjectID.index = ~~(Math.random() * 0xffffff); - - /** - * @ignore - */ - ObjectID.createPk = function createPk() { - return new ObjectID(); - }; - - /** - * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. - * - * @method - * @param {number} time an integer number representing a number of seconds. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Return the new objectId - return new ObjectID(buffer); - }; - - // Lookup tables - //var encodeLookup = '0123456789abcdef'.split(''); - var decodeLookup = []; - i = 0; - while (i < 10) decodeLookup[0x30 + i] = i++; - while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - - var _Buffer = Buffer; - var convertToHex = function (bytes) { - return bytes.toString('hex'); - }; - - /** - * Creates an ObjectID from a hex string representation of an ObjectID. - * - * @method - * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || string != null && string.length !== 24) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); - }; - - /** - * Checks if a value is a valid bson ObjectId - * - * @method - * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. - */ - ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); - } - - return false; - }; - - /** - * @ignore - */ - Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function () { - return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - }, - set: function (value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = value >> 8 & 0xff; - this.id[1] = value >> 16 & 0xff; - this.id[0] = value >> 24 & 0xff; - } - }); - - /** - * Expose. - */ - module.exports = ObjectID; - module.exports.ObjectID = ObjectID; - module.exports.ObjectId = ObjectID; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer, __webpack_require__(343))) - -/***/ }), -/* 339 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(340) - var ieee754 = __webpack_require__(341) - var isArray = __webpack_require__(342) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - 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 utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - 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 - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - 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; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - 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; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - 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 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - 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; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - } - - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } 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': - // Warning: maxLength not taken into account in base64Write - 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 (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) 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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= 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 *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - 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) { - 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) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - 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 || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.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 & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (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 i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - 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 & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - 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 & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - 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) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - 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) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - 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) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - 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 < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - 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 (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - 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) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 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 < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 340 */ -/***/ (function(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; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - // Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 - - function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] - } - - // base64 is 4/3 + up to two characters of the original data - 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 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - 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) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr - } - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] - } - - function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') - } - - function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') - } - - -/***/ }), -/* 341 */ -/***/ (function(module, exports) { - - exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 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 << eLen) - 1 - var eBias = eMax >> 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 & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 - } - - -/***/ }), -/* 342 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - -/***/ }), -/* 343 */ -/***/ (function(module, exports) { - - // shim for using process in browser - var process = module.exports = {}; - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - 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) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - 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 (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - process.prependListener = noop; - process.prependOnceListener = noop; - - process.listeners = function (name) { return [] } - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }), -/* 344 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - /** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ - - function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); - } - - function newBuffer(item, encoding) { - return new Buffer(item, encoding); - } - - function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); - } - - function toBuffer() { - return Buffer.from.apply(Buffer, arguments); - } - - module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }), -/* 345 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = __webpack_require__(346); - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(347); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(343))) - -/***/ }), -/* 346 */ -/***/ (function(module, exports) { - - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } - -/***/ }), -/* 347 */ -/***/ (function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } - - -/***/ }), -/* 348 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } - } - - module.exports = BSONRegExp; - module.exports.BSONRegExp = BSONRegExp; - -/***/ }), -/* 349 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. - var inspect = Buffer ? __webpack_require__(345).inspect.custom || 'inspect' : 'inspect'; - - /** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ - function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; - } - - /** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ - Symbol.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toString = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype[inspect] = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Symbol; - module.exports.Symbol = Symbol; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }), -/* 350 */ -/***/ (function(module, exports) { - - /** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ - var Int32 = function (value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; - }; - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Int32.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Int32; - module.exports.Int32 = Int32; - -/***/ }), -/* 351 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ - var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; - }; - - /** - * @ignore - */ - Code.prototype.toJSON = function () { - return { scope: this.scope, code: this.code }; - }; - - module.exports = Code; - module.exports.Code = Code; - -/***/ }), -/* 352 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(335); - - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - - var utils = __webpack_require__(344); - - // Detect if the value is a digit - var isDigit = function (value) { - return !isNaN(parseInt(value, 10)); - }; - - // Divide two uint128 values - var divideu128 = function (value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; - }; - - // Multiply two Long values and return the 128 bit value - var multiply64x2 = function (left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; - }; - - var lessThan = function (left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; - }; - - // var longtoHex = function(value) { - // var buffer = utils.allocBuffer(8); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value.low_ & 0xff; - // buffer[index++] = (value.low_ >> 8) & 0xff; - // buffer[index++] = (value.low_ >> 16) & 0xff; - // buffer[index++] = (value.low_ >> 24) & 0xff; - // // Encode high bits - // buffer[index++] = value.high_ & 0xff; - // buffer[index++] = (value.high_ >> 8) & 0xff; - // buffer[index++] = (value.high_ >> 16) & 0xff; - // buffer[index++] = (value.high_ >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - // var int32toHex = function(value) { - // var buffer = utils.allocBuffer(4); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value & 0xff; - // buffer[index++] = (value >> 8) & 0xff; - // buffer[index++] = (value >> 16) & 0xff; - // buffer[index++] = (value >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - /** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ - var Decimal128 = function (bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; - }; - - /** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ - Decimal128.fromString = function (string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = dec.low.low_ >> 8 & 0xff; - buffer[index++] = dec.low.low_ >> 16 & 0xff; - buffer[index++] = dec.low.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = dec.low.high_ >> 8 & 0xff; - buffer[index++] = dec.low.high_ >> 16 & 0xff; - buffer[index++] = dec.low.high_ >> 24 & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = dec.high.low_ >> 8 & 0xff; - buffer[index++] = dec.high.low_ >> 16 & 0xff; - buffer[index++] = dec.high.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = dec.high.high_ >> 8 & 0xff; - buffer[index++] = dec.high.high_ >> 16 & 0xff; - buffer[index++] = dec.high.high_ >> 24 & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); - }; - - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Value of combination field for NaN - // var COMBINATION_SNAN = 32; - // decimal128 exponent bias - EXPONENT_BIAS = 6176; - - /** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack the high 64bits into a long - midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = high >> 26 & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = high >> 15 & EXPONENT_MASK; - significand_msb = 0x08 + (high >> 14 & 0x01); - } - } else { - significand_msb = high >> 14 & 0x07; - biased_exponent = high >> 17 & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); - }; - - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - - module.exports = Decimal128; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 353 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ - function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; - } - - module.exports = MinKey; - module.exports.MinKey = MinKey; - -/***/ }), -/* 354 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ - function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; - } - - module.exports = MaxKey; - module.exports.MaxKey = MaxKey; - -/***/ }), -/* 355 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ - function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; - } - - /** - * @ignore - * @api private - */ - DBRef.prototype.toJSON = function () { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; - }; - - module.exports = DBRef; - module.exports.DBRef = DBRef; - -/***/ }), -/* 356 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - * @ignore - */ - - // Test if we're in Node via presence of "global" not absence of "window" - // to support hybrid environments like Electron - if (typeof global !== 'undefined') { - var Buffer = __webpack_require__(339).Buffer; // TODO just use global Buffer - } - - var utils = __webpack_require__(344); - - /** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if (typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]') { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } - } - - /** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ - Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); - if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } - }; - - /** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ - Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if (Object.prototype.toString.call(string) === '[object Uint8Array]' || Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } - }; - - /** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ - Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; - }; - - /** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ - Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } - }; - - /** - * Length. - * - * @method - * @return {number} the length of the binary. - */ - Binary.prototype.length = function length() { - return this.position; - }; - - /** - * @ignore - */ - Binary.prototype.toJSON = function () { - return this.buffer != null ? this.buffer.toString('base64') : ''; - }; - - /** - * @ignore - */ - Binary.prototype.toString = function (format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; - }; - - /** - * Binary default subtype - * @ignore - */ - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - - /** - * @ignore - */ - var writeStringToArray = function (data) { - // Create a buffer - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; - }; - - /** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ - var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; - }; - - Binary.BUFFER_SIZE = 256; - - /** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_DEFAULT = 0; - /** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_FUNCTION = 1; - /** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID_OLD = 3; - /** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID = 4; - /** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_MD5 = 5; - /** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_USER_DEFINED = 128; - - /** - * Expose. - */ - module.exports = Binary; - module.exports.Binary = Binary; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 357 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(335).Long, - Double = __webpack_require__(336).Double, - Timestamp = __webpack_require__(337).Timestamp, - ObjectID = __webpack_require__(338).ObjectID, - Symbol = __webpack_require__(349).Symbol, - Code = __webpack_require__(351).Code, - MinKey = __webpack_require__(353).MinKey, - MaxKey = __webpack_require__(354).MaxKey, - Decimal128 = __webpack_require__(352), - Int32 = __webpack_require__(350), - DBRef = __webpack_require__(355).DBRef, - BSONRegExp = __webpack_require__(348).BSONRegExp, - Binary = __webpack_require__(356).Binary; - - var utils = __webpack_require__(344); - - var deserialize = function (buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - }; - - var deserializeObject = function (buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEvalWithHash = function (functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEval = function (functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - var functionCache = BSON.functionCache = {}; - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ - BSON.BSON_DATA_DBPOINTER = 12; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = deserialize; - -/***/ }), -/* 358 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var writeIEEE754 = __webpack_require__(359).writeIEEE754, - Long = __webpack_require__(335).Long, - Map = __webpack_require__(334), - Binary = __webpack_require__(356).Binary; - - var normalizedFunctionString = __webpack_require__(344).normalizedFunctionString; - - // try { - // var _Buffer = Uint8Array; - // } catch (e) { - // _Buffer = Buffer; - // } - - var regexp = /\x00/; // eslint-disable-line no-control-regex - var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - }; - - var serializeString = function (buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = size + 1 >> 24 & 0xff; - buffer[index + 2] = size + 1 >> 16 & 0xff; - buffer[index + 1] = size + 1 >> 8 & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeNumber = function (buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - }; - - var serializeNull = function (buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeBoolean = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - }; - - var serializeDate = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeBSONRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeMinMax = function (buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeObjectId = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; - }; - - var serializeBuffer = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - }; - - var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - // Write size - return endIndex; - }; - - var serializeDecimal128 = function (buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; - }; - - var serializeLong = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeInt32 = function (buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - return index; - }; - - var serializeDouble = function (buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - }; - - var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = codeSize >> 8 & 0xff; - buffer[index + 2] = codeSize >> 16 & 0xff; - buffer[index + 3] = codeSize >> 24 & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = totalSize >> 8 & 0xff; - buffer[startIndex++] = totalSize >> 16 & 0xff; - buffer[startIndex++] = totalSize >> 24 & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; - }; - - var serializeBinary = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; - }; - - var serializeSymbol = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - }; - - var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = size >> 8 & 0xff; - buffer[startIndex++] = size >> 16 & 0xff; - buffer[startIndex++] = size >> 24 & 0xff; - // Set index - return endIndex; - }; - - var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || value === undefined && ignoreUndefined === false) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = size >> 8 & 0xff; - buffer[startingIndex++] = size >> 16 & 0xff; - buffer[startingIndex++] = size >> 24 & 0xff; - return index; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - // var functionCache = (BSON.functionCache = {}); - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = serializeInto; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }), -/* 359 */ -/***/ (function(module, exports) { - - // Copyright (c) 2008, Fair Oaks Labs, Inc. - // All rights reserved. - // - // Redistribution and use in source and binary forms, with or without - // modification, are permitted provided that the following conditions are met: - // - // * Redistributions of source code must retain the above copyright notice, - // this list of conditions and the following disclaimer. - // - // * Redistributions in binary form must reproduce the above copyright notice, - // this list of conditions and the following disclaimer in the documentation - // and/or other materials provided with the distribution. - // - // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors - // may be used to endorse or promote products derived from this software - // without specific prior written permission. - // - // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - // POSSIBILITY OF SUCH DAMAGE. - // - // - // Modifications to writeIEEE754 to support negative zeroes made by Brian White - - var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - 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); - }; - - var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - 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 & 0xff, i += d, m /= 256, mLen -= 8); - - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; - }; - - exports.readIEEE754 = readIEEE754; - exports.writeIEEE754 = writeIEEE754; - -/***/ }), -/* 360 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Long = __webpack_require__(335).Long, - Double = __webpack_require__(336).Double, - Timestamp = __webpack_require__(337).Timestamp, - ObjectID = __webpack_require__(338).ObjectID, - Symbol = __webpack_require__(349).Symbol, - BSONRegExp = __webpack_require__(348).BSONRegExp, - Code = __webpack_require__(351).Code, - Decimal128 = __webpack_require__(352), - MinKey = __webpack_require__(353).MinKey, - MaxKey = __webpack_require__(354).MaxKey, - DBRef = __webpack_require__(355).DBRef, - Binary = __webpack_require__(356).Binary; - - var normalizedFunctionString = __webpack_require__(344).normalizedFunctionString; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; - }; - - /** - * @ignore - * @api private - */ - function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; - } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if (serializeFunctions) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; - } - } - } - - return 0; - } - - var BSON = {}; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = calculateObjectSize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }) -/******/ ]) -}); -; \ No newline at end of file diff --git a/reverse_engineering/node_modules/bson/browser_build/package.json b/reverse_engineering/node_modules/bson/browser_build/package.json deleted file mode 100644 index 980db7f..0000000 --- a/reverse_engineering/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/reverse_engineering/node_modules/bson/index.js b/reverse_engineering/node_modules/bson/index.js deleted file mode 100644 index 6502552..0000000 --- a/reverse_engineering/node_modules/bson/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var BSON = require('./lib/bson/bson'), - Binary = require('./lib/bson/binary'), - Code = require('./lib/bson/code'), - DBRef = require('./lib/bson/db_ref'), - Decimal128 = require('./lib/bson/decimal128'), - Double = require('./lib/bson/double'), - Int32 = require('./lib/bson/int_32'), - Long = require('./lib/bson/long'), - Map = require('./lib/bson/map'), - MaxKey = require('./lib/bson/max_key'), - MinKey = require('./lib/bson/min_key'), - ObjectId = require('./lib/bson/objectid'), - BSONRegExp = require('./lib/bson/regexp'), - Symbol = require('./lib/bson/symbol'), - Timestamp = require('./lib/bson/timestamp'); - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Add BSON types to function creation -BSON.Binary = Binary; -BSON.Code = Code; -BSON.DBRef = DBRef; -BSON.Decimal128 = Decimal128; -BSON.Double = Double; -BSON.Int32 = Int32; -BSON.Long = Long; -BSON.Map = Map; -BSON.MaxKey = MaxKey; -BSON.MinKey = MinKey; -BSON.ObjectId = ObjectId; -BSON.ObjectID = ObjectId; -BSON.BSONRegExp = BSONRegExp; -BSON.Symbol = Symbol; -BSON.Timestamp = Timestamp; - -// Return the BSON -module.exports = BSON; diff --git a/reverse_engineering/node_modules/bson/lib/bson/binary.js b/reverse_engineering/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 6d190bc..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,384 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ - -// Test if we're in Node via presence of "global" not absence of "window" -// to support hybrid environments like Electron -if (typeof global !== 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -var utils = require('./parser/utils'); - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if ( - buffer != null && - !(typeof buffer === 'string') && - !Buffer.isBuffer(buffer) && - !(buffer instanceof Uint8Array) && - !Array.isArray(buffer) - ) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if ( - typeof Uint8Array !== 'undefined' || - Object.prototype.toString.call(buffer) === '[object Array]' - ) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -} - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) - throw new Error('only accepts single character String, Uint8Array or Array'); - if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) - throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if ( - typeof Buffer !== 'undefined' && - typeof string === 'string' && - Buffer.isBuffer(this.buffer) - ) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if ( - Object.prototype.toString.call(string) === '[object Uint8Array]' || - (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') - ) { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(length)) - : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if ( - asRaw && - typeof Buffer !== 'undefined' && - Buffer.isBuffer(this.buffer) && - this.buffer.length === this.position - ) - return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw - ? this.buffer.slice(0, this.position) - : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = - Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' - ? new Uint8Array(new ArrayBuffer(this.position)) - : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -}; - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -}; - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(data.length)) - : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -}; - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; diff --git a/reverse_engineering/node_modules/bson/lib/bson/bson.js b/reverse_engineering/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 912c5b9..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,386 +0,0 @@ -'use strict'; - -var Map = require('./map'), - Long = require('./long'), - Double = require('./double'), - Timestamp = require('./timestamp'), - ObjectID = require('./objectid'), - BSONRegExp = require('./regexp'), - Symbol = require('./symbol'), - Int32 = require('./int_32'), - Code = require('./code'), - Decimal128 = require('./decimal128'), - MinKey = require('./min_key'), - MaxKey = require('./max_key'), - DBRef = require('./db_ref'), - Binary = require('./binary'); - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'), - utils = require('./parser/utils'); - -/** - * @ignore - * @api private - */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; - -// Current Internal Temporary Serialization Buffer -var buffer = utils.allocBuffer(MAXSIZE); - -var BSON = function() {}; - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = - typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer( - buffer, - object, - checkKeys, - 0, - 0, - serializeFunctions, - ignoreUndefined, - [] - ); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -}; - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer( - finalBuffer, - object, - checkKeys, - startIndex || 0, - 0, - serializeFunctions, - ignoreUndefined - ); - - // Return the index - return serializationIndex - 1; -}; - -/** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(buffer, options) { - return deserialize(buffer, options); -}; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, options) { - options = options || {}; - - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -}; - -/** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function( - data, - startIndex, - numberOfDocuments, - documents, - docStartIndex, - options -) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = - data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.Int32 = Int32; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; -module.exports.Decimal128 = Decimal128; diff --git a/reverse_engineering/node_modules/bson/lib/bson/code.js b/reverse_engineering/node_modules/bson/lib/bson/code.js deleted file mode 100644 index c2984cd..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return { scope: this.scope, code: this.code }; -}; - -module.exports = Code; -module.exports.Code = Code; diff --git a/reverse_engineering/node_modules/bson/lib/bson/db_ref.js b/reverse_engineering/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index f95795b..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -} - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; -}; - -module.exports = DBRef; -module.exports.DBRef = DBRef; diff --git a/reverse_engineering/node_modules/bson/lib/bson/decimal128.js b/reverse_engineering/node_modules/bson/lib/bson/decimal128.js deleted file mode 100644 index 924513f..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/decimal128.js +++ /dev/null @@ -1,820 +0,0 @@ -'use strict'; - -var Long = require('./long'); - -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; - -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); - -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - -var utils = require('./parser/utils'); - -// Detect if the value is a digit -var isDigit = function(value) { - return !isNaN(parseInt(value, 10)); -}; - -// Divide two uint128 values -var divideu128 = function(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; -}; - -// Multiply two Long values and return the 128 bit value -var multiply64x2 = function(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; -}; - -var lessThan = function(left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; -}; - -// var longtoHex = function(value) { -// var buffer = utils.allocBuffer(8); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value.low_ & 0xff; -// buffer[index++] = (value.low_ >> 8) & 0xff; -// buffer[index++] = (value.low_ >> 16) & 0xff; -// buffer[index++] = (value.low_ >> 24) & 0xff; -// // Encode high bits -// buffer[index++] = value.high_ & 0xff; -// buffer[index++] = (value.high_ >> 8) & 0xff; -// buffer[index++] = (value.high_ >> 16) & 0xff; -// buffer[index++] = (value.high_ >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -// var int32toHex = function(value) { -// var buffer = utils.allocBuffer(4); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value & 0xff; -// buffer[index++] = (value >> 8) & 0xff; -// buffer[index++] = (value >> 16) & 0xff; -// buffer[index++] = (value >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -/** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ -var Decimal128 = function(bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; -}; - -/** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ -Decimal128.fromString = function(string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128( - utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) - ); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if ( - significand.high - .shiftRightUnsigned(49) - .and(Long.fromNumber(1)) - .equals(Long.fromNumber) - ) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or( - Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) - ); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = (dec.low.low_ >> 8) & 0xff; - buffer[index++] = (dec.low.low_ >> 16) & 0xff; - buffer[index++] = (dec.low.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = (dec.low.high_ >> 8) & 0xff; - buffer[index++] = (dec.low.high_ >> 16) & 0xff; - buffer[index++] = (dec.low.high_ >> 24) & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = (dec.high.low_ >> 8) & 0xff; - buffer[index++] = (dec.high.low_ >> 16) & 0xff; - buffer[index++] = (dec.high.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = (dec.high.high_ >> 8) & 0xff; - buffer[index++] = (dec.high.high_ >> 16) & 0xff; - buffer[index++] = (dec.high.high_ >> 24) & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); -}; - -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Value of combination field for NaN -// var COMBINATION_SNAN = 32; -// decimal128 exponent bias -EXPONENT_BIAS = 6176; - -/** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ -Decimal128.prototype.toString = function() { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - midl = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack the high 64bits into a long - midh = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - high = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = (high >> 26) & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if ( - significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0 - ) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); -}; - -Decimal128.prototype.toJSON = function() { - return { $numberDecimal: this.toString() }; -}; - -module.exports = Decimal128; -module.exports.Decimal128 = Decimal128; diff --git a/reverse_engineering/node_modules/bson/lib/bson/double.js b/reverse_engineering/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 523c21f..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Double; -module.exports.Double = Double; diff --git a/reverse_engineering/node_modules/bson/lib/bson/float_parser.js b/reverse_engineering/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 0054a2f..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - 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); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - 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 & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; diff --git a/reverse_engineering/node_modules/bson/lib/bson/int_32.js b/reverse_engineering/node_modules/bson/lib/bson/int_32.js deleted file mode 100644 index 85dbdec..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/int_32.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ -var Int32 = function(value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; -}; - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ -Int32.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Int32.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Int32; -module.exports.Int32 = Int32; diff --git a/reverse_engineering/node_modules/bson/lib/bson/long.js b/reverse_engineering/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 551d1a6..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,865 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** Converts the Long to a BigInt (arbitrary precision). */ -Long.prototype.toBigInt = function () { - return BigInt(this.toString()); -} - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param {bigint} value - The number in question - * @returns {Long} The corresponding Long value - */ -Long.fromBigInt = function(value) { - return Long.fromString(value.toString(10), 10); -} - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; diff --git a/reverse_engineering/node_modules/bson/lib/bson/map.js b/reverse_engineering/node_modules/bson/lib/bson/map.js deleted file mode 100644 index 7edb4f2..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -// We have an ES6 Map available, return the native instance -if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function(key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function(key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function() { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; -} diff --git a/reverse_engineering/node_modules/bson/lib/bson/max_key.js b/reverse_engineering/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index eebca7b..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; diff --git a/reverse_engineering/node_modules/bson/lib/bson/min_key.js b/reverse_engineering/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 15f4522..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; diff --git a/reverse_engineering/node_modules/bson/lib/bson/objectid.js b/reverse_engineering/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 0ebcc03..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,392 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = 'inspect'; - -var utils = require('./parser/utils'); - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - -// Check if buffer exists -try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = require('util').inspect.custom || 'inspect'; - } -} catch (err) { - hasBufferType = false; -} - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && typeof id.toHexString === 'function') { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); -}; - -// Allow usage of ObjectId as well as ObjectID -// var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error( - 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + - JSON.stringify(this.id) + - ']' - ); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id buffer used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {Buffer} return the 12 byte id buffer string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = - (typeof process === 'undefined' || process.pid === 1 - ? Math.floor(Math.random() * 100000) - : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = (MACHINE_ID >> 8) & 0xff; - buffer[4] = (MACHINE_ID >> 16) & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = (pid >> 8) & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - // Return the buffer - return buffer; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @param {String} format The Buffer toString format parameter. -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function(format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype[inspect] = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if ( - typeof otherId === 'string' && - ObjectID.isValid(otherId) && - otherId.length === 12 && - this.id instanceof _Buffer - ) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } -}; - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; -}; - -/** -* @ignore -*/ -ObjectID.index = ~~(Math.random() * 0xffffff); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk() { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Return the new objectId - return new ObjectID(buffer); -}; - -// Lookup tables -//var encodeLookup = '0123456789abcdef'.split(''); -var decodeLookup = []; -i = 0; -while (i < 10) decodeLookup[0x30 + i] = i++; -while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - -var _Buffer = Buffer; -var convertToHex = function(bytes) { - return bytes.toString('hex'); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || (string != null && string.length !== 24)) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if ( - typeof id.toHexString === 'function' && - (id.id instanceof _Buffer || typeof id.id === 'string') - ) { - return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); - } - - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function() { - return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - }, - set: function(value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = (value >> 8) & 0xff; - this.id[1] = (value >> 16) & 0xff; - this.id[0] = (value >> 24) & 0xff; - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/reverse_engineering/node_modules/bson/lib/bson/parser/calculate_size.js b/reverse_engineering/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index 7e0026c..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - BSONRegExp = require('../regexp').BSONRegExp, - Code = require('../code').Code, - Decimal128 = require('../decimal128'), - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var calculateObjectSize = function calculateObjectSize( - object, - serializeFunctions, - ignoreUndefined -) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement( - i.toString(), - object[i], - serializeFunctions, - true, - ignoreUndefined - ); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; -}; - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if ( - value == null || - value instanceof MinKey || - value instanceof MaxKey || - value['_bsontype'] === 'MinKey' || - value['_bsontype'] === 'MaxKey' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length - ); - } else if ( - value instanceof Long || - value instanceof Double || - value instanceof Timestamp || - value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 - ); - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) - ); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - Buffer.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1 - ); - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) - ); - } else if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.pattern, 'utf8') + - 1 + - Buffer.byteLength(value.options, 'utf8') + - 1 - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1 - ); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' || - String.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else if (serializeFunctions) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 - ); - } - } - } - - return 0; -} - -var BSON = {}; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = calculateObjectSize; diff --git a/reverse_engineering/node_modules/bson/lib/bson/parser/deserializer.js b/reverse_engineering/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index be3c865..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - Decimal128 = require('../decimal128'), - Int32 = require('../int_32'), - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var utils = require('./utils'); - -var deserialize = function(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -}; - -var deserializeObject = function(buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = - options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32( - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) - ); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(binarySize)) - : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error( - 'Detected unknown BSON type ' + - elementType.toString(16) + - ' for fieldname "' + - name + - '", are you using the latest BSON parser' - ); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ -BSON.BSON_DATA_DBPOINTER = 12; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = deserialize; diff --git a/reverse_engineering/node_modules/bson/lib/bson/parser/serializer.js b/reverse_engineering/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index fab9b6f..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,1194 +0,0 @@ -'use strict'; - -var writeIEEE754 = require('../float_parser').writeIEEE754, - Long = require('../long').Long, - Map = require('../map'), - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// try { -// var _Buffer = Uint8Array; -// } catch (e) { -// _Buffer = Buffer; -// } - -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -}; - -var serializeString = function(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeNumber = function(buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -}; - -var serializeNull = function(buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeBoolean = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -}; - -var serializeDate = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeBSONRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = - index + - buffer.write( - value.options - .split('') - .sort() - .join(''), - index, - 'utf8' - ); - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeMinMax = function(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeObjectId = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; -}; - -var serializeBuffer = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -}; - -var serializeObject = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray, - path -) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto( - buffer, - value, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined, - path - ); - // Pop stack - path.pop(); - // Write size - return endIndex; -}; - -var serializeDecimal128 = function(buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; -}; - -var serializeLong = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeInt32 = function(buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -}; - -var serializeDouble = function(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -}; - -var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeCode = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray -) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto( - buffer, - value.scope, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined - ); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -}; - -var serializeBinary = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -}; - -var serializeSymbol = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -}; - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, - false, - index, - depth + 1, - serializeFunctions - ); - } else { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid - }, - false, - index, - depth + 1, - serializeFunctions - ); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -}; - -var serializeInto = function serializeInto( - buffer, - object, - checkKeys, - startingIndex, - depth, - serializeFunctions, - ignoreUndefined, - path -) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if(type === 'bigint') { - throw new TypeError('Unsupported type BigInt, please use Decimal128'); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - true - ); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true - ); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type === 'bigint') { - throw new TypeError('Unsupported type BigInt, please use Decimal128'); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type === 'bigint') { - throw new TypeError('Unsupported type BigInt, please use Decimal128'); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -// var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = serializeInto; diff --git a/reverse_engineering/node_modules/bson/lib/bson/parser/utils.js b/reverse_engineering/node_modules/bson/lib/bson/parser/utils.js deleted file mode 100644 index 6faa439..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/parser/utils.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); -} - -function newBuffer(item, encoding) { - return new Buffer(item, encoding); -} - -function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); -} - -function toBuffer() { - return Buffer.from.apply(Buffer, arguments); -} - -module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer -}; - diff --git a/reverse_engineering/node_modules/bson/lib/bson/regexp.js b/reverse_engineering/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 108f016..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if ( - !( - this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u' - ) - ) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; diff --git a/reverse_engineering/node_modules/bson/lib/bson/symbol.js b/reverse_engineering/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index ba20cab..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,50 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; - -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype[inspect] = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Symbol; -module.exports.Symbol = Symbol; diff --git a/reverse_engineering/node_modules/bson/lib/bson/timestamp.js b/reverse_engineering/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index dc61a6c..0000000 --- a/reverse_engineering/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,854 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0 - ); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; diff --git a/reverse_engineering/node_modules/bson/package.json b/reverse_engineering/node_modules/bson/package.json deleted file mode 100644 index 5dc76e8..0000000 --- a/reverse_engineering/node_modules/bson/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "files": [ - "lib", - "index.js", - "browser_build", - "bower.json" - ], - "version": "1.1.6", - "author": "Christian Amor Kvalheim ", - "contributors": [], - "repository": "mongodb/js-bson", - "bugs": { - "mail": "node-mongodb-native@googlegroups.com", - "url": "https://github.com/mongodb/js-bson/issues" - }, - "devDependencies": { - "benchmark": "1.0.0", - "colors": "1.1.0", - "nodeunit": "0.9.0", - "babel-core": "^6.14.0", - "babel-loader": "^6.2.5", - "babel-polyfill": "^6.13.0", - "babel-preset-es2015": "^6.14.0", - "babel-preset-stage-0": "^6.5.0", - "babel-register": "^6.14.0", - "conventional-changelog-cli": "^1.3.5", - "standard-version": "^9.1.1", - "webpack": "^1.13.2", - "webpack-polyfills-plugin": "0.0.9" - }, - "config": { - "native": false - }, - "main": "./index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "nodeunit ./test/node", - "build": "webpack --config ./webpack.dist.config.js", - "changelog": "conventional-changelog -p angular -i HISTORY.md -s", - "lint": "eslint lib test", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "release": "standard-version -i HISTORY.md" - }, - "browser": "lib/bson/bson.js", - "license": "Apache-2.0" -} diff --git a/reverse_engineering/node_modules/buffer/AUTHORS.md b/reverse_engineering/node_modules/buffer/AUTHORS.md deleted file mode 100644 index 22eb171..0000000 --- a/reverse_engineering/node_modules/buffer/AUTHORS.md +++ /dev/null @@ -1,70 +0,0 @@ -# Authors - -#### Ordered by first contribution. - -- Romain Beauxis (toots@rastageeks.org) -- Tobias Koppers (tobias.koppers@googlemail.com) -- Janus (ysangkok@gmail.com) -- Rainer Dreyer (rdrey1@gmail.com) -- Tõnis Tiigi (tonistiigi@gmail.com) -- James Halliday (mail@substack.net) -- Michael Williamson (mike@zwobble.org) -- elliottcable (github@elliottcable.name) -- rafael (rvalle@livelens.net) -- Andrew Kelley (superjoe30@gmail.com) -- Andreas Madsen (amwebdk@gmail.com) -- Mike Brevoort (mike.brevoort@pearson.com) -- Brian White (mscdex@mscdex.net) -- Feross Aboukhadijeh (feross@feross.org) -- Ruben Verborgh (ruben@verborgh.org) -- eliang (eliang.cs@gmail.com) -- Jesse Tane (jesse.tane@gmail.com) -- Alfonso Boza (alfonso@cloud.com) -- Mathias Buus (mathiasbuus@gmail.com) -- Devon Govett (devongovett@gmail.com) -- Daniel Cousens (github@dcousens.com) -- Joseph Dykstra (josephdykstra@gmail.com) -- Parsha Pourkhomami (parshap+git@gmail.com) -- Damjan Košir (damjan.kosir@gmail.com) -- daverayment (dave.rayment@gmail.com) -- kawanet (u-suke@kawa.net) -- Linus Unnebäck (linus@folkdatorn.se) -- Nolan Lawson (nolan.lawson@gmail.com) -- Calvin Metcalf (calvin.metcalf@gmail.com) -- Koki Takahashi (hakatasiloving@gmail.com) -- Guy Bedford (guybedford@gmail.com) -- Jan Schär (jscissr@gmail.com) -- RaulTsc (tomescu.raul@gmail.com) -- Matthieu Monsch (monsch@alum.mit.edu) -- Dan Ehrenberg (littledan@chromium.org) -- Kirill Fomichev (fanatid@ya.ru) -- Yusuke Kawasaki (u-suke@kawa.net) -- DC (dcposch@dcpos.ch) -- John-David Dalton (john.david.dalton@gmail.com) -- adventure-yunfei (adventure030@gmail.com) -- Emil Bay (github@tixz.dk) -- Sam Sudar (sudar.sam@gmail.com) -- Volker Mische (volker.mische@gmail.com) -- David Walton (support@geekstocks.com) -- Сковорода Никита Андреевич (chalkerx@gmail.com) -- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) -- ukstv (sergey.ukustov@machinomy.com) -- Renée Kooi (renee@kooi.me) -- ranbochen (ranbochen@qq.com) -- Vladimir Borovik (bobahbdb@gmail.com) -- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) -- kumavis (aaron@kumavis.me) -- Sergey Ukustov (sergey.ukustov@machinomy.com) -- Fei Liu (liu.feiwood@gmail.com) -- Blaine Bublitz (blaine.bublitz@gmail.com) -- clement (clement@seald.io) -- Koushik Dutta (koushd@gmail.com) -- Jordan Harband (ljharb@gmail.com) -- Niklas Mischkulnig (mischnic@users.noreply.github.com) -- Nikolai Vavilov (vvnicholas@gmail.com) -- Fedor Nezhivoi (gyzerok@users.noreply.github.com) -- Peter Newman (peternewman@users.noreply.github.com) -- mathmakgakpak (44949126+mathmakgakpak@users.noreply.github.com) -- jkkang (jkkang@smartauth.kr) - -#### Generated by bin/update-authors.sh. diff --git a/reverse_engineering/node_modules/buffer/LICENSE b/reverse_engineering/node_modules/buffer/LICENSE deleted file mode 100644 index d6bf75d..0000000 --- a/reverse_engineering/node_modules/buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh, and other contributors. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/buffer/README.md b/reverse_engineering/node_modules/buffer/README.md deleted file mode 100644 index 9a23d7c..0000000 --- a/reverse_engineering/node_modules/buffer/README.md +++ /dev/null @@ -1,410 +0,0 @@ -# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg -[travis-url]: https://travis-ci.org/feross/buffer -[npm-image]: https://img.shields.io/npm/v/buffer.svg -[npm-url]: https://npmjs.org/package/buffer -[downloads-image]: https://img.shields.io/npm/dm/buffer.svg -[downloads-url]: https://npmjs.org/package/buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### The buffer module from [node.js](https://nodejs.org/), for the browser. - -[![saucelabs][saucelabs-image]][saucelabs-url] - -[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg -[saucelabs-url]: https://saucelabs.com/u/buffer - -With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. - -The goal is to provide an API that is 100% identical to -[node's Buffer API](https://nodejs.org/api/buffer.html). Read the -[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, -instance methods, and class methods that are supported. - -## features - -- Manipulate binary data like a boss, in all browsers! -- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) -- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) -- Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) -- Preserves Node API exactly, with one minor difference (see below) -- Square-bracket `buf[4]` notation works! -- Does not modify any browser prototypes or put anything on `window` -- Comprehensive test suite (including all buffer tests from node.js core) - -## install - -To use this module directly (without browserify), install it: - -```bash -npm install buffer -``` - -This module was previously called **native-buffer-browserify**, but please use **buffer** -from now on. - -If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). - -## usage - -The module's API is identical to node's `Buffer` API. Read the -[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, -instance methods, and class methods that are supported. - -As mentioned above, `require('buffer')` or use the `Buffer` global with -[browserify](http://browserify.org) and this module will automatically be included -in your bundle. Almost any npm module will work in the browser, even if it assumes that -the node `Buffer` API will be available. - -To depend on this module explicitly (without browserify), require it like this: - -```js -var Buffer = require('buffer/').Buffer // note: the trailing slash is important! -``` - -To require this module explicitly, use `require('buffer/')` which tells the node.js module -lookup algorithm (also used by browserify) to use the **npm module** named `buffer` -instead of the **node.js core** module named `buffer`! - - -## how does it work? - -The Buffer constructor returns instances of `Uint8Array` that have their prototype -changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, -so the returned instances will have all the node `Buffer` methods and the -`Uint8Array` methods. Square bracket notation works as expected -- it returns a -single octet. - -The `Uint8Array` prototype remains unmodified. - - -## tracking the latest node api - -This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer -API is considered **stable** in the -[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), -so it is unlikely that there will ever be breaking changes. -Nonetheless, when/if the Buffer API changes in node, this module's API will change -accordingly. - -## related packages - -- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer -- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer -- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package - -## conversion packages - -### convert typed array to buffer - -Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. - -### convert buffer to typed array - -`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. - -### convert blob to buffer - -Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. - -### convert buffer to blob - -To convert a `Buffer` to a `Blob`, use the `Blob` constructor: - -```js -var blob = new Blob([ buffer ]) -``` - -Optionally, specify a mimetype: - -```js -var blob = new Blob([ buffer ], { type: 'text/html' }) -``` - -### convert arraybuffer to buffer - -To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. - -```js -var buffer = Buffer.from(arrayBuffer) -``` - -### convert buffer to arraybuffer - -To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): - -```js -var arrayBuffer = buffer.buffer.slice( - buffer.byteOffset, buffer.byteOffset + buffer.byteLength -) -``` - -Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. - -## performance - -See perf tests in `/perf`. - -`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a -sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will -always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, -which is included to compare against. - -NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. - -### Chrome 38 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | -| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | -| | | | | -| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | -| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | -| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | -| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | -| | | | | -| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | -| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | -| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | -| | | | | -| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | -| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | -| | | | | -| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | -| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | -| | | | | -| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | -| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | -| | | | | -| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | -| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | -| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | - - -### Firefox 33 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | -| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | -| | | | | -| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | -| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | -| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | -| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | -| | | | | -| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | -| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | -| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | -| | | | | -| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | -| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | -| | | | | -| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | -| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | -| | | | | -| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | -| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | -| | | | | -| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | -| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | -| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | - -### Safari 8 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | -| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | -| | | | | -| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | -| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | -| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | -| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | -| | | | | -| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | -| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | -| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | -| | | | | -| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | -| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | -| | | | | -| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | -| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | -| | | | | -| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | -| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | -| | | | | -| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | -| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | -| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | - - -### Node 0.11.14 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | -| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | -| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | -| | | | | -| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | -| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | -| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | -| | | | | -| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | -| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | -| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | -| | | | | -| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | -| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | -| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | -| | | | | -| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | -| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | -| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | -| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | -| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | -| | | | | -| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | -| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | -| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | -| | | | | -| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | -| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | -| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | -| | | | | -| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | -| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | -| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | -| | | | | -| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | -| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | -| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | -| | | | | -| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | -| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | -| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | - -### iojs 1.8.1 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | -| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | -| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | -| | | | | -| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | -| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | -| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | -| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | -| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | -| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | -| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | -| | | | | -| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | -| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | -| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | -| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | -| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | -| | | | | -| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | -| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | -| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | -| | | | | -| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | -| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | -| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | -| | | | | -| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | -| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | -| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | -| | | | | -| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | -| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | -| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | -| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | -| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | -| | | | | - -## Testing the project - -First, install the project: - - npm install - -Then, to run tests in Node.js, run: - - npm run test-node - -To test locally in a browser, you can run: - - npm run test-browser-es5-local # For ES5 browsers that don't support ES6 - npm run test-browser-es6-local # For ES6 compliant browsers - -This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). - -To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: - - npm test - -This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. - -## JavaScript Standard Style - -This module uses [JavaScript Standard Style](https://github.com/feross/standard). - -[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) - -To test that the code conforms to the style, `npm install` and run: - - ./node_modules/.bin/standard - -## credit - -This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). - -## Security Policies and Procedures - -The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/reverse_engineering/node_modules/buffer/index.d.ts b/reverse_engineering/node_modules/buffer/index.d.ts deleted file mode 100644 index 5d1a804..0000000 --- a/reverse_engineering/node_modules/buffer/index.d.ts +++ /dev/null @@ -1,186 +0,0 @@ -export class Buffer extends Uint8Array { - length: number - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - reverse(): this; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor (str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor (size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor (arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor (buffer: Buffer); - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer | Uint8Array): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initializing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; -} diff --git a/reverse_engineering/node_modules/buffer/index.js b/reverse_engineering/node_modules/buffer/index.js deleted file mode 100644 index 609cf31..0000000 --- a/reverse_engineering/node_modules/buffer/index.js +++ /dev/null @@ -1,1817 +0,0 @@ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var customInspectSymbol = - (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation - ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation - : null - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -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 () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - var proto = { foo: function () { return 42 } } - Object.setPrototypeOf(proto, Uint8Array.prototype) - Object.setPrototypeOf(arr, proto) - 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"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - Object.setPrototypeOf(buf, Buffer.prototype) - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - 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) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayView(value) - } - - if (value == null) { - throw new 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 SharedArrayBuffer !== 'undefined' && - (isInstance(value, SharedArrayBuffer) || - (value && isInstance(value.buffer, SharedArrayBuffer)))) { - 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) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) -Object.setPrototypeOf(Buffer, 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) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpreted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -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) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - 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 < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayView (arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView) - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) - } - return fromArrayLike(arrayView) -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(buf, Buffer.prototype) - - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= 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) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -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); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer.from(buf).copy(buffer, pos) - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ) - } - } else if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } else { - buf.copy(buffer, pos) - } - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - 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 // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coercion to uint32. This will also coerce falsey/NaN values to 0. - 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 - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -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; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} -if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect -} - -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; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - 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 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-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; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 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': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - 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 (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) - ? 4 - : (firstByte > 0xDF) - ? 3 - : (firstByte > 0xBF) - ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]] - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - for (var i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(newBuf, Buffer.prototype) - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUintLE = -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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUintBE = -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUint8 = -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUint16LE = -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 = -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 = -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] * 0x1000000) -} - -Buffer.prototype.readUint32BE = -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= 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 *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - 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] & 0x80)) return (this[offset]) - return ((0xff - 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 & 0x8000) ? val | 0xFFFF0000 : 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 & 0x8000) ? val | 0xFFFF0000 : 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 || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUintLE = -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 & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUintBE = -Buffer.prototype.writeUIntBE = function writeUIntBE (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 i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUint8 = -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUint16LE = -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUint16BE = -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUint32LE = -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUint32BE = -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - 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 & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - 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 & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - 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, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - 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, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - 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, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - 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, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - 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) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -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 < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - 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') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } else if (typeof val === 'boolean') { - val = Number(val) - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 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 < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -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) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -// Create lookup table for `toString('hex')` -// See: https://github.com/feross/buffer/issues/219 -var hexSliceLookupTable = (function () { - var alphabet = '0123456789abcdef' - var table = new Array(256) - for (var i = 0; i < 16; ++i) { - var i16 = i * 16 - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j] - } - } - return table -})() diff --git a/reverse_engineering/node_modules/buffer/package.json b/reverse_engineering/node_modules/buffer/package.json deleted file mode 100644 index 3b1b498..0000000 --- a/reverse_engineering/node_modules/buffer/package.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "name": "buffer", - "description": "Node.js Buffer API, for the browser", - "version": "5.7.1", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "https://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/buffer/issues" - }, - "contributors": [ - "Romain Beauxis ", - "James Halliday " - ], - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - }, - "devDependencies": { - "airtap": "^3.0.0", - "benchmark": "^2.1.4", - "browserify": "^17.0.0", - "concat-stream": "^2.0.0", - "hyperquest": "^2.1.3", - "is-buffer": "^2.0.4", - "is-nan": "^1.3.0", - "split": "^1.0.1", - "standard": "*", - "tape": "^5.0.1", - "through2": "^4.0.2", - "uglify-js": "^3.11.3" - }, - "homepage": "https://github.com/feross/buffer", - "jspm": { - "map": { - "./index.js": { - "node": "@node/buffer" - } - } - }, - "keywords": [ - "arraybuffer", - "browser", - "browserify", - "buffer", - "compatible", - "dataview", - "uint8array" - ], - "license": "MIT", - "main": "index.js", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "git://github.com/feross/buffer.git" - }, - "scripts": { - "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", - "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", - "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", - "test": "standard && node ./bin/test.js", - "test-browser-es5": "airtap -- test/*.js", - "test-browser-es5-local": "airtap --local -- test/*.js", - "test-browser-es6": "airtap -- test/*.js test/node/*.js", - "test-browser-es6-local": "airtap --local -- test/*.js test/node/*.js", - "test-node": "tape test/*.js test/node/*.js", - "update-authors": "./bin/update-authors.sh" - }, - "standard": { - "ignore": [ - "test/node/**/*.js", - "test/common.js", - "test/_polyfill.js", - "perf/**/*.js" - ], - "globals": [ - "SharedArrayBuffer" - ] - }, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] -} diff --git a/reverse_engineering/node_modules/camelcase/index.d.ts b/reverse_engineering/node_modules/camelcase/index.d.ts deleted file mode 100644 index 58f2069..0000000 --- a/reverse_engineering/node_modules/camelcase/index.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -declare namespace camelcase { - interface Options { - /** - Uppercase the first character: `foo-bar` → `FooBar`. - - @default false - */ - readonly pascalCase?: boolean; - } -} - -declare const camelcase: { - /** - Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`. - - @param input - String to convert to camel case. - - @example - ``` - import camelCase = require('camelcase'); - - camelCase('foo-bar'); - //=> 'fooBar' - - camelCase('foo_bar'); - //=> 'fooBar' - - camelCase('Foo-Bar'); - //=> 'fooBar' - - camelCase('Foo-Bar', {pascalCase: true}); - //=> 'FooBar' - - camelCase('--foo.bar', {pascalCase: false}); - //=> 'fooBar' - - camelCase('foo bar'); - //=> 'fooBar' - - console.log(process.argv[3]); - //=> '--foo-bar' - camelCase(process.argv[3]); - //=> 'fooBar' - - camelCase(['foo', 'bar']); - //=> 'fooBar' - - camelCase(['__foo__', '--bar'], {pascalCase: true}); - //=> 'FooBar' - ``` - */ - (input: string | ReadonlyArray, options?: camelcase.Options): string; - - // TODO: Remove this for the next major release, refactor the whole definition to: - // declare function camelcase( - // input: string | ReadonlyArray, - // options?: camelcase.Options - // ): string; - // export = camelcase; - default: typeof camelcase; -}; - -export = camelcase; diff --git a/reverse_engineering/node_modules/camelcase/index.js b/reverse_engineering/node_modules/camelcase/index.js deleted file mode 100644 index 579f99b..0000000 --- a/reverse_engineering/node_modules/camelcase/index.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -const preserveCamelCase = string => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - - for (let i = 0; i < string.length; i++) { - const character = string[i]; - - if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { - string = string.slice(0, i) + '-' + string.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { - string = string.slice(0, i - 1) + '-' + string.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; - } - } - - return string; -}; - -const camelCase = (input, options) => { - if (!(typeof input === 'string' || Array.isArray(input))) { - throw new TypeError('Expected the input to be `string | string[]`'); - } - - options = Object.assign({ - pascalCase: false - }, options); - - const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; - - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - - if (input.length === 0) { - return ''; - } - - if (input.length === 1) { - return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); - } - - const hasUpperCase = input !== input.toLowerCase(); - - if (hasUpperCase) { - input = preserveCamelCase(input); - } - - input = input - .replace(/^[_.\- ]+/, '') - .toLowerCase() - .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) - .replace(/\d+(\w|$)/g, m => m.toUpperCase()); - - return postProcess(input); -}; - -module.exports = camelCase; -// TODO: Remove this for the next major release -module.exports.default = camelCase; diff --git a/reverse_engineering/node_modules/camelcase/license b/reverse_engineering/node_modules/camelcase/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/camelcase/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/camelcase/package.json b/reverse_engineering/node_modules/camelcase/package.json deleted file mode 100644 index fbdbaaa..0000000 --- a/reverse_engineering/node_modules/camelcase/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "camelcase", - "version": "5.3.1", - "description": "Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`", - "license": "MIT", - "repository": "sindresorhus/camelcase", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=6" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "camelcase", - "camel-case", - "camel", - "case", - "dash", - "hyphen", - "dot", - "underscore", - "separator", - "string", - "text", - "convert", - "pascalcase", - "pascal-case" - ], - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.1", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/camelcase/readme.md b/reverse_engineering/node_modules/camelcase/readme.md deleted file mode 100644 index fde2726..0000000 --- a/reverse_engineering/node_modules/camelcase/readme.md +++ /dev/null @@ -1,99 +0,0 @@ -# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase) - -> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar` - ---- - -
- - Get professional support for 'camelcase' with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
- ---- - -## Install - -``` -$ npm install camelcase -``` - - -## Usage - -```js -const camelCase = require('camelcase'); - -camelCase('foo-bar'); -//=> 'fooBar' - -camelCase('foo_bar'); -//=> 'fooBar' - -camelCase('Foo-Bar'); -//=> 'fooBar' - -camelCase('Foo-Bar', {pascalCase: true}); -//=> 'FooBar' - -camelCase('--foo.bar', {pascalCase: false}); -//=> 'fooBar' - -camelCase('foo bar'); -//=> 'fooBar' - -console.log(process.argv[3]); -//=> '--foo-bar' -camelCase(process.argv[3]); -//=> 'fooBar' - -camelCase(['foo', 'bar']); -//=> 'fooBar' - -camelCase(['__foo__', '--bar'], {pascalCase: true}); -//=> 'FooBar' -``` - - -## API - -### camelCase(input, [options]) - -#### input - -Type: `string` `string[]` - -String to convert to camel case. - -#### options - -Type: `Object` - -##### pascalCase - -Type: `boolean`
-Default: `false` - -Uppercase the first character: `foo-bar` → `FooBar` - - -## Security - -To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. - - -## Related - -- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module -- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase -- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string -- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/reverse_engineering/node_modules/cliui/CHANGELOG.md b/reverse_engineering/node_modules/cliui/CHANGELOG.md deleted file mode 100644 index 6a77f8f..0000000 --- a/reverse_engineering/node_modules/cliui/CHANGELOG.md +++ /dev/null @@ -1,76 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -## [6.0.0](https://www.github.com/yargs/cliui/compare/v5.0.0...v6.0.0) (2019-11-10) - - -### ⚠ BREAKING CHANGES - -* update deps, drop Node 6 - -### Code Refactoring - -* update deps, drop Node 6 ([62056df](https://www.github.com/yargs/cliui/commit/62056df)) - -## [5.0.0](https://github.com/yargs/cliui/compare/v4.1.0...v5.0.0) (2019-04-10) - - -### Bug Fixes - -* Update wrap-ansi to fix compatibility with latest versions of chalk. ([#60](https://github.com/yargs/cliui/issues/60)) ([7bf79ae](https://github.com/yargs/cliui/commit/7bf79ae)) - - -### BREAKING CHANGES - -* Drop support for node < 6. - - - - -## [4.1.0](https://github.com/yargs/cliui/compare/v4.0.0...v4.1.0) (2018-04-23) - - -### Features - -* add resetOutput method ([#57](https://github.com/yargs/cliui/issues/57)) ([7246902](https://github.com/yargs/cliui/commit/7246902)) - - - - -## [4.0.0](https://github.com/yargs/cliui/compare/v3.2.0...v4.0.0) (2017-12-18) - - -### Bug Fixes - -* downgrades strip-ansi to version 3.0.1 ([#54](https://github.com/yargs/cliui/issues/54)) ([5764c46](https://github.com/yargs/cliui/commit/5764c46)) -* set env variable FORCE_COLOR. ([#56](https://github.com/yargs/cliui/issues/56)) ([7350e36](https://github.com/yargs/cliui/commit/7350e36)) - - -### Chores - -* drop support for node < 4 ([#53](https://github.com/yargs/cliui/issues/53)) ([b105376](https://github.com/yargs/cliui/commit/b105376)) - - -### Features - -* add fallback for window width ([#45](https://github.com/yargs/cliui/issues/45)) ([d064922](https://github.com/yargs/cliui/commit/d064922)) - - -### BREAKING CHANGES - -* officially drop support for Node < 4 - - - - -## [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11) - - -### Bug Fixes - -* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33)) - -### Features - -* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32)) diff --git a/reverse_engineering/node_modules/cliui/LICENSE.txt b/reverse_engineering/node_modules/cliui/LICENSE.txt deleted file mode 100644 index c7e2747..0000000 --- a/reverse_engineering/node_modules/cliui/LICENSE.txt +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) 2015, Contributors - -Permission to use, copy, modify, and/or distribute this software -for any purpose with or without fee is hereby granted, provided -that the above copyright notice and this permission notice -appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE -LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/cliui/README.md b/reverse_engineering/node_modules/cliui/README.md deleted file mode 100644 index deacfa0..0000000 --- a/reverse_engineering/node_modules/cliui/README.md +++ /dev/null @@ -1,115 +0,0 @@ -# cliui - -[![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) -[![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) -[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) -[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) - -easily create complex multi-column command-line-interfaces. - -## Example - -```js -var ui = require('cliui')() - -ui.div('Usage: $0 [command] [options]') - -ui.div({ - text: 'Options:', - padding: [2, 0, 2, 0] -}) - -ui.div( - { - text: "-f, --file", - width: 20, - padding: [0, 4, 0, 4] - }, - { - text: "the file to load." + - chalk.green("(if this description is long it wraps).") - , - width: 20 - }, - { - text: chalk.red("[required]"), - align: 'right' - } -) - -console.log(ui.toString()) -``` - - - -## Layout DSL - -cliui exposes a simple layout DSL: - -If you create a single `ui.div`, passing a string rather than an -object: - -* `\n`: characters will be interpreted as new rows. -* `\t`: characters will be interpreted as new columns. -* `\s`: characters will be interpreted as padding. - -**as an example...** - -```js -var ui = require('./')({ - width: 60 -}) - -ui.div( - 'Usage: node ./bin/foo.js\n' + - ' \t provide a regex\n' + - ' \t provide a glob\t [required]' -) - -console.log(ui.toString()) -``` - -**will output:** - -```shell -Usage: node ./bin/foo.js - provide a regex - provide a glob [required] -``` - -## Methods - -```js -cliui = require('cliui') -``` - -### cliui({width: integer}) - -Specify the maximum width of the UI being generated. -If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. - -### cliui({wrap: boolean}) - -Enable or disable the wrapping of text in a column. - -### cliui.div(column, column, column) - -Create a row with any number of columns, a column -can either be a string, or an object with the following -options: - -* **text:** some text to place in the column. -* **width:** the width of a column. -* **align:** alignment, `right` or `center`. -* **padding:** `[top, right, bottom, left]`. -* **border:** should a border be placed around the div? - -### cliui.span(column, column, column) - -Similar to `div`, except the next row will be appended without -a new line being created. - -### cliui.resetOutput() - -Resets the UI elements of the current cliui instance, maintaining the values -set for `width` and `wrap`. diff --git a/reverse_engineering/node_modules/cliui/index.js b/reverse_engineering/node_modules/cliui/index.js deleted file mode 100644 index e917b00..0000000 --- a/reverse_engineering/node_modules/cliui/index.js +++ /dev/null @@ -1,354 +0,0 @@ -'use strict' - -const stringWidth = require('string-width') -const stripAnsi = require('strip-ansi') -const wrap = require('wrap-ansi') - -const align = { - right: alignRight, - center: alignCenter -} -const top = 0 -const right = 1 -const bottom = 2 -const left = 3 - -class UI { - constructor (opts) { - this.width = opts.width - this.wrap = opts.wrap - this.rows = [] - } - - span (...args) { - const cols = this.div(...args) - cols.span = true - } - - resetOutput () { - this.rows = [] - } - - div (...args) { - if (args.length === 0) { - this.div('') - } - - if (this.wrap && this._shouldApplyLayoutDSL(...args)) { - return this._applyLayoutDSL(args[0]) - } - - const cols = args.map(arg => { - if (typeof arg === 'string') { - return this._colFromString(arg) - } - - return arg - }) - - this.rows.push(cols) - return cols - } - - _shouldApplyLayoutDSL (...args) { - return args.length === 1 && typeof args[0] === 'string' && - /[\t\n]/.test(args[0]) - } - - _applyLayoutDSL (str) { - const rows = str.split('\n').map(row => row.split('\t')) - let leftColumnWidth = 0 - - // simple heuristic for layout, make sure the - // second column lines up along the left-hand. - // don't allow the first column to take up more - // than 50% of the screen. - rows.forEach(columns => { - if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) { - leftColumnWidth = Math.min( - Math.floor(this.width * 0.5), - stringWidth(columns[0]) - ) - } - }) - - // generate a table: - // replacing ' ' with padding calculations. - // using the algorithmically generated width. - rows.forEach(columns => { - this.div(...columns.map((r, i) => { - return { - text: r.trim(), - padding: this._measurePadding(r), - width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined - } - })) - }) - - return this.rows[this.rows.length - 1] - } - - _colFromString (text) { - return { - text, - padding: this._measurePadding(text) - } - } - - _measurePadding (str) { - // measure padding without ansi escape codes - const noAnsi = stripAnsi(str) - return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length] - } - - toString () { - const lines = [] - - this.rows.forEach(row => { - this.rowToString(row, lines) - }) - - // don't display any lines with the - // hidden flag set. - return lines - .filter(line => !line.hidden) - .map(line => line.text) - .join('\n') - } - - rowToString (row, lines) { - this._rasterize(row).forEach((rrow, r) => { - let str = '' - rrow.forEach((col, c) => { - const { width } = row[c] // the width with padding. - const wrapWidth = this._negatePadding(row[c]) // the width without padding. - - let ts = col // temporary string used during alignment/padding. - - if (wrapWidth > stringWidth(col)) { - ts += ' '.repeat(wrapWidth - stringWidth(col)) - } - - // align the string within its column. - if (row[c].align && row[c].align !== 'left' && this.wrap) { - ts = align[row[c].align](ts, wrapWidth) - if (stringWidth(ts) < wrapWidth) { - ts += ' '.repeat(width - stringWidth(ts) - 1) - } - } - - // apply border and padding to string. - const padding = row[c].padding || [0, 0, 0, 0] - if (padding[left]) { - str += ' '.repeat(padding[left]) - } - - str += addBorder(row[c], ts, '| ') - str += ts - str += addBorder(row[c], ts, ' |') - if (padding[right]) { - str += ' '.repeat(padding[right]) - } - - // if prior row is span, try to render the - // current row on the prior line. - if (r === 0 && lines.length > 0) { - str = this._renderInline(str, lines[lines.length - 1]) - } - }) - - // remove trailing whitespace. - lines.push({ - text: str.replace(/ +$/, ''), - span: row.span - }) - }) - - return lines - } - - // if the full 'source' can render in - // the target line, do so. - _renderInline (source, previousLine) { - const leadingWhitespace = source.match(/^ */)[0].length - const target = previousLine.text - const targetTextWidth = stringWidth(target.trimRight()) - - if (!previousLine.span) { - return source - } - - // if we're not applying wrapping logic, - // just always append to the span. - if (!this.wrap) { - previousLine.hidden = true - return target + source - } - - if (leadingWhitespace < targetTextWidth) { - return source - } - - previousLine.hidden = true - - return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft() - } - - _rasterize (row) { - const rrows = [] - const widths = this._columnWidths(row) - let wrapped - - // word wrap all columns, and create - // a data-structure that is easy to rasterize. - row.forEach((col, c) => { - // leave room for left and right padding. - col.width = widths[c] - if (this.wrap) { - wrapped = wrap(col.text, this._negatePadding(col), { hard: true }).split('\n') - } else { - wrapped = col.text.split('\n') - } - - if (col.border) { - wrapped.unshift('.' + '-'.repeat(this._negatePadding(col) + 2) + '.') - wrapped.push("'" + '-'.repeat(this._negatePadding(col) + 2) + "'") - } - - // add top and bottom padding. - if (col.padding) { - wrapped.unshift(...new Array(col.padding[top] || 0).fill('')) - wrapped.push(...new Array(col.padding[bottom] || 0).fill('')) - } - - wrapped.forEach((str, r) => { - if (!rrows[r]) { - rrows.push([]) - } - - const rrow = rrows[r] - - for (let i = 0; i < c; i++) { - if (rrow[i] === undefined) { - rrow.push('') - } - } - - rrow.push(str) - }) - }) - - return rrows - } - - _negatePadding (col) { - let wrapWidth = col.width - if (col.padding) { - wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0) - } - - if (col.border) { - wrapWidth -= 4 - } - - return wrapWidth - } - - _columnWidths (row) { - if (!this.wrap) { - return row.map(col => { - return col.width || stringWidth(col.text) - }) - } - - let unset = row.length - let remainingWidth = this.width - - // column widths can be set in config. - const widths = row.map(col => { - if (col.width) { - unset-- - remainingWidth -= col.width - return col.width - } - - return undefined - }) - - // any unset widths should be calculated. - const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0 - - return widths.map((w, i) => { - if (w === undefined) { - return Math.max(unsetWidth, _minWidth(row[i])) - } - - return w - }) - } -} - -function addBorder (col, ts, style) { - if (col.border) { - if (/[.']-+[.']/.test(ts)) { - return '' - } - - if (ts.trim().length !== 0) { - return style - } - - return ' ' - } - - return '' -} - -// calculates the minimum width of -// a column, based on padding preferences. -function _minWidth (col) { - const padding = col.padding || [] - const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0) - if (col.border) { - return minWidth + 4 - } - - return minWidth -} - -function getWindowWidth () { - /* istanbul ignore next: depends on terminal */ - if (typeof process === 'object' && process.stdout && process.stdout.columns) { - return process.stdout.columns - } -} - -function alignRight (str, width) { - str = str.trim() - const strWidth = stringWidth(str) - - if (strWidth < width) { - return ' '.repeat(width - strWidth) + str - } - - return str -} - -function alignCenter (str, width) { - str = str.trim() - const strWidth = stringWidth(str) - - /* istanbul ignore next */ - if (strWidth >= width) { - return str - } - - return ' '.repeat((width - strWidth) >> 1) + str -} - -module.exports = function (opts = {}) { - return new UI({ - width: opts.width || getWindowWidth() || /* istanbul ignore next */ 80, - wrap: opts.wrap !== false - }) -} diff --git a/reverse_engineering/node_modules/cliui/package.json b/reverse_engineering/node_modules/cliui/package.json deleted file mode 100644 index f92fd10..0000000 --- a/reverse_engineering/node_modules/cliui/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "cliui", - "version": "6.0.0", - "description": "easily create complex multi-column command-line-interfaces", - "main": "index.js", - "scripts": { - "pretest": "standard", - "test": "nyc mocha", - "coverage": "nyc --reporter=text-lcov mocha | coveralls" - }, - "repository": { - "type": "git", - "url": "http://github.com/yargs/cliui.git" - }, - "config": { - "blanket": { - "pattern": [ - "index.js" - ], - "data-cover-never": [ - "node_modules", - "test" - ], - "output-reporter": "spec" - } - }, - "standard": { - "ignore": [ - "**/example/**" - ], - "globals": [ - "it" - ] - }, - "keywords": [ - "cli", - "command-line", - "layout", - "design", - "console", - "wrap", - "table" - ], - "author": "Ben Coe ", - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^6.2.0" - }, - "devDependencies": { - "chai": "^4.2.0", - "chalk": "^3.0.0", - "coveralls": "^3.0.3", - "mocha": "^6.2.2", - "nyc": "^14.1.1", - "standard": "^12.0.1" - }, - "files": [ - "index.js" - ], - "engine": { - "node": ">=8" - } -} diff --git a/reverse_engineering/node_modules/color-convert/CHANGELOG.md b/reverse_engineering/node_modules/color-convert/CHANGELOG.md deleted file mode 100644 index 0a7bce4..0000000 --- a/reverse_engineering/node_modules/color-convert/CHANGELOG.md +++ /dev/null @@ -1,54 +0,0 @@ -# 1.0.0 - 2016-01-07 - -- Removed: unused speed test -- Added: Automatic routing between previously unsupported conversions -([#27](https://github.com/Qix-/color-convert/pull/27)) -- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions -([#27](https://github.com/Qix-/color-convert/pull/27)) -- Removed: `convert()` class -([#27](https://github.com/Qix-/color-convert/pull/27)) -- Changed: all functions to lookup dictionary -([#27](https://github.com/Qix-/color-convert/pull/27)) -- Changed: `ansi` to `ansi256` -([#27](https://github.com/Qix-/color-convert/pull/27)) -- Fixed: argument grouping for functions requiring only one argument -([#27](https://github.com/Qix-/color-convert/pull/27)) - -# 0.6.0 - 2015-07-23 - -- Added: methods to handle -[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: - - rgb2ansi16 - - rgb2ansi - - hsl2ansi16 - - hsl2ansi - - hsv2ansi16 - - hsv2ansi - - hwb2ansi16 - - hwb2ansi - - cmyk2ansi16 - - cmyk2ansi - - keyword2ansi16 - - keyword2ansi - - ansi162rgb - - ansi162hsl - - ansi162hsv - - ansi162hwb - - ansi162cmyk - - ansi162keyword - - ansi2rgb - - ansi2hsl - - ansi2hsv - - ansi2hwb - - ansi2cmyk - - ansi2keyword -([#18](https://github.com/harthur/color-convert/pull/18)) - -# 0.5.3 - 2015-06-02 - -- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` -([#15](https://github.com/harthur/color-convert/issues/15)) - ---- - -Check out commit logs for older releases diff --git a/reverse_engineering/node_modules/color-convert/LICENSE b/reverse_engineering/node_modules/color-convert/LICENSE deleted file mode 100644 index 5b4c386..0000000 --- a/reverse_engineering/node_modules/color-convert/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2011-2016 Heather Arthur - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/reverse_engineering/node_modules/color-convert/README.md b/reverse_engineering/node_modules/color-convert/README.md deleted file mode 100644 index d4b08fc..0000000 --- a/reverse_engineering/node_modules/color-convert/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# color-convert - -[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) - -Color-convert is a color conversion library for JavaScript and node. -It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): - -```js -var convert = require('color-convert'); - -convert.rgb.hsl(140, 200, 100); // [96, 48, 59] -convert.keyword.rgb('blue'); // [0, 0, 255] - -var rgbChannels = convert.rgb.channels; // 3 -var cmykChannels = convert.cmyk.channels; // 4 -var ansiChannels = convert.ansi16.channels; // 1 -``` - -# Install - -```console -$ npm install color-convert -``` - -# API - -Simply get the property of the _from_ and _to_ conversion that you're looking for. - -All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. - -All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). - -```js -var convert = require('color-convert'); - -// Hex to LAB -convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] -convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] - -// RGB to CMYK -convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] -convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] -``` - -### Arrays -All functions that accept multiple arguments also support passing an array. - -Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) - -```js -var convert = require('color-convert'); - -convert.rgb.hex(123, 45, 67); // '7B2D43' -convert.rgb.hex([123, 45, 67]); // '7B2D43' -``` - -## Routing - -Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). - -Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). - -# Contribute - -If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. - -# License -Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). diff --git a/reverse_engineering/node_modules/color-convert/conversions.js b/reverse_engineering/node_modules/color-convert/conversions.js deleted file mode 100644 index 2657f26..0000000 --- a/reverse_engineering/node_modules/color-convert/conversions.js +++ /dev/null @@ -1,839 +0,0 @@ -/* MIT license */ -/* eslint-disable no-mixed-operators */ -const cssKeywords = require('color-name'); - -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -const reverseKeywords = {}; -for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; -} - -const convert = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -module.exports = convert; - -// Hide .channels and .labels properties -for (const model of Object.keys(convert)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - const {channels, labels} = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); -} - -convert.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - const l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; -}; - -convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; - - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } - - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; -}; - -convert.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; -}; - -convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - - return [c * 100, m * 100, y * 100, k * 100]; -}; - -function comparativeDistance(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); -} - -convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - - let currentClosestDistance = Infinity; - let currentClosestKeyword; - - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; - - // Compute comparative distance - const distance = comparativeDistance(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - - return currentClosestKeyword; -}; - -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; -}; - -convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; - - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); - - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - - return [x * 100, y * 100, z * 100]; -}; - -convert.rgb.lab = function (rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; -}; - -convert.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - const t1 = 2 * l - t2; - - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; -}; - -convert.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; -}; - -convert.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; - -convert.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; -}; - -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert.hwb.rgb = function (hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - - // Wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - const n = wh + f * (v - wh); // Linear interpolation - - let r; - let g; - let b; - /* eslint-disable max-statements-per-line,no-multi-spaces */ - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - /* eslint-enable max-statements-per-line,no-multi-spaces */ - - return [r * 255, g * 255, b * 255]; -}; - -convert.cmyk.rgb = function (cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; - - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); - - return [r * 255, g * 255, b * 255]; -}; - -convert.xyz.rgb = function (xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; - - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; - - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; - - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; - - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - - return [r * 255, g * 255, b * 255]; -}; - -convert.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; -}; - -convert.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; - - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - - x *= 95.047; - y *= 100; - z *= 108.883; - - return [x, y, z]; -}; - -convert.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - const c = Math.sqrt(a * a + b * b); - - return [l, c, h]; -}; - -convert.lch.lab = function (lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; - - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - - return [l, a, b]; -}; - -convert.rgb.ansi16 = function (args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; -}; - -convert.hsv.ansi16 = function (args) { - // Optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); -}; - -convert.rgb.ansi256 = function (args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; - - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round(((r - 8) / 247) * 24) + 232; - } - - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); - - return ansi; -}; - -convert.ansi16.rgb = function (args) { - let color = args % 10; - - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - - return [color, color, color]; - } - - const mult = (~~(args > 50) + 1) * 0.5; - const r = ((color & 1) * mult) * 255; - const g = (((color >> 1) & 1) * mult) * 255; - const b = (((color >> 2) & 1) * mult) * 255; - - return [r, g, b]; -}; - -convert.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = (rem % 6) / 5 * 255; - - return [r, g, b]; -}; - -convert.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert.hex.rgb = function (args) { - const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } - - let colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } - - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; - - return [r, g, b]; -}; - -convert.rgb.hcg = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = (max - min); - let grayscale; - let hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } - - hue /= 6; - hue %= 1; - - return [hue * 360, chroma * 100, grayscale * 100]; -}; - -convert.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; - - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; -}; - -convert.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - - const c = s * v; - let f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; -}; - -convert.hcg.rgb = function (hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - - /* eslint-disable max-statements-per-line */ - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - /* eslint-enable max-statements-per-line */ - - mg = (1.0 - c) * g; - - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; - -convert.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const v = c + g * (1.0 - c); - let f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; -}; - -convert.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; -}; - -convert.hcg.hwb = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; - -convert.hwb.hcg = function (hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; -}; - -convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; - -convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; - -convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; - -convert.gray.hsl = function (args) { - return [0, 0, args[0]]; -}; - -convert.gray.hsv = convert.gray.hsl; - -convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; - -convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; - -convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; - -convert.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; diff --git a/reverse_engineering/node_modules/color-convert/index.js b/reverse_engineering/node_modules/color-convert/index.js deleted file mode 100644 index b648e57..0000000 --- a/reverse_engineering/node_modules/color-convert/index.js +++ /dev/null @@ -1,81 +0,0 @@ -const conversions = require('./conversions'); -const route = require('./route'); - -const convert = {}; - -const models = Object.keys(conversions); - -function wrapRaw(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - return fn(args); - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - const result = fn(args); - - // We're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -models.forEach(fromModel => { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - const routes = route(fromModel); - const routeModels = Object.keys(routes); - - routeModels.forEach(toModel => { - const fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); - -module.exports = convert; diff --git a/reverse_engineering/node_modules/color-convert/package.json b/reverse_engineering/node_modules/color-convert/package.json deleted file mode 100644 index 6e48000..0000000 --- a/reverse_engineering/node_modules/color-convert/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "color-convert", - "description": "Plain color conversion functions", - "version": "2.0.1", - "author": "Heather Arthur ", - "license": "MIT", - "repository": "Qix-/color-convert", - "scripts": { - "pretest": "xo", - "test": "node test/basic.js" - }, - "engines": { - "node": ">=7.0.0" - }, - "keywords": [ - "color", - "colour", - "convert", - "converter", - "conversion", - "rgb", - "hsl", - "hsv", - "hwb", - "cmyk", - "ansi", - "ansi16" - ], - "files": [ - "index.js", - "conversions.js", - "route.js" - ], - "xo": { - "rules": { - "default-case": 0, - "no-inline-comments": 0, - "operator-linebreak": 0 - } - }, - "devDependencies": { - "chalk": "^2.4.2", - "xo": "^0.24.0" - }, - "dependencies": { - "color-name": "~1.1.4" - } -} diff --git a/reverse_engineering/node_modules/color-convert/route.js b/reverse_engineering/node_modules/color-convert/route.js deleted file mode 100644 index 1a08521..0000000 --- a/reverse_engineering/node_modules/color-convert/route.js +++ /dev/null @@ -1,97 +0,0 @@ -const conversions = require('./conversions'); - -/* - This function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. -*/ - -function buildGraph() { - const graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - const models = Object.keys(conversions); - - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; -} - -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; // Unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); - - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; -} - -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} - -function wrapConversion(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions[graph[toModel].parent][toModel]; - - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -module.exports = function (fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; - - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node = graph[toModel]; - - if (node.parent === null) { - // No possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } - - return conversion; -}; - diff --git a/reverse_engineering/node_modules/color-name/LICENSE b/reverse_engineering/node_modules/color-name/LICENSE deleted file mode 100644 index c6b1001..0000000 --- a/reverse_engineering/node_modules/color-name/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -The MIT License (MIT) -Copyright (c) 2015 Dmitry Ivanov - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/color-name/README.md b/reverse_engineering/node_modules/color-name/README.md deleted file mode 100644 index 932b979..0000000 --- a/reverse_engineering/node_modules/color-name/README.md +++ /dev/null @@ -1,11 +0,0 @@ -A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. - -[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) - - -```js -var colors = require('color-name'); -colors.red //[255,0,0] -``` - - diff --git a/reverse_engineering/node_modules/color-name/index.js b/reverse_engineering/node_modules/color-name/index.js deleted file mode 100644 index b7c198a..0000000 --- a/reverse_engineering/node_modules/color-name/index.js +++ /dev/null @@ -1,152 +0,0 @@ -'use strict' - -module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; diff --git a/reverse_engineering/node_modules/color-name/package.json b/reverse_engineering/node_modules/color-name/package.json deleted file mode 100644 index 782dd82..0000000 --- a/reverse_engineering/node_modules/color-name/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "color-name", - "version": "1.1.4", - "description": "A list of color names and its values", - "main": "index.js", - "files": [ - "index.js" - ], - "scripts": { - "test": "node test.js" - }, - "repository": { - "type": "git", - "url": "git@github.com:colorjs/color-name.git" - }, - "keywords": [ - "color-name", - "color", - "color-keyword", - "keyword" - ], - "author": "DY ", - "license": "MIT", - "bugs": { - "url": "https://github.com/colorjs/color-name/issues" - }, - "homepage": "https://github.com/colorjs/color-name" -} diff --git a/reverse_engineering/node_modules/core-util-is/LICENSE b/reverse_engineering/node_modules/core-util-is/LICENSE deleted file mode 100644 index d8d7f94..0000000 --- a/reverse_engineering/node_modules/core-util-is/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Node.js contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/core-util-is/README.md b/reverse_engineering/node_modules/core-util-is/README.md deleted file mode 100644 index 5a76b41..0000000 --- a/reverse_engineering/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/reverse_engineering/node_modules/core-util-is/lib/util.js b/reverse_engineering/node_modules/core-util-is/lib/util.js deleted file mode 100644 index 6e5a20d..0000000 --- a/reverse_engineering/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('buffer').Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} diff --git a/reverse_engineering/node_modules/core-util-is/package.json b/reverse_engineering/node_modules/core-util-is/package.json deleted file mode 100644 index b0c51f5..0000000 --- a/reverse_engineering/node_modules/core-util-is/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "core-util-is", - "version": "1.0.3", - "description": "The `util.is*` functions introduced in Node v0.12.", - "main": "lib/util.js", - "files": [ - "lib" - ], - "repository": { - "type": "git", - "url": "git://github.com/isaacs/core-util-is" - }, - "keywords": [ - "util", - "isBuffer", - "isArray", - "isNumber", - "isString", - "isRegExp", - "isThis", - "isThat", - "polyfill" - ], - "author": "Isaac Z. Schlueter (http://blog.izs.me/)", - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/core-util-is/issues" - }, - "scripts": { - "test": "tap test.js", - "preversion": "npm test", - "postversion": "npm publish", - "prepublishOnly": "git push origin --follow-tags" - }, - "devDependencies": { - "tap": "^15.0.9" - } -} diff --git a/reverse_engineering/node_modules/debug/.coveralls.yml b/reverse_engineering/node_modules/debug/.coveralls.yml deleted file mode 100644 index 20a7068..0000000 --- a/reverse_engineering/node_modules/debug/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/reverse_engineering/node_modules/debug/.eslintrc b/reverse_engineering/node_modules/debug/.eslintrc deleted file mode 100644 index 8a37ae2..0000000 --- a/reverse_engineering/node_modules/debug/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "env": { - "browser": true, - "node": true - }, - "rules": { - "no-console": 0, - "no-empty": [1, { "allowEmptyCatch": true }] - }, - "extends": "eslint:recommended" -} diff --git a/reverse_engineering/node_modules/debug/.npmignore b/reverse_engineering/node_modules/debug/.npmignore deleted file mode 100644 index 5f60eec..0000000 --- a/reverse_engineering/node_modules/debug/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -support -test -examples -example -*.sock -dist -yarn.lock -coverage -bower.json diff --git a/reverse_engineering/node_modules/debug/.travis.yml b/reverse_engineering/node_modules/debug/.travis.yml deleted file mode 100644 index 6c6090c..0000000 --- a/reverse_engineering/node_modules/debug/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ - -language: node_js -node_js: - - "6" - - "5" - - "4" - -install: - - make node_modules - -script: - - make lint - - make test - - make coveralls diff --git a/reverse_engineering/node_modules/debug/CHANGELOG.md b/reverse_engineering/node_modules/debug/CHANGELOG.md deleted file mode 100644 index eadaa18..0000000 --- a/reverse_engineering/node_modules/debug/CHANGELOG.md +++ /dev/null @@ -1,362 +0,0 @@ - -2.6.9 / 2017-09-22 -================== - - * remove ReDoS regexp in %o formatter (#504) - -2.6.8 / 2017-05-18 -================== - - * Fix: Check for undefined on browser globals (#462, @marbemac) - -2.6.7 / 2017-05-16 -================== - - * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) - * Fix: Inline extend function in node implementation (#452, @dougwilson) - * Docs: Fix typo (#455, @msasad) - -2.6.5 / 2017-04-27 -================== - - * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) - * Misc: clean up browser reference checks (#447, @thebigredgeek) - * Misc: add npm-debug.log to .gitignore (@thebigredgeek) - - -2.6.4 / 2017-04-20 -================== - - * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) - * Chore: ignore bower.json in npm installations. (#437, @joaovieira) - * Misc: update "ms" to v0.7.3 (@tootallnate) - -2.6.3 / 2017-03-13 -================== - - * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) - * Docs: Changelog fix (@thebigredgeek) - -2.6.2 / 2017-03-10 -================== - - * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) - * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) - * Docs: Add Slackin invite badge (@tootallnate) - -2.6.1 / 2017-02-10 -================== - - * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error - * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) - * Fix: IE8 "Expected identifier" error (#414, @vgoma) - * Fix: Namespaces would not disable once enabled (#409, @musikov) - -2.6.0 / 2016-12-28 -================== - - * Fix: added better null pointer checks for browser useColors (@thebigredgeek) - * Improvement: removed explicit `window.debug` export (#404, @tootallnate) - * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) - -2.5.2 / 2016-12-25 -================== - - * Fix: reference error on window within webworkers (#393, @KlausTrainer) - * Docs: fixed README typo (#391, @lurch) - * Docs: added notice about v3 api discussion (@thebigredgeek) - -2.5.1 / 2016-12-20 -================== - - * Fix: babel-core compatibility - -2.5.0 / 2016-12-20 -================== - - * Fix: wrong reference in bower file (@thebigredgeek) - * Fix: webworker compatibility (@thebigredgeek) - * Fix: output formatting issue (#388, @kribblo) - * Fix: babel-loader compatibility (#383, @escwald) - * Misc: removed built asset from repo and publications (@thebigredgeek) - * Misc: moved source files to /src (#378, @yamikuronue) - * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) - * Test: coveralls integration (#378, @yamikuronue) - * Docs: simplified language in the opening paragraph (#373, @yamikuronue) - -2.4.5 / 2016-12-17 -================== - - * Fix: `navigator` undefined in Rhino (#376, @jochenberger) - * Fix: custom log function (#379, @hsiliev) - * Improvement: bit of cleanup + linting fixes (@thebigredgeek) - * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) - * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) - -2.4.4 / 2016-12-14 -================== - - * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) - -2.4.3 / 2016-12-14 -================== - - * Fix: navigation.userAgent error for react native (#364, @escwald) - -2.4.2 / 2016-12-14 -================== - - * Fix: browser colors (#367, @tootallnate) - * Misc: travis ci integration (@thebigredgeek) - * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) - -2.4.1 / 2016-12-13 -================== - - * Fix: typo that broke the package (#356) - -2.4.0 / 2016-12-13 -================== - - * Fix: bower.json references unbuilt src entry point (#342, @justmatt) - * Fix: revert "handle regex special characters" (@tootallnate) - * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) - * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) - * Improvement: allow colors in workers (#335, @botverse) - * Improvement: use same color for same namespace. (#338, @lchenay) - -2.3.3 / 2016-11-09 -================== - - * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) - * Fix: Returning `localStorage` saved values (#331, Levi Thomason) - * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) - -2.3.2 / 2016-11-09 -================== - - * Fix: be super-safe in index.js as well (@TooTallNate) - * Fix: should check whether process exists (Tom Newby) - -2.3.1 / 2016-11-09 -================== - - * Fix: Added electron compatibility (#324, @paulcbetts) - * Improvement: Added performance optimizations (@tootallnate) - * Readme: Corrected PowerShell environment variable example (#252, @gimre) - * Misc: Removed yarn lock file from source control (#321, @fengmk2) - -2.3.0 / 2016-11-07 -================== - - * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) - * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) - * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) - * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) - * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) - * Package: Update "ms" to 0.7.2 (#315, @DevSide) - * Package: removed superfluous version property from bower.json (#207 @kkirsche) - * Readme: fix USE_COLORS to DEBUG_COLORS - * Readme: Doc fixes for format string sugar (#269, @mlucool) - * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) - * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) - * Readme: better docs for browser support (#224, @matthewmueller) - * Tooling: Added yarn integration for development (#317, @thebigredgeek) - * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) - * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) - * Misc: Updated contributors (@thebigredgeek) - -2.2.0 / 2015-05-09 -================== - - * package: update "ms" to v0.7.1 (#202, @dougwilson) - * README: add logging to file example (#193, @DanielOchoa) - * README: fixed a typo (#191, @amir-s) - * browser: expose `storage` (#190, @stephenmathieson) - * Makefile: add a `distclean` target (#189, @stephenmathieson) - -2.1.3 / 2015-03-13 -================== - - * Updated stdout/stderr example (#186) - * Updated example/stdout.js to match debug current behaviour - * Renamed example/stderr.js to stdout.js - * Update Readme.md (#184) - * replace high intensity foreground color for bold (#182, #183) - -2.1.2 / 2015-03-01 -================== - - * dist: recompile - * update "ms" to v0.7.0 - * package: update "browserify" to v9.0.3 - * component: fix "ms.js" repo location - * changed bower package name - * updated documentation about using debug in a browser - * fix: security error on safari (#167, #168, @yields) - -2.1.1 / 2014-12-29 -================== - - * browser: use `typeof` to check for `console` existence - * browser: check for `console.log` truthiness (fix IE 8/9) - * browser: add support for Chrome apps - * Readme: added Windows usage remarks - * Add `bower.json` to properly support bower install - -2.1.0 / 2014-10-15 -================== - - * node: implement `DEBUG_FD` env variable support - * package: update "browserify" to v6.1.0 - * package: add "license" field to package.json (#135, @panuhorsmalahti) - -2.0.0 / 2014-09-01 -================== - - * package: update "browserify" to v5.11.0 - * node: use stderr rather than stdout for logging (#29, @stephenmathieson) - -1.0.4 / 2014-07-15 -================== - - * dist: recompile - * example: remove `console.info()` log usage - * example: add "Content-Type" UTF-8 header to browser example - * browser: place %c marker after the space character - * browser: reset the "content" color via `color: inherit` - * browser: add colors support for Firefox >= v31 - * debug: prefer an instance `log()` function over the global one (#119) - * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) - -1.0.3 / 2014-07-09 -================== - - * Add support for multiple wildcards in namespaces (#122, @seegno) - * browser: fix lint - -1.0.2 / 2014-06-10 -================== - - * browser: update color palette (#113, @gscottolson) - * common: make console logging function configurable (#108, @timoxley) - * node: fix %o colors on old node <= 0.8.x - * Makefile: find node path using shell/which (#109, @timoxley) - -1.0.1 / 2014-06-06 -================== - - * browser: use `removeItem()` to clear localStorage - * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) - * package: add "contributors" section - * node: fix comment typo - * README: list authors - -1.0.0 / 2014-06-04 -================== - - * make ms diff be global, not be scope - * debug: ignore empty strings in enable() - * node: make DEBUG_COLORS able to disable coloring - * *: export the `colors` array - * npmignore: don't publish the `dist` dir - * Makefile: refactor to use browserify - * package: add "browserify" as a dev dependency - * Readme: add Web Inspector Colors section - * node: reset terminal color for the debug content - * node: map "%o" to `util.inspect()` - * browser: map "%j" to `JSON.stringify()` - * debug: add custom "formatters" - * debug: use "ms" module for humanizing the diff - * Readme: add "bash" syntax highlighting - * browser: add Firebug color support - * browser: add colors for WebKit browsers - * node: apply log to `console` - * rewrite: abstract common logic for Node & browsers - * add .jshintrc file - -0.8.1 / 2014-04-14 -================== - - * package: re-add the "component" section - -0.8.0 / 2014-03-30 -================== - - * add `enable()` method for nodejs. Closes #27 - * change from stderr to stdout - * remove unnecessary index.js file - -0.7.4 / 2013-11-13 -================== - - * remove "browserify" key from package.json (fixes something in browserify) - -0.7.3 / 2013-10-30 -================== - - * fix: catch localStorage security error when cookies are blocked (Chrome) - * add debug(err) support. Closes #46 - * add .browser prop to package.json. Closes #42 - -0.7.2 / 2013-02-06 -================== - - * fix package.json - * fix: Mobile Safari (private mode) is broken with debug - * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript - -0.7.1 / 2013-02-05 -================== - - * add repository URL to package.json - * add DEBUG_COLORED to force colored output - * add browserify support - * fix component. Closes #24 - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/reverse_engineering/node_modules/debug/LICENSE b/reverse_engineering/node_modules/debug/LICENSE deleted file mode 100644 index 658c933..0000000 --- a/reverse_engineering/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software -and associated documentation files (the 'Software'), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial -portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/reverse_engineering/node_modules/debug/Makefile b/reverse_engineering/node_modules/debug/Makefile deleted file mode 100644 index 584da8b..0000000 --- a/reverse_engineering/node_modules/debug/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 -THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) -THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) - -# BIN directory -BIN := $(THIS_DIR)/node_modules/.bin - -# Path -PATH := node_modules/.bin:$(PATH) -SHELL := /bin/bash - -# applications -NODE ?= $(shell which node) -YARN ?= $(shell which yarn) -PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) -BROWSERIFY ?= $(NODE) $(BIN)/browserify - -.FORCE: - -install: node_modules - -node_modules: package.json - @NODE_ENV= $(PKG) install - @touch node_modules - -lint: .FORCE - eslint browser.js debug.js index.js node.js - -test-node: .FORCE - istanbul cover node_modules/mocha/bin/_mocha -- test/**.js - -test-browser: .FORCE - mkdir -p dist - - @$(BROWSERIFY) \ - --standalone debug \ - . > dist/debug.js - - karma start --single-run - rimraf dist - -test: .FORCE - concurrently \ - "make test-node" \ - "make test-browser" - -coveralls: - cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js - -.PHONY: all install clean distclean diff --git a/reverse_engineering/node_modules/debug/README.md b/reverse_engineering/node_modules/debug/README.md deleted file mode 100644 index f67be6b..0000000 --- a/reverse_engineering/node_modules/debug/README.md +++ /dev/null @@ -1,312 +0,0 @@ -# debug -[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) -[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) - - - -A tiny node.js debugging utility modelled after node core's debugging technique. - -**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** - -## Installation - -```bash -$ npm install debug -``` - -## Usage - -`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -#### Windows note - - On Windows the environment variable is set using the `set` command. - - ```cmd - set DEBUG=*,-not_this - ``` - - Note that PowerShell uses different syntax to set environment variables. - - ```cmd - $env:DEBUG = "*,-not_this" - ``` - -Then, run the program to be debugged as usual. - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". - -## Environment Variables - - When running through Node.js, you can set a few environment variables that will - change the behavior of the debug logging: - -| Name | Purpose | -|-----------|-------------------------------------------------| -| `DEBUG` | Enables/disables specific debugging namespaces. | -| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | -| `DEBUG_DEPTH` | Object inspection depth. | -| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | - - - __Note:__ The environment variables beginning with `DEBUG_` end up being - converted into an Options object that gets used with `%o`/`%O` formatters. - See the Node.js documentation for - [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) - for the complete list. - -## Formatters - - - Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: - -| Formatter | Representation | -|-----------|----------------| -| `%O` | Pretty-print an Object on multiple lines. | -| `%o` | Pretty-print an Object all on a single line. | -| `%s` | String. | -| `%d` | Number (both integer and float). | -| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | -| `%%` | Single percent sign ('%'). This does not consume an argument. | - -### Custom formatters - - You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: - -```js -const createDebug = require('debug') -createDebug.formatters.h = (v) => { - return v.toString('hex') -} - -// …elsewhere -const debug = createDebug('foo') -debug('this is hex: %h', new Buffer('hello world')) -// foo this is hex: 68656c6c6f20776f726c6421 +0ms -``` - -## Browser support - You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), - or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), - if you don't want to build it yourself. - - Debug's enable state is currently persisted by `localStorage`. - Consider the situation shown below where you have `worker:a` and `worker:b`, - and wish to debug both. You can enable this using `localStorage.debug`: - -```js -localStorage.debug = 'worker:*' -``` - -And then refresh the page. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - b('doing some work'); -}, 1200); -``` - -#### Web Inspector Colors - - Colors are also enabled on "Web Inspectors" that understand the `%c` formatting - option. These are WebKit web inspectors, Firefox ([since version - 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) - and the Firebug plugin for Firefox (any version). - - Colored output looks something like: - - ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) - - -## Output streams - - By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: - -Example _stdout.js_: - -```js -var debug = require('debug'); -var error = debug('app:error'); - -// by default stderr is used -error('goes to stderr!'); - -var log = debug('app:log'); -// set this namespace to log via console.log -log.log = console.log.bind(console); // don't forget to bind to console! -log('goes to stdout'); -error('still goes to stderr!'); - -// set all output to go via console.info -// overrides all per-namespace log settings -debug.log = console.info.bind(console); -error('now goes to stdout via console.info'); -log('still goes to stdout, but via console.info now'); -``` - - -## Authors - - - TJ Holowaychuk - - Nathan Rajlich - - Andrew Rhyne - -## Backers - -Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Sponsors - -Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## License - -(The MIT License) - -Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/debug/component.json b/reverse_engineering/node_modules/debug/component.json deleted file mode 100644 index 9de2641..0000000 --- a/reverse_engineering/node_modules/debug/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "debug", - "repo": "visionmedia/debug", - "description": "small debugging utility", - "version": "2.6.9", - "keywords": [ - "debug", - "log", - "debugger" - ], - "main": "src/browser.js", - "scripts": [ - "src/browser.js", - "src/debug.js" - ], - "dependencies": { - "rauchg/ms.js": "0.7.1" - } -} diff --git a/reverse_engineering/node_modules/debug/karma.conf.js b/reverse_engineering/node_modules/debug/karma.conf.js deleted file mode 100644 index 103a82d..0000000 --- a/reverse_engineering/node_modules/debug/karma.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// Karma configuration -// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) - -module.exports = function(config) { - config.set({ - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['mocha', 'chai', 'sinon'], - - - // list of files / patterns to load in the browser - files: [ - 'dist/debug.js', - 'test/*spec.js' - ], - - - // list of files to exclude - exclude: [ - 'src/node.js' - ], - - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - }, - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress'], - - - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: true, - - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['PhantomJS'], - - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false, - - // Concurrency level - // how many browser should be started simultaneous - concurrency: Infinity - }) -} diff --git a/reverse_engineering/node_modules/debug/node.js b/reverse_engineering/node_modules/debug/node.js deleted file mode 100644 index 7fc36fe..0000000 --- a/reverse_engineering/node_modules/debug/node.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./src/node'); diff --git a/reverse_engineering/node_modules/debug/package.json b/reverse_engineering/node_modules/debug/package.json deleted file mode 100644 index dc787ba..0000000 --- a/reverse_engineering/node_modules/debug/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "debug", - "version": "2.6.9", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": "TJ Holowaychuk ", - "contributors": [ - "Nathan Rajlich (http://n8.io)", - "Andrew Rhyne " - ], - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - }, - "devDependencies": { - "browserify": "9.0.3", - "chai": "^3.5.0", - "concurrently": "^3.1.0", - "coveralls": "^2.11.15", - "eslint": "^3.12.1", - "istanbul": "^0.4.5", - "karma": "^1.3.0", - "karma-chai": "^0.1.0", - "karma-mocha": "^1.3.0", - "karma-phantomjs-launcher": "^1.0.2", - "karma-sinon": "^1.0.5", - "mocha": "^3.2.0", - "mocha-lcov-reporter": "^1.2.0", - "rimraf": "^2.5.4", - "sinon": "^1.17.6", - "sinon-chai": "^2.8.0" - }, - "main": "./src/index.js", - "browser": "./src/browser.js", - "component": { - "scripts": { - "debug/index.js": "browser.js", - "debug/debug.js": "debug.js" - } - } -} diff --git a/reverse_engineering/node_modules/debug/src/browser.js b/reverse_engineering/node_modules/debug/src/browser.js deleted file mode 100644 index 7106924..0000000 --- a/reverse_engineering/node_modules/debug/src/browser.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} diff --git a/reverse_engineering/node_modules/debug/src/debug.js b/reverse_engineering/node_modules/debug/src/debug.js deleted file mode 100644 index 6a5e3fc..0000000 --- a/reverse_engineering/node_modules/debug/src/debug.js +++ /dev/null @@ -1,202 +0,0 @@ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} diff --git a/reverse_engineering/node_modules/debug/src/index.js b/reverse_engineering/node_modules/debug/src/index.js deleted file mode 100644 index e12cf4d..0000000 --- a/reverse_engineering/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ - -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = require('./browser.js'); -} else { - module.exports = require('./node.js'); -} diff --git a/reverse_engineering/node_modules/debug/src/inspector-log.js b/reverse_engineering/node_modules/debug/src/inspector-log.js deleted file mode 100644 index 60ea6c0..0000000 --- a/reverse_engineering/node_modules/debug/src/inspector-log.js +++ /dev/null @@ -1,15 +0,0 @@ -module.exports = inspectorLog; - -// black hole -const nullStream = new (require('stream').Writable)(); -nullStream._write = () => {}; - -/** - * Outputs a `console.log()` to the Node.js Inspector console *only*. - */ -function inspectorLog() { - const stdout = console._stdout; - console._stdout = nullStream; - console.log.apply(console, arguments); - console._stdout = stdout; -} diff --git a/reverse_engineering/node_modules/debug/src/node.js b/reverse_engineering/node_modules/debug/src/node.js deleted file mode 100644 index b15109c..0000000 --- a/reverse_engineering/node_modules/debug/src/node.js +++ /dev/null @@ -1,248 +0,0 @@ -/** - * Module dependencies. - */ - -var tty = require('tty'); -var util = require('util'); - -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); - -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ - -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} - -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; - -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ - -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ - -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ - -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - case 'FILE': - var fs = require('fs'); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - - case 'PIPE': - case 'TCP': - var net = require('net'); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - - // For supporting legacy API we put the FD here. - stream.fd = fd; - - stream._isStdio = true; - - return stream; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); diff --git a/reverse_engineering/node_modules/decamelize/index.js b/reverse_engineering/node_modules/decamelize/index.js deleted file mode 100644 index 8d5bab7..0000000 --- a/reverse_engineering/node_modules/decamelize/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; -module.exports = function (str, sep) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - sep = typeof sep === 'undefined' ? '_' : sep; - - return str - .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') - .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') - .toLowerCase(); -}; diff --git a/reverse_engineering/node_modules/decamelize/license b/reverse_engineering/node_modules/decamelize/license deleted file mode 100644 index 654d0bf..0000000 --- a/reverse_engineering/node_modules/decamelize/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/decamelize/package.json b/reverse_engineering/node_modules/decamelize/package.json deleted file mode 100644 index ca35790..0000000 --- a/reverse_engineering/node_modules/decamelize/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "decamelize", - "version": "1.2.0", - "description": "Convert a camelized string into a lowercased one with a custom separator: unicornRainbow → unicorn_rainbow", - "license": "MIT", - "repository": "sindresorhus/decamelize", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=0.10.0" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "decamelize", - "decamelcase", - "camelcase", - "lowercase", - "case", - "dash", - "hyphen", - "string", - "str", - "text", - "convert" - ], - "devDependencies": { - "ava": "*", - "xo": "*" - } -} diff --git a/reverse_engineering/node_modules/decamelize/readme.md b/reverse_engineering/node_modules/decamelize/readme.md deleted file mode 100644 index 624c7ee..0000000 --- a/reverse_engineering/node_modules/decamelize/readme.md +++ /dev/null @@ -1,48 +0,0 @@ -# decamelize [![Build Status](https://travis-ci.org/sindresorhus/decamelize.svg?branch=master)](https://travis-ci.org/sindresorhus/decamelize) - -> Convert a camelized string into a lowercased one with a custom separator
-> Example: `unicornRainbow` → `unicorn_rainbow` - - -## Install - -``` -$ npm install --save decamelize -``` - - -## Usage - -```js -const decamelize = require('decamelize'); - -decamelize('unicornRainbow'); -//=> 'unicorn_rainbow' - -decamelize('unicornRainbow', '-'); -//=> 'unicorn-rainbow' -``` - - -## API - -### decamelize(input, [separator]) - -#### input - -Type: `string` - -#### separator - -Type: `string`
-Default: `_` - - -## Related - -See [`camelcase`](https://github.com/sindresorhus/camelcase) for the inverse. - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/reverse_engineering/node_modules/denque/CHANGELOG.md b/reverse_engineering/node_modules/denque/CHANGELOG.md deleted file mode 100644 index 123d6ef..0000000 --- a/reverse_engineering/node_modules/denque/CHANGELOG.md +++ /dev/null @@ -1,8 +0,0 @@ -## 1.5.1 - - - perf: minor performance tweak when growing queue size (#29) - -## 1.5.0 - - - feat: adds capacity option for circular buffers (#27) - diff --git a/reverse_engineering/node_modules/denque/LICENSE b/reverse_engineering/node_modules/denque/LICENSE deleted file mode 100644 index fd22a2d..0000000 --- a/reverse_engineering/node_modules/denque/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2018 Mike Diarmid (Salakar) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this library except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/reverse_engineering/node_modules/denque/README.md b/reverse_engineering/node_modules/denque/README.md deleted file mode 100644 index 886d2dd..0000000 --- a/reverse_engineering/node_modules/denque/README.md +++ /dev/null @@ -1,77 +0,0 @@ -

-

Denque

-

- -

- NPM downloads - NPM version - Tests status - Coverage - License - Follow on Twitter -

- -Denque is a well tested, extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue) -implementation with zero dependencies and includes TypeScript types. - -Double-ended queues can also be used as a: - -- [Stack](http://en.wikipedia.org/wiki/Stack_\(abstract_data_type\)) -- [Queue](http://en.wikipedia.org/wiki/Queue_\(data_structure\)) - -This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](https://docs.page/invertase/denque/benchmarks). - -Every queue operation is done at a constant `O(1)` - including random access from `.peekAt(index)`. - -**Works on all node versions >= v0.10** - -## Quick Start - -Install the package: - -```bash -npm install denque -``` - -Create and consume a queue: - -```js -const Denque = require("denque"); - -const denque = new Denque([1,2,3,4]); -denque.shift(); // 1 -denque.pop(); // 4 -``` - - -See the [API reference documentation](https://docs.page/invertase/denque/api) for more examples. - ---- - -## Who's using it? - -- [Kafka Node.js client](https://www.npmjs.com/package/kafka-node) -- [MariaDB Node.js client](https://www.npmjs.com/package/mariadb) -- [MongoDB Node.js client](https://www.npmjs.com/package/mongodb) -- [MySQL Node.js client](https://www.npmjs.com/package/mysql2) -- [Redis Node.js clients](https://www.npmjs.com/package/redis) - -... and [many more](https://www.npmjs.com/browse/depended/denque). - - ---- - -## License - -- See [LICENSE](/LICENSE) - ---- - -

- - - -

- Built and maintained by Invertase. -

-

diff --git a/reverse_engineering/node_modules/denque/index.d.ts b/reverse_engineering/node_modules/denque/index.d.ts deleted file mode 100644 index 05d7123..0000000 --- a/reverse_engineering/node_modules/denque/index.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -declare class Denque { - constructor(); - constructor(array: T[]); - constructor(array: T[], options: IDenqueOptions); - - push(item: T): number; - unshift(item: T): number; - pop(): T | undefined; - removeBack(): T | undefined; - shift(): T | undefined; - peekBack(): T | undefined; - peekFront(): T | undefined; - peekAt(index: number): T | undefined; - get(index: number): T | undefined; - remove(index: number, count: number): T[]; - removeOne(index: number): T | undefined; - splice(index: number, count: number, ...item: T[]): T[] | undefined; - isEmpty(): boolean; - clear(): void; - - toString(): string; - toArray(): T[]; - - length: number; -} - -interface IDenqueOptions { - capacity?: number -} - -export = Denque; diff --git a/reverse_engineering/node_modules/denque/index.js b/reverse_engineering/node_modules/denque/index.js deleted file mode 100644 index c809f08..0000000 --- a/reverse_engineering/node_modules/denque/index.js +++ /dev/null @@ -1,443 +0,0 @@ -'use strict'; - -/** - * Custom implementation of a double ended queue. - */ -function Denque(array, options) { - var options = options || {}; - - this._head = 0; - this._tail = 0; - this._capacity = options.capacity; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); - } -} - -/** - * ------------- - * PUBLIC API - * ------------- - */ - -/** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} - */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; - -/** - * Alias for peekAt() - * @param i - * @returns {*} - */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; - -/** - * Returns the first item in the list without removing it. - * @returns {*} - */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; - -/** - * Alias for peek() - * @returns {*} - */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; - -/** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) - */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; - -/** - * Returns the current length of the queue - * @return {Number} - */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); - } -}); - -/** - * Return the number of items on the list, or 0 if empty. - * @returns {number} - */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; - -/** - * Add an item at the beginning of the list. - * @param item - */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._capacity && this.size() > this._capacity) this.pop(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; - -/** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; - -/** - * Add an item to the bottom of the list. - * @param item - */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); - } - if (this._capacity && this.size() > this._capacity) { - this.shift(); - } - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; - -/** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; - -/** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} - */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; - } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; - } - return item; -}; - -/** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} - */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; - } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; - } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; - } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (i < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - if (index < 0) this._tail = i; - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); - } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; - } - } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; - -/** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. - * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} - */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; - } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); - } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); - } - } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); - } - } - return removed; - } else { - return this.remove(i, count); - } -}; - -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; - -/** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; - -/** - * Returns an array of all queue items. - * @returns {Array} - */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; - -/** - * ------------- - * INTERNALS - * ------------- - */ - -/** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private - */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; - -/** - * - * @param fullCopy - * @returns {Array} - * @private - */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); - } - return newArray; -}; - -/** - * Grows the internal list array. - * @private - */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; - } - - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; - - this._list.length <<= 1; - this._capacityMask = (this._capacityMask << 1) | 1; -}; - -/** - * Shrinks the internal list array. - * @private - */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; - - -module.exports = Denque; diff --git a/reverse_engineering/node_modules/denque/package.json b/reverse_engineering/node_modules/denque/package.json deleted file mode 100644 index 42534a6..0000000 --- a/reverse_engineering/node_modules/denque/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "denque", - "version": "1.5.1", - "description": "The fastest javascript implementation of a double-ended queue. Used by the official Redis, MongoDB, MariaDB & MySQL libraries for Node.js and many other libraries. Maintains compatability with deque.", - "main": "index.js", - "engines": { - "node": ">=0.10" - }, - "keywords": [ - "data-structure", - "data-structures", - "queue", - "double", - "end", - "ended", - "deque", - "denque", - "double-ended-queue" - ], - "scripts": { - "test": "istanbul cover --report lcov _mocha && npm run typescript", - "coveralls": "cat ./coverage/lcov.info | coveralls", - "typescript": "tsc --project ./test/type/tsconfig.json", - "benchmark_thousand": "node benchmark/thousand", - "benchmark_2mil": "node benchmark/two_million", - "benchmark_splice": "node benchmark/splice", - "benchmark_remove": "node benchmark/remove", - "benchmark_removeOne": "node benchmark/removeOne" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/invertase/denque.git" - }, - "license": "Apache-2.0", - "author": { - "name": "Invertase", - "email": "oss@invertase.io", - "url": "http://github.com/invertase/" - }, - "contributors": [ - "Mike Diarmid (Salakar) " - ], - "bugs": { - "url": "https://github.com/invertase/denque/issues" - }, - "homepage": "https://docs.page/invertase/denque", - "devDependencies": { - "benchmark": "^2.1.4", - "codecov": "^3.8.3", - "double-ended-queue": "^2.1.0-0", - "istanbul": "^0.4.5", - "mocha": "^3.5.3", - "typescript": "^3.4.1" - } -} diff --git a/reverse_engineering/node_modules/duplexer/.travis.yml b/reverse_engineering/node_modules/duplexer/.travis.yml deleted file mode 100644 index ed05f88..0000000 --- a/reverse_engineering/node_modules/duplexer/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - "0.11" - - "0.10" - - "0.8" - - "0.6" diff --git a/reverse_engineering/node_modules/duplexer/LICENCE b/reverse_engineering/node_modules/duplexer/LICENCE deleted file mode 100644 index a23e08a..0000000 --- a/reverse_engineering/node_modules/duplexer/LICENCE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012 Raynos. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/duplexer/README.md b/reverse_engineering/node_modules/duplexer/README.md deleted file mode 100644 index 1dd3b89..0000000 --- a/reverse_engineering/node_modules/duplexer/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# duplexer - -[![build status][1]][2] [![dependency status][3]][4] - -[![browser support][5]][6] - -Creates a duplex stream - -Taken from [event-stream][7] - -## duplex (writeStream, readStream) - -Takes a writable stream and a readable stream and makes them appear as a readable writable stream. - -It is assumed that the two streams are connected to each other in some way. - -## Example - -```js -var cp = require('child_process') - , duplex = require('duplexer') - , grep = cp.exec('grep Stream') - -duplex(grep.stdin, grep.stdout) -``` - -## Installation - -`npm install duplexer` - -## Tests - -`npm test` - -## Contributors - - - Dominictarr - - Raynos - - samccone - -## MIT Licenced - - [1]: https://secure.travis-ci.org/Raynos/duplexer.png - [2]: https://travis-ci.org/Raynos/duplexer - [3]: https://david-dm.org/Raynos/duplexer.png - [4]: https://david-dm.org/Raynos/duplexer - [5]: https://ci.testling.com/Raynos/duplexer.png - [6]: https://ci.testling.com/Raynos/duplexer - [7]: https://github.com/dominictarr/event-stream#duplex-writestream-readstream diff --git a/reverse_engineering/node_modules/duplexer/index.js b/reverse_engineering/node_modules/duplexer/index.js deleted file mode 100644 index a188a21..0000000 --- a/reverse_engineering/node_modules/duplexer/index.js +++ /dev/null @@ -1,87 +0,0 @@ -var Stream = require("stream") -var writeMethods = ["write", "end", "destroy"] -var readMethods = ["resume", "pause"] -var readEvents = ["data", "close"] -var slice = Array.prototype.slice - -module.exports = duplex - -function forEach (arr, fn) { - if (arr.forEach) { - return arr.forEach(fn) - } - - for (var i = 0; i < arr.length; i++) { - fn(arr[i], i) - } -} - -function duplex(writer, reader) { - var stream = new Stream() - var ended = false - - forEach(writeMethods, proxyWriter) - - forEach(readMethods, proxyReader) - - forEach(readEvents, proxyStream) - - reader.on("end", handleEnd) - - writer.on("drain", function() { - stream.emit("drain") - }) - - writer.on("error", reemit) - reader.on("error", reemit) - - stream.writable = writer.writable - stream.readable = reader.readable - - return stream - - function proxyWriter(methodName) { - stream[methodName] = method - - function method() { - return writer[methodName].apply(writer, arguments) - } - } - - function proxyReader(methodName) { - stream[methodName] = method - - function method() { - stream.emit(methodName) - var func = reader[methodName] - if (func) { - return func.apply(reader, arguments) - } - reader.emit(methodName) - } - } - - function proxyStream(methodName) { - reader.on(methodName, reemit) - - function reemit() { - var args = slice.call(arguments) - args.unshift(methodName) - stream.emit.apply(stream, args) - } - } - - function handleEnd() { - if (ended) { - return - } - ended = true - var args = slice.call(arguments) - args.unshift("end") - stream.emit.apply(stream, args) - } - - function reemit(err) { - stream.emit("error", err) - } -} diff --git a/reverse_engineering/node_modules/duplexer/package.json b/reverse_engineering/node_modules/duplexer/package.json deleted file mode 100644 index 015bd41..0000000 --- a/reverse_engineering/node_modules/duplexer/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "duplexer", - "version": "0.1.2", - "description": "Creates a duplex stream", - "keywords": [], - "author": "Raynos ", - "repository": "git://github.com/Raynos/duplexer.git", - "main": "index", - "homepage": "https://github.com/Raynos/duplexer", - "contributors": [ - { - "name": "Jake Verbaten" - } - ], - "bugs": { - "url": "https://github.com/Raynos/duplexer/issues", - "email": "raynos2@gmail.com" - }, - "devDependencies": { - "tape": "0.3.3", - "through": "~0.1.4" - }, - "license": "MIT", - "scripts": { - "test": "node test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "ie/8..latest", - "firefox/16..latest", - "firefox/nightly", - "chrome/22..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest" - ] - } -} diff --git a/reverse_engineering/node_modules/duplexer/test/index.js b/reverse_engineering/node_modules/duplexer/test/index.js deleted file mode 100644 index a154567..0000000 --- a/reverse_engineering/node_modules/duplexer/test/index.js +++ /dev/null @@ -1,31 +0,0 @@ -var through = require("through") -var test = require("tape") - -var duplex = require("../index") - -var readable = through() -var writable = through(write) -var written = 0 -var data = 0 - -var stream = duplex(writable, readable) - -function write() { - written++ -} - -stream.on("data", ondata) - -function ondata() { - data++ -} - -test("emit and write", function(t) { - t.plan(2) - - stream.write() - readable.emit("data") - - t.equal(written, 1, "should have written once") - t.equal(data, 1, "should have received once") -}) diff --git a/reverse_engineering/node_modules/emoji-regex/LICENSE-MIT.txt b/reverse_engineering/node_modules/emoji-regex/LICENSE-MIT.txt deleted file mode 100644 index a41e0a7..0000000 --- a/reverse_engineering/node_modules/emoji-regex/LICENSE-MIT.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright Mathias Bynens - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/emoji-regex/README.md b/reverse_engineering/node_modules/emoji-regex/README.md deleted file mode 100644 index f10e173..0000000 --- a/reverse_engineering/node_modules/emoji-regex/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) - -_emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. - -This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. - -## Installation - -Via [npm](https://www.npmjs.com/): - -```bash -npm install emoji-regex -``` - -In [Node.js](https://nodejs.org/): - -```js -const emojiRegex = require('emoji-regex'); -// Note: because the regular expression has the global flag set, this module -// exports a function that returns the regex rather than exporting the regular -// expression itself, to make it impossible to (accidentally) mutate the -// original regular expression. - -const text = ` -\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) -\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji -\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) -\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier -`; - -const regex = emojiRegex(); -let match; -while (match = regex.exec(text)) { - const emoji = match[0]; - console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); -} -``` - -Console output: - -``` -Matched sequence ⌚ — code points: 1 -Matched sequence ⌚ — code points: 1 -Matched sequence ↔️ — code points: 2 -Matched sequence ↔️ — code points: 2 -Matched sequence 👩 — code points: 1 -Matched sequence 👩 — code points: 1 -Matched sequence 👩🏿 — code points: 2 -Matched sequence 👩🏿 — code points: 2 -``` - -To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: - -```js -const emojiRegex = require('emoji-regex/text.js'); -``` - -Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: - -```js -const emojiRegex = require('emoji-regex/es2015/index.js'); -const emojiRegexText = require('emoji-regex/es2015/text.js'); -``` - -## Author - -| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | -|---| -| [Mathias Bynens](https://mathiasbynens.be/) | - -## License - -_emoji-regex_ is available under the [MIT](https://mths.be/mit) license. diff --git a/reverse_engineering/node_modules/emoji-regex/es2015/index.js b/reverse_engineering/node_modules/emoji-regex/es2015/index.js deleted file mode 100644 index b4cf3dc..0000000 --- a/reverse_engineering/node_modules/emoji-regex/es2015/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = () => { - // https://mths.be/emoji - return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\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B}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; -}; diff --git a/reverse_engineering/node_modules/emoji-regex/es2015/text.js b/reverse_engineering/node_modules/emoji-regex/es2015/text.js deleted file mode 100644 index 780309d..0000000 --- a/reverse_engineering/node_modules/emoji-regex/es2015/text.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = () => { - // https://mths.be/emoji - return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}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A}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; -}; diff --git a/reverse_engineering/node_modules/emoji-regex/index.d.ts b/reverse_engineering/node_modules/emoji-regex/index.d.ts deleted file mode 100644 index 1955b47..0000000 --- a/reverse_engineering/node_modules/emoji-regex/index.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -declare module 'emoji-regex' { - function emojiRegex(): RegExp; - - export default emojiRegex; -} - -declare module 'emoji-regex/text' { - function emojiRegex(): RegExp; - - export default emojiRegex; -} - -declare module 'emoji-regex/es2015' { - function emojiRegex(): RegExp; - - export default emojiRegex; -} - -declare module 'emoji-regex/es2015/text' { - function emojiRegex(): RegExp; - - export default emojiRegex; -} diff --git a/reverse_engineering/node_modules/emoji-regex/index.js b/reverse_engineering/node_modules/emoji-regex/index.js deleted file mode 100644 index d993a3a..0000000 --- a/reverse_engineering/node_modules/emoji-regex/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83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uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; -}; diff --git a/reverse_engineering/node_modules/emoji-regex/package.json b/reverse_engineering/node_modules/emoji-regex/package.json deleted file mode 100644 index 6d32352..0000000 --- a/reverse_engineering/node_modules/emoji-regex/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "emoji-regex", - "version": "8.0.0", - "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", - "homepage": "https://mths.be/emoji-regex", - "main": "index.js", - "types": "index.d.ts", - "keywords": [ - "unicode", - "regex", - "regexp", - "regular expressions", - "code points", - "symbols", - "characters", - "emoji" - ], - "license": "MIT", - "author": { - "name": "Mathias Bynens", - "url": "https://mathiasbynens.be/" - }, - "repository": { - "type": "git", - "url": "https://github.com/mathiasbynens/emoji-regex.git" - }, - "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", - "files": [ - "LICENSE-MIT.txt", - "index.js", - "index.d.ts", - "text.js", - "es2015/index.js", - "es2015/text.js" - ], - "scripts": { - "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", - "test": "mocha", - "test:watch": "npm run test -- --watch" - }, - "devDependencies": { - "@babel/cli": "^7.2.3", - "@babel/core": "^7.3.4", - "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", - "@babel/preset-env": "^7.3.4", - "mocha": "^6.0.2", - "regexgen": "^1.3.0", - "unicode-12.0.0": "^0.7.9" - } -} diff --git a/reverse_engineering/node_modules/emoji-regex/text.js b/reverse_engineering/node_modules/emoji-regex/text.js deleted file mode 100644 index 0a55ce2..0000000 --- a/reverse_engineering/node_modules/emoji-regex/text.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4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72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; -}; diff --git a/reverse_engineering/node_modules/event-stream/.travis.yml b/reverse_engineering/node_modules/event-stream/.travis.yml deleted file mode 100644 index 6e5919d..0000000 --- a/reverse_engineering/node_modules/event-stream/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - "0.10" diff --git a/reverse_engineering/node_modules/event-stream/LICENCE b/reverse_engineering/node_modules/event-stream/LICENCE deleted file mode 100644 index 2af26fe..0000000 --- a/reverse_engineering/node_modules/event-stream/LICENCE +++ /dev/null @@ -1,24 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2011 Dominic Tarr - -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom -the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/event-stream/examples/data b/reverse_engineering/node_modules/event-stream/examples/data deleted file mode 100644 index 8c40730..0000000 --- a/reverse_engineering/node_modules/event-stream/examples/data +++ /dev/null @@ -1,3 +0,0 @@ -{"foo": 1} -{"foo": 2} -{"foo": 3, "bar": "test"} diff --git a/reverse_engineering/node_modules/event-stream/examples/map.js b/reverse_engineering/node_modules/event-stream/examples/map.js deleted file mode 100644 index 02eb840..0000000 --- a/reverse_engineering/node_modules/event-stream/examples/map.js +++ /dev/null @@ -1,15 +0,0 @@ -var es = require('..') - -process.stdin - .pipe(es.map(function (data, callback) { - for (var i = 0; i < data.length; i++) { - if (data[i] == 0x61) { - data[i] = 0x41 - } - } - callback(null, data) - })) - .pipe(process.stdout) - -// echo abcdabcd | node map.js -// AbcdAbcd \ No newline at end of file diff --git a/reverse_engineering/node_modules/event-stream/examples/pretty.js b/reverse_engineering/node_modules/event-stream/examples/pretty.js deleted file mode 100644 index 5ec88a4..0000000 --- a/reverse_engineering/node_modules/event-stream/examples/pretty.js +++ /dev/null @@ -1,18 +0,0 @@ - -var inspect = require('util').inspect -var es = require('..') - -es.pipe( //pipe joins streams together - process.openStdin(), //open stdin - es.split(null, null, {trailing: false}), //split stream to break on newlines - es.map(function (data, callback) { //turn this async function into a stream - var obj = JSON.parse(data) //parse input into json - callback(null, inspect(obj) + '\n') //render it nicely - }), - process.stdout // pipe it to stdout ! -) - -// cat data | node pretty.js -// { foo: 1 } -// { foo: 2 } -// { foo: 3, bar: 'test' } \ No newline at end of file diff --git a/reverse_engineering/node_modules/event-stream/examples/split.js b/reverse_engineering/node_modules/event-stream/examples/split.js deleted file mode 100644 index e21d579..0000000 --- a/reverse_engineering/node_modules/event-stream/examples/split.js +++ /dev/null @@ -1,12 +0,0 @@ -var es = require('..') - -process.stdin - .pipe(es.split(null, null, {trailing: false})) // ignore trailing empty line - .on('data', function (data) { - console.log('data: ' + data) - }) - -// cat data | node map.js -// data: {"foo": 1} -// data: {"foo": 2} -// data: {"foo": 3, "bar": "test"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/event-stream/index.js b/reverse_engineering/node_modules/event-stream/index.js deleted file mode 100644 index adb0468..0000000 --- a/reverse_engineering/node_modules/event-stream/index.js +++ /dev/null @@ -1,351 +0,0 @@ -//filter will reemit the data if cb(err,pass) pass is truthy - -// reduce is more tricky -// maybe we want to group the reductions or emit progress updates occasionally -// the most basic reduce just emits one 'data' event after it has recieved 'end' - -var Stream = require('stream').Stream - , es = exports - , through = require('through') - , from = require('from') - , duplex = require('duplexer') - , map = require('map-stream') - , pause = require('pause-stream') - , split = require('split') - , pipeline = require('stream-combiner') - , immediately = global.setImmediate || process.nextTick; - -es.Stream = Stream //re-export Stream from core -es.through = through -es.from = from -es.duplex = duplex -es.map = map -es.pause = pause -es.split = split -es.pipeline = es.connect = es.pipe = pipeline -// merge / concat -// -// combine multiple streams into a single stream. -// will emit end only once - -es.concat = //actually this should be called concat -es.merge = function (/*streams...*/) { - var toMerge = [].slice.call(arguments) - if (toMerge.length === 1 && (toMerge[0] instanceof Array)) { - toMerge = toMerge[0] //handle array as arguments object - } - var stream = new Stream() - stream.setMaxListeners(0) // allow adding more than 11 streams - var endCount = 0 - stream.writable = stream.readable = true - - if (toMerge.length) { - toMerge.forEach(function (e) { - e.pipe(stream, {end: false}) - var ended = false - e.on('end', function () { - if(ended) return - ended = true - endCount ++ - if(endCount == toMerge.length) - stream.emit('end') - }) - }) - } else { - process.nextTick(function () { - stream.emit('end') - }) - } - - stream.write = function (data) { - this.emit('data', data) - } - stream.destroy = function () { - toMerge.forEach(function (e) { - if(e.destroy) e.destroy() - }) - } - return stream -} - - -// writable stream, collects all events into an array -// and calls back when 'end' occurs -// mainly I'm using this to test the other functions - -es.collect = -es.writeArray = function (done) { - if ('function' !== typeof done) - throw new Error('function writeArray (done): done must be function') - - var a = new Stream () - , array = [], isDone = false - a.write = function (l) { - array.push(l) - } - a.end = function () { - isDone = true - done(null, array) - } - a.writable = true - a.readable = false - a.destroy = function () { - a.writable = a.readable = false - if(isDone) return - done(new Error('destroyed before end'), array) - } - return a -} - -//return a Stream that reads the properties of an object -//respecting pause() and resume() - -es.readArray = function (array) { - var stream = new Stream() - , i = 0 - , paused = false - , ended = false - - stream.readable = true - stream.writable = false - - if(!Array.isArray(array)) - throw new Error('event-stream.read expects an array') - - stream.resume = function () { - if(ended) return - paused = false - var l = array.length - while(i < l && !paused && !ended) { - stream.emit('data', array[i++]) - } - if(i == l && !ended) - ended = true, stream.readable = false, stream.emit('end') - } - process.nextTick(stream.resume) - stream.pause = function () { - paused = true - } - stream.destroy = function () { - ended = true - stream.emit('close') - } - return stream -} - -// -// readable (asyncFunction) -// return a stream that calls an async function while the stream is not paused. -// -// the function must take: (count, callback) {... -// - -es.readable = -function (func, continueOnError) { - var stream = new Stream() - , i = 0 - , paused = false - , ended = false - , reading = false - - stream.readable = true - stream.writable = false - - if('function' !== typeof func) - throw new Error('event-stream.readable expects async function') - - stream.on('end', function () { ended = true }) - - function get (err, data) { - - if(err) { - stream.emit('error', err) - if(!continueOnError) stream.emit('end') - } else if (arguments.length > 1) - stream.emit('data', data) - - immediately(function () { - if(ended || paused || reading) return - try { - reading = true - func.call(stream, i++, function () { - reading = false - get.apply(null, arguments) - }) - } catch (err) { - stream.emit('error', err) - } - }) - } - stream.resume = function () { - paused = false - get() - } - process.nextTick(get) - stream.pause = function () { - paused = true - } - stream.destroy = function () { - stream.emit('end') - stream.emit('close') - ended = true - } - return stream -} - - -// -// map sync -// - -es.mapSync = function (sync) { - return es.through(function write(data) { - var mappedData - try { - mappedData = sync(data) - } catch (err) { - return this.emit('error', err) - } - if (mappedData !== undefined) - this.emit('data', mappedData) - }) -} - -// -// filterSync -// - -es.filterSync = function (test) { - return es.through(function(data){ - var s = this - if (test(data)) { - s.queue(data) - } - }); -} - -// -// flatmapSync -// - -es.flatmapSync = function (mapper) { - return es.through(function(data) { - var s = this - data.forEach(function(e) { - s.queue(mapper(e)) - }) - }) -} - -// -// log just print out what is coming through the stream, for debugging -// - -es.log = function (name) { - return es.through(function (data) { - var args = [].slice.call(arguments) - if(name) console.error(name, data) - else console.error(data) - this.emit('data', data) - }) -} - - -// -// child -- pipe through a child process -// - -es.child = function (child) { - - return es.duplex(child.stdin, child.stdout) - -} - -// -// parse -// -// must be used after es.split() to ensure that each chunk represents a line -// source.pipe(es.split()).pipe(es.parse()) - -es.parse = function (options) { - var emitError = !!(options ? options.error : false) - return es.through(function (data) { - var obj - try { - if(data) //ignore empty lines - obj = JSON.parse(data.toString()) - } catch (err) { - if (emitError) - return this.emit('error', err) - return console.error(err, 'attempting to parse:', data) - } - //ignore lines that where only whitespace. - if(obj !== undefined) - this.emit('data', obj) - }) -} -// -// stringify -// - -es.stringify = function () { - var Buffer = require('buffer').Buffer - return es.mapSync(function (e){ - return JSON.stringify(Buffer.isBuffer(e) ? e.toString() : e) + '\n' - }) -} - -// -// replace a string within a stream. -// -// warn: just concatenates the string and then does str.split().join(). -// probably not optimal. -// for smallish responses, who cares? -// I need this for shadow-npm so it's only relatively small json files. - -es.replace = function (from, to) { - return es.pipeline(es.split(from), es.join(to)) -} - -// -// join chunks with a joiner. just like Array#join -// also accepts a callback that is passed the chunks appended together -// this is still supported for legacy reasons. -// - -es.join = function (str) { - - //legacy api - if('function' === typeof str) - return es.wait(str) - - var first = true - return es.through(function (data) { - if(!first) - this.emit('data', str) - first = false - this.emit('data', data) - return true - }) -} - - -// -// wait. callback when 'end' is emitted, with all chunks appended as string. -// - -es.wait = function (callback) { - var arr = [] - return es.through(function (data) { arr.push(data) }, - function () { - var body = Buffer.isBuffer(arr[0]) ? Buffer.concat(arr) - : arr.join('') - this.emit('data', body) - this.emit('end') - if(callback) callback(null, body) - }) -} - -es.pipeable = function () { - throw new Error('[EVENT-STREAM] es.pipeable is deprecated') -} diff --git a/reverse_engineering/node_modules/event-stream/package.json b/reverse_engineering/node_modules/event-stream/package.json deleted file mode 100644 index a2a487d..0000000 --- a/reverse_engineering/node_modules/event-stream/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "event-stream", - "version": "4.0.1", - "description": "construct pipes of streams of events", - "homepage": "http://github.com/dominictarr/event-stream", - "repository": { - "type": "git", - "url": "git://github.com/dominictarr/event-stream.git" - }, - "dependencies": { - "duplexer": "^0.1.1", - "from": "^0.1.7", - "map-stream": "0.0.7", - "pause-stream": "^0.0.11", - "split": "^1.0.1", - "stream-combiner": "^0.2.2", - "through": "^2.3.8" - }, - "devDependencies": { - "asynct": "^1.1.0", - "it-is": "^1.0.3", - "stream-spec": "^0.3.6", - "tape": "^4.9.1", - "ubelt": "^3.2.2" - }, - "scripts": { - "prepublish": "npm ls && npm test", - "test": "asynct test/", - "test_tap": "set -e; for t in test/*.js; do node $t; done" - }, - "keywords": [ - "stream", "map", "flatmap", "filter", "split", "join", "merge", "replace" - ], - "license": "MIT", - "author": "Dominic Tarr (http://bit.ly/dominictarr)" -} diff --git a/reverse_engineering/node_modules/event-stream/readme.markdown b/reverse_engineering/node_modules/event-stream/readme.markdown deleted file mode 100644 index 4ce5177..0000000 --- a/reverse_engineering/node_modules/event-stream/readme.markdown +++ /dev/null @@ -1,345 +0,0 @@ -# EventStream - -[Streams](http://nodejs.org/api/stream.html "Stream") are node's best and most misunderstood idea, and EventStream is a toolkit to make creating and working with streams easy. - -Normally, streams are only used for IO, but in event stream we send all kinds of objects down the pipe. If your application's input and output are streams, shouldn't the throughput be a stream too? - -The *EventStream* functions resemble the array functions, because Streams are like Arrays, but laid out in time, rather than in memory. - -All the `event-stream` functions return instances of `Stream`. - -`event-stream` creates [0.8 streams](https://github.com/joyent/node/blob/v0.8/doc/api/stream.markdown), which are compatible with [0.10 streams](http://nodejs.org/api/stream.html "Stream"). - ->NOTE: I shall use the term "through stream" to refer to a stream that is writable and readable. - ->NOTE for Gulp users: Merge will not work for gulp 4. [merge-stream](https://npmjs.com/merge-stream) should be used. - -### [simple example](https://github.com/dominictarr/event-stream/blob/master/examples/pretty.js): - -``` js -//pretty.js - -if(!module.parent) { - var es = require('event-stream') - var inspect = require('util').inspect - - process.stdin //connect streams together with `pipe` - .pipe(es.split()) //split stream to break on newlines - .pipe(es.map(function (data, cb) { //turn this async function into a stream - cb(null - , inspect(JSON.parse(data))) //render it nicely - })) - .pipe(process.stdout) // pipe it to stdout ! -} -``` -run it ... - -``` bash -curl -sS registry.npmjs.org/event-stream | node pretty.js -``` - -[node Stream documentation](http://nodejs.org/api/stream.html) - -## through (write?, end?) - -Re-emits data synchronously. Easy way to create synchronous through streams. -Pass in optional `write` and `end` methods. They will be called in the -context of the stream. Use `this.pause()` and `this.resume()` to manage flow. -Check `this.paused` to see current flow state. (write always returns `!this.paused`) - -this function is the basis for most of the synchronous streams in `event-stream`. - -``` js - -es.through(function write(data) { - this.emit('data', data) - //this.pause() - }, - function end () { //optional - this.emit('end') - }) - -``` - -## map (asyncFunction) - -Create a through stream from an asynchronous function. - -``` js -var es = require('event-stream') - -es.map(function (data, callback) { - //transform data - // ... - callback(null, data) -}) - -``` - -Each map MUST call the callback. It may callback with data, with an error or with no arguments, - - * `callback()` drop this data. - this makes the map work like `filter`, - note:`callback(null,null)` is not the same, and will emit `null` - - * `callback(null, newData)` turn data into newData - - * `callback(error)` emit an error for this item. - ->Note: if a callback is not called, `map` will think that it is still being processed, ->every call must be answered or the stream will not know when to end. -> ->Also, if the callback is called more than once, every call but the first will be ignored. - -## mapSync (syncFunction) - -Same as `map`, but the callback is called synchronously. Based on `es.through` - -## flatmapSync (syncFunction) - -Map elements nested. - -``` js -var es = require('event-stream') - -es.flatmapSync(function (data) { - //transform data - // ... - return data -}) - -``` - -## filterSync (syncFunction) - -Filter elements. - -``` js -var es = require('event-stream') - -es.filterSync(function (data) { - return data > 0 -}) - -``` - -## split (matcher) - -Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` - -Example, read every line in a file ... - -``` js -fs.createReadStream(file, {flags: 'r'}) - .pipe(es.split()) - .pipe(es.map(function (line, cb) { - //do something with the line - cb(null, line) - })) -``` - -`split` takes the same arguments as `string.split` except it defaults to '\n' instead of ',', and the optional `limit` parameter is ignored. -[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split) - -**NOTE** - Maintaining Line Breaks -If you want to process each line of the stream, transform the data, reassemble, and **KEEP** the line breaks the example will look like this: - -```javascript -fs.createReadStream(file, {flags: 'r'}) - .pipe(es.split(/(\r?\n)/)) - .pipe(es.map(function (line, cb) { - //do something with the line - cb(null, line) - })) -``` - -This technique is mentioned in the [underlying documentation](https://www.npmjs.com/package/split#keep-matched-splitter) for the split npm package. - -## join (separator) - -Create a through stream that emits `separator` between each chunk, just like Array#join. - -(for legacy reasons, if you pass a callback instead of a string, join is a synonym for `es.wait`) - -## merge (stream1,...,streamN) or merge (streamArray) -> concat → merge - -Merges streams into one and returns it. -Incoming data will be emitted as soon it comes into - no ordering will be applied (for example: `data1 data1 data2 data1 data2` - where `data1` and `data2` is data from two streams). -Counts how many streams were passed to it and emits end only when all streams emitted end. - -```js -es.merge( - process.stdout, - process.stderr -).pipe(fs.createWriteStream('output.log')); -``` - -It can also take an Array of streams as input like this: -```js -es.merge([ - fs.createReadStream('input1.txt'), - fs.createReadStream('input2.txt') -]).pipe(fs.createWriteStream('output.log')); -``` - -## replace (from, to) - -Replace all occurrences of `from` with `to`. `from` may be a `String` or a `RegExp`. -Works just like `string.split(from).join(to)`, but streaming. - - -## parse - -Convenience function for parsing JSON chunks. For newline separated JSON, -use with `es.split`. By default it logs parsing errors by `console.error`; -for another behaviour, transforms created by `es.parse({error: true})` will -emit error events for exceptions thrown from `JSON.parse`, unmodified. - -``` js -fs.createReadStream(filename) - .pipe(es.split()) //defaults to lines. - .pipe(es.parse()) -``` - -## stringify - -convert javascript objects into lines of text. The text will have whitespace escaped and have a `\n` appended, so it will be compatible with `es.parse` - -``` js -objectStream - .pipe(es.stringify()) - .pipe(fs.createWriteStream(filename)) -``` - -## readable (asyncFunction) - -create a readable stream (that respects pause) from an async function. -while the stream is not paused, -the function will be polled with `(count, callback)`, -and `this` will be the readable stream. - -``` js - -es.readable(function (count, callback) { - if(streamHasEnded) - return this.emit('end') - - //... - - this.emit('data', data) //use this way to emit multiple chunks per call. - - callback() // you MUST always call the callback eventually. - // the function will not be called again until you do this. -}) -``` -you can also pass the data and the error to the callback. -you may only call the callback once. -calling the same callback more than once will have no effect. - -## readArray (array) - -Create a readable stream from an Array. - -Just emit each item as a data event, respecting `pause` and `resume`. - -``` js - var es = require('event-stream') - , reader = es.readArray([1,2,3]) - - reader.pipe(...) -``` - -If you want the stream behave like a 0.10 stream you will need to wrap it using [`Readable.wrap()`](http://nodejs.org/api/stream.html#stream_readable_wrap_stream) function. Example: - -``` js - var s = new stream.Readable({objectMode: true}).wrap(es.readArray([1,2,3])); -``` - -## writeArray (callback) - -create a writeable stream from a callback, -all `data` events are stored in an array, which is passed to the callback when the stream ends. - -``` js - var es = require('event-stream') - , reader = es.readArray([1, 2, 3]) - , writer = es.writeArray(function (err, array){ - //array deepEqual [1, 2, 3] - }) - - reader.pipe(writer) -``` - -## pause () - -A stream that buffers all chunks when paused. - - -``` js - var ps = es.pause() - ps.pause() //buffer the stream, also do not allow 'end' - ps.resume() //allow chunks through -``` - -## duplex (writeStream, readStream) - -Takes a writable stream and a readable stream and makes them appear as a readable writable stream. - -It is assumed that the two streams are connected to each other in some way. - -(This is used by `pipeline` and `child`.) - -``` js - var grep = cp.exec('grep Stream') - - es.duplex(grep.stdin, grep.stdout) -``` - -## child (child_process) - -Create a through stream from a child process ... - -``` js - var cp = require('child_process') - - es.child(cp.exec('grep Stream')) // a through stream - -``` - -## wait (callback) - -waits for stream to emit 'end'. -joins chunks of a stream into a single string or buffer. -takes an optional callback, which will be passed the -complete string/buffer when it receives the 'end' event. - -also, emits a single 'data' event. - -``` js - -readStream.pipe(es.wait(function (err, body) { - // have complete text here. -})) - -``` - -# Other Stream Modules - -These modules are not included as a part of *EventStream* but may be -useful when working with streams. - -## [reduce (syncFunction, initial)](https://github.com/parshap/node-stream-reduce) - -Like `Array.prototype.reduce` but for streams. Given a sync reduce -function and an initial value it will return a through stream that emits -a single data event with the reduced value once the input stream ends. - -``` js -var reduce = require("stream-reduce"); -process.stdin.pipe(reduce(function(acc, data) { - return acc + data.length; -}, 0)).on("data", function(length) { - console.log("stdin size:", length); -}); -``` diff --git a/reverse_engineering/node_modules/event-stream/test/connect.asynct.js b/reverse_engineering/node_modules/event-stream/test/connect.asynct.js deleted file mode 100644 index e6a442b..0000000 --- a/reverse_engineering/node_modules/event-stream/test/connect.asynct.js +++ /dev/null @@ -1,86 +0,0 @@ -var es = require('../') - , it = require('it-is').style('colour') - , d = require('ubelt') - -function makeExamplePipe() { - - return es.connect( - es.map(function (data, callback) { - callback(null, data * 2) - }), - es.map(function (data, callback) { - d.delay(callback)(null, data) - }), - es.map(function (data, callback) { - callback(null, data + 2) - })) -} - -exports['simple pipe'] = function (test) { - - var pipe = makeExamplePipe() - - pipe.on('data', function (data) { - it(data).equal(18) - test.done() - }) - - pipe.write(8) - -} - -exports['read array then map'] = function (test) { - - var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 - , first = es.readArray(readThis) - , read = [] - , pipe = - es.connect( - first, - es.map(function (data, callback) { - callback(null, {data: data}) - }), - es.map(function (data, callback) { - callback(null, {data: data}) - }), - es.writeArray(function (err, array) { - it(array).deepEqual(d.map(readThis, function (data) { - return {data: {data: data}} - })) - test.done() - }) - ) -} - -exports ['connect returns a stream'] = function (test) { - - var rw = - es.connect( - es.map(function (data, callback) { - callback(null, data * 2) - }), - es.map(function (data, callback) { - callback(null, data * 5) - }) - ) - - it(rw).has({readable: true, writable: true}) - - var array = [190, 24, 6, 7, 40, 57, 4, 6] - , _array = [] - , c = - es.connect( - es.readArray(array), - rw, - es.log('after rw:'), - es.writeArray(function (err, _array) { - it(_array).deepEqual(array.map(function (e) { return e * 10 })) - test.done() - }) - ) - -} - - -require('./helper')(module) - diff --git a/reverse_engineering/node_modules/event-stream/test/filter.asynct.js b/reverse_engineering/node_modules/event-stream/test/filter.asynct.js deleted file mode 100644 index 1d2e4f9..0000000 --- a/reverse_engineering/node_modules/event-stream/test/filter.asynct.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var es = require('../') - , it = require('it-is') - -exports ['filter'] = function (test) { - es.readArray([1, 2, 3, 4]) - .pipe(es.filterSync(function(e) { - return e > 2 - })) - .pipe(es.writeArray(function(error, array) { - test.deepEqual([3, 4], array) - test.end() - })) -} - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/flatmap.asynct.js b/reverse_engineering/node_modules/event-stream/test/flatmap.asynct.js deleted file mode 100644 index ae6a9a0..0000000 --- a/reverse_engineering/node_modules/event-stream/test/flatmap.asynct.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var es = require('../') - , it = require('it-is') - -exports ['flatmap'] = function (test) { - es.readArray([[1], [1, 2], [1, 2, 3]]) - .pipe(es.flatmapSync(function(e) { - return e + 1 - })) - .pipe(es.writeArray(function(error, array) { - test.deepEqual([2, 2, 3, 2, 3, 4], array) - test.end() - })) -} - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/helper/index.js b/reverse_engineering/node_modules/event-stream/test/helper/index.js deleted file mode 100644 index 96abaeb..0000000 --- a/reverse_engineering/node_modules/event-stream/test/helper/index.js +++ /dev/null @@ -1,12 +0,0 @@ -var tape = require('tape') - -module.exports = function (m) { - if(m.parent) return - for(var name in m.exports) { - tape(name, function (t) { - console.log('start', name) - t.done = t.end - m.exports[name](t) - }) - } -} diff --git a/reverse_engineering/node_modules/event-stream/test/merge.asynct.js b/reverse_engineering/node_modules/event-stream/test/merge.asynct.js deleted file mode 100644 index 68f38ba..0000000 --- a/reverse_engineering/node_modules/event-stream/test/merge.asynct.js +++ /dev/null @@ -1,29 +0,0 @@ -var es = require('../') - , it = require('it-is').style('colour') - , d = require('ubelt') - -exports.merge = function (t) { - var odd = d.map(1, 3, 100, d.id) //array of multiples of 3 < 100 - var even = d.map(2, 4, 100, d.id) //array of multiples of 3 < 100 - - var r1 = es.readArray(even) - var r2 = es.readArray(odd) - var endCount = 0 - - var writer = es.writeArray(function (err, array){ - if(err) throw err //unpossible - it(array.sort()).deepEqual(even.concat(odd).sort()) - if (++endCount === 2) t.done() - }) - - var writer2 = es.writeArray(function (err, array){ - if(err) throw err //unpossible - it(array.sort()).deepEqual(even.concat(odd).sort()) - if (++endCount === 2) t.done() - }) - - es.merge(r1, r2).pipe(writer) - es.merge([r1, r2]).pipe(writer2) - -} -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/parse.asynct.js b/reverse_engineering/node_modules/event-stream/test/parse.asynct.js deleted file mode 100644 index a5fefcf..0000000 --- a/reverse_engineering/node_modules/event-stream/test/parse.asynct.js +++ /dev/null @@ -1,32 +0,0 @@ -var es = require('../') - , it = require('it-is').style('colour') - -exports ['es.parse() writes parsing errors with console.error'] = function (test) { - var parseStream = es.parse() - var oldConsoleError = console.error - console.error = function () { - console.error = oldConsoleError - it(arguments.length > 0).ok() - test.done() - } - - // bare word is not valid JSON - parseStream.write('A') -} - -exports ['es.parse({error: true(thy)}) emits error events from parsing'] = function (test) { - var parseStream = es.parse({error: 1}) - var expectedError - try { - JSON.parse('A') - } catch(e) { - expectedError = e - } - - parseStream.on('error', function (e) { - it(e).deepEqual(expectedError) - process.nextTick(function () { - test.done() - }) - }).write('A') -} diff --git a/reverse_engineering/node_modules/event-stream/test/pause.asynct.js b/reverse_engineering/node_modules/event-stream/test/pause.asynct.js deleted file mode 100644 index b073604..0000000 --- a/reverse_engineering/node_modules/event-stream/test/pause.asynct.js +++ /dev/null @@ -1,39 +0,0 @@ - -var es = require('../') - , it = require('it-is') - , d = require('ubelt') - -exports ['gate buffers when shut'] = function (test) { - - var hundy = d.map(1,100, d.id) - , gate = es.pause() - , ten = 10 - es.connect( - es.readArray(hundy), - es.log('after readArray'), - gate, - //es.log('after gate'), - es.map(function (num, next) { - //stick a map in here to check that gate never emits when open - it(gate.paused).equal(false) - console.log('data', num) - if(!--ten) { - console.log('PAUSE') - gate.pause()//.resume() - d.delay(gate.resume.bind(gate), 10)() - ten = 10 - } - - next(null, num) - }), - es.writeArray(function (err, array) { //just realized that I should remove the error param. errors will be emitted - console.log('eonuhoenuoecbulc') - it(array).deepEqual(hundy) - test.done() - }) - ) - - gate.resume() - -} -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/pipeline.asynct.js b/reverse_engineering/node_modules/event-stream/test/pipeline.asynct.js deleted file mode 100644 index f07c6fa..0000000 --- a/reverse_engineering/node_modules/event-stream/test/pipeline.asynct.js +++ /dev/null @@ -1,52 +0,0 @@ -var es = require('..') - -exports['do not duplicate errors'] = function (test) { - - var errors = 0; - var pipe = es.pipeline( - es.through(function(data) { - return this.emit('data', data); - }), - es.through(function(data) { - return this.emit('error', new Error(data)); - }) - ) - - pipe.on('error', function(err) { - errors++ - console.log('error count', errors) - process.nextTick(function () { - return test.done(); - }) - }) - - return pipe.write('meh'); - -} - -exports['3 pipe do not duplicate errors'] = function (test) { - - var errors = 0; - var pipe = es.pipeline( - es.through(function(data) { - return this.emit('data', data); - }), - es.through(function(data) { - return this.emit('error', new Error(data)); - }), - es.through() - ) - - pipe.on('error', function(err) { - errors++ - console.log('error count', errors) - process.nextTick(function () { - return test.done(); - }) - }) - - return pipe.write('meh'); - -} - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/readArray.asynct.js b/reverse_engineering/node_modules/event-stream/test/readArray.asynct.js deleted file mode 100644 index 3eeb90a..0000000 --- a/reverse_engineering/node_modules/event-stream/test/readArray.asynct.js +++ /dev/null @@ -1,89 +0,0 @@ - -var es = require('../') - , it = require('it-is').style('colour') - , d = require('ubelt') - -function readStream(stream, pauseAt, done) { - if(!done) done = pauseAt, pauseAt = -1 - var array = [] - stream.on('data', function (data) { - array.push(data) - if(!--pauseAt ) - stream.pause(), done(null, array) - }) - stream.on('error', done) - stream.on('end', function (data) { - done(null, array) - }) - -} - -exports ['read an array'] = function (test) { - - var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 - - var reader = es.readArray(readThis) - - var writer = es.writeArray(function (err, array){ - if(err) throw err //unpossible - it(array).deepEqual(readThis) - test.done() - }) - - reader.pipe(writer) -} - -exports ['read an array and pause it.'] = function (test) { - - var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 - - var reader = es.readArray(readThis) - - readStream(reader, 10, function (err, data) { - if(err) throw err - it(data).deepEqual([3, 6, 9, 12, 15, 18, 21, 24, 27, 30]) - readStream(reader, 10, function (err, data) { - it(data).deepEqual([33, 36, 39, 42, 45, 48, 51, 54, 57, 60]) - test.done() - }) - reader.resume() - }) - -} - -exports ['reader is readable, but not writeable'] = function (test) { - var reader = es.readArray([1]) - it(reader).has({ - readable: true, - writable: false - }) - - test.done() -} - - -exports ['read one item per tick'] = function (test) { - var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 - var drains = 0 - var reader = es.readArray(readThis) - var tickMapper = es.map(function (data,callback) { - process.nextTick(function () { - callback(null, data) - }) - //since tickMapper is returning false - //pipe should pause the writer until a drain occurs - return false - }) - reader.pipe(tickMapper) - readStream(tickMapper, function (err, array) { - it(array).deepEqual(readThis) - it(array.length).deepEqual(readThis.length) - it(drains).equal(readThis.length) - test.done() - }) - tickMapper.on('drain', function () { - drains ++ - }) - -} -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/readable.asynct.js b/reverse_engineering/node_modules/event-stream/test/readable.asynct.js deleted file mode 100644 index 6ea2fdb..0000000 --- a/reverse_engineering/node_modules/event-stream/test/readable.asynct.js +++ /dev/null @@ -1,197 +0,0 @@ - -var es = require('../') - , it = require('it-is').style('colour') - , u = require('ubelt') - -exports ['read an array'] = function (test) { - - - console.log('readable') - return test.end() - var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100 - - console.log('readable') - - var reader = - es.readable(function (i, callback) { - if(i >= readThis.length) - return this.emit('end') - console.log('readable') - callback(null, readThis[i]) - }) - - var writer = es.writeArray(function (err, array){ - if(err) throw err - it(array).deepEqual(readThis) - test.done() - }) - - reader.pipe(writer) -} - -exports ['read an array - async'] = function (test) { - - var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100 - - var reader = - es.readable(function (i, callback) { - if(i >= readThis.length) - return this.emit('end') - u.delay(callback)(null, readThis[i]) - }) - - var writer = es.writeArray(function (err, array){ - if(err) throw err - it(array).deepEqual(readThis) - test.done() - }) - - reader.pipe(writer) -} - - -exports ['emit data then call next() also works'] = function (test) { - - var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100 - - var reader = - es.readable(function (i, next) { - if(i >= readThis.length) - return this.emit('end') - this.emit('data', readThis[i]) - next() - }) - - var writer = es.writeArray(function (err, array){ - if(err) throw err - it(array).deepEqual(readThis) - test.done() - }) - - reader.pipe(writer) -} - - -exports ['callback emits error, then stops'] = function (test) { - - var err = new Error('INTENSIONAL ERROR') - , called = 0 - - var reader = - es.readable(function (i, callback) { - if(called++) - return - callback(err) - }) - - reader.on('error', function (_err){ - it(_err).deepEqual(err) - u.delay(function() { - it(called).equal(1) - test.done() - }, 50)() - }) -} - -exports['readable does not call read concurrently'] = function (test) { - - var current = 0 - var source = es.readable(function(count, cb){ - current ++ - if(count > 100) - return this.emit('end') - u.delay(function(){ - current -- - it(current).equal(0) - cb(null, {ok: true, n: count}); - })(); - }); - - var destination = es.map(function(data, cb){ - //console.info(data); - cb(); - }); - - var all = es.connect(source, destination); - - destination.on('end', test.done) -} - -exports ['does not raise a warning: Recursive process.nextTick detected'] = function (test) { - var readThisDelayed; - - u.delay(function () { - readThisDelayed = [1, 3, 5]; - })(); - - es.readable(function (count, callback) { - - if (readThisDelayed) { - var that = this; - readThisDelayed.forEach(function (item) { - that.emit('data', item); - }); - - this.emit('end'); - test.done(); - } - - callback(); - }); -}; - -// -// emitting multiple errors is not supported by stream. -// -// I do not think that this is a good idea, at least, there should be an option to pipe to -// continue on error. it makes alot ef sense, if you are using Stream like I am, to be able to emit multiple errors. -// an error might not necessarily mean the end of the stream. it depends on the error, at least. -// -// I will start a thread on the mailing list. I'd rather that than use a custom `pipe` implementation. -// -// basically, I want to be able use pipe to transform objects, and if one object is invalid, -// the next might still be good, so I should get to choose if it's gonna stop. -// re-enstate this test when this issue progresses. -// -// hmm. I could add this to es.connect by deregistering the error listener, -// but I would rather it be an option in core. - -/* -exports ['emit multiple errors, with 2nd parameter (continueOnError)'] = function (test) { - - var readThis = d.map(1, 100, d.id) - , errors = 0 - var reader = - es.readable(function (i, callback) { - console.log(i, readThis.length) - if(i >= readThis.length) - return this.emit('end') - if(!(readThis[i] % 7)) - return callback(readThis[i]) - callback(null, readThis[i]) - }, true) - - var writer = es.writeArray(function (err, array) { - if(err) throw err - it(array).every(function (u){ - it(u % 7).notEqual(0) - }).property('length', 80) - it(errors).equal(14) - test.done() - }) - - reader.on('error', function (u) { - errors ++ - console.log(u) - if('number' !== typeof u) - throw u - - it(u % 7).equal(0) - - }) - - reader.pipe(writer) -} -*/ - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/replace.asynct.js b/reverse_engineering/node_modules/event-stream/test/replace.asynct.js deleted file mode 100644 index 1c8735b..0000000 --- a/reverse_engineering/node_modules/event-stream/test/replace.asynct.js +++ /dev/null @@ -1,76 +0,0 @@ -var es = require('../') - , it = require('it-is').style('colour') - , d = require('ubelt') - , spec = require('stream-spec') - -var next = process.nextTick - -var fizzbuzz = '12F4BF78FB11F1314FB1617F19BF2223FB26F2829FB3132F34BF3738FB41F4344FB4647F49BF5253FB56F5859FB6162F64BF6768FB71F7374FB7677F79BF8283FB86F8889FB9192F94BF9798FB' - , fizz7buzz = '12F4BFseven8FB11F1314FB161sevenF19BF2223FB26F2829FB3132F34BF3seven38FB41F4344FB464sevenF49BF5253FB56F5859FB6162F64BF6seven68FBseven1Fseven3seven4FBseven6sevensevenFseven9BF8283FB86F8889FB9192F94BF9seven98FB' - , fizzbuzzwhitespce = ' 12F4BF78FB11F1314FB1617F19BF2223FB26F2829FB3132F34BF3738FB41F4344FB4647F49BF5253FB56F5859FB6162F64BF6768FB71F7374FB7677F79BF8283FB86F8889FB9192F94BF9798FB ' - -exports ['fizz buzz'] = function (test) { - - var readThis = d.map(1, 100, function (i) { - return ( - ! (i % 3 || i % 5) ? "FB" : - !(i % 3) ? "F" : - !(i % 5) ? "B" : - ''+i - ) - }) //array of multiples of 3 < 100 - - var reader = es.readArray(readThis) - var join = es.wait(function (err, string){ - it(string).equal(fizzbuzz) - test.done() - }) - reader.pipe(join) - -} - - -exports ['fizz buzz replace'] = function (test) { - var split = es.split(/(1)/) - var replace = es.replace('7', 'seven') -// var x = spec(replace).through() - split - .pipe(replace) - .pipe(es.join(function (err, string) { - it(string).equal(fizz7buzz) - })) - - replace.on('close', function () { -// x.validate() - test.done() - }) - - split.write(fizzbuzz) - split.end() - -} - - -exports ['fizz buzz replace whitespace using regexp'] = function (test) { - var split = es.split(/(1)/) - var replaceLeading = es.replace(/^[\s]*/, '') - var replaceTrailing = es.replace(/[\s]*$/, '') -// var x = spec(replace).through() - split - .pipe(replaceLeading) - .pipe(replaceTrailing) - .pipe(es.join(function (err, string) { - it(string).equal(fizzbuzz) - })) - - replaceTrailing.on('close', function () { -// x.validate() - test.done() - }) - - split.write(fizzbuzz) - split.end() - -} - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/simple-map.asynct.js b/reverse_engineering/node_modules/event-stream/test/simple-map.asynct.js deleted file mode 100644 index 25121f9..0000000 --- a/reverse_engineering/node_modules/event-stream/test/simple-map.asynct.js +++ /dev/null @@ -1,343 +0,0 @@ -'use strict'; - -var es = require('../') - , it = require('it-is') - , u = require('ubelt') - , spec = require('stream-spec') - , Stream = require('stream') - , from = require('from') - , through = require('through') - -//REFACTOR THIS TEST TO USE es.readArray and es.writeArray - -function writeArray(array, stream) { - - array.forEach( function (j) { - stream.write(j) - }) - stream.end() - -} - -function readStream(stream, done) { - - var array = [] - stream.on('data', function (data) { - array.push(data) - }) - stream.on('error', done) - stream.on('end', function (data) { - done(null, array) - }) - -} - -//call sink on each write, -//and complete when finished. - -function pauseStream (prob, delay) { - var pauseIf = ( - 'number' == typeof prob - ? function () { - return Math.random() < prob - } - : 'function' == typeof prob - ? prob - : 0.1 - ) - var delayer = ( - !delay - ? process.nextTick - : 'number' == typeof delay - ? function (next) { setTimeout(next, delay) } - : delay - ) - - return es.through(function (data) { - if(!this.paused && pauseIf()) { - console.log('PAUSE STREAM PAUSING') - this.pause() - var self = this - delayer(function () { - console.log('PAUSE STREAM RESUMING') - self.resume() - }) - } - console.log("emit ('data', " + data + ')') - this.emit('data', data) - }) -} - -exports ['simple map'] = function (test) { - - var input = u.map(1, 1000, function () { - return Math.random() - }) - var expected = input.map(function (v) { - return v * 2 - }) - - var pause = pauseStream(0.1) - var fs = from(input) - var ts = es.writeArray(function (err, ar) { - it(ar).deepEqual(expected) - test.done() - }) - var map = es.through(function (data) { - this.emit('data', data * 2) - }) - - spec(map).through().validateOnExit() - spec(pause).through().validateOnExit() - - fs.pipe(map).pipe(pause).pipe(ts) -} - -exports ['simple map applied to a stream'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - //create event stream from - - var doubler = es.map(function (data, cb) { - cb(null, data * 2) - }) - - spec(doubler).through().validateOnExit() - - //a map is only a middle man, so it is both readable and writable - - it(doubler).has({ - readable: true, - writable: true, - }) - - readStream(doubler, function (err, output) { - it(output).deepEqual(input.map(function (j) { - return j * 2 - })) -// process.nextTick(x.validate) - test.done() - }) - - writeArray(input, doubler) - -} - -exports['pipe two maps together'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - //create event stream from - function dd (data, cb) { - cb(null, data * 2) - } - var doubler1 = es.map(dd), doubler2 = es.map(dd) - - doubler1.pipe(doubler2) - - spec(doubler1).through().validateOnExit() - spec(doubler2).through().validateOnExit() - - readStream(doubler2, function (err, output) { - it(output).deepEqual(input.map(function (j) { - return j * 4 - })) - test.done() - }) - - writeArray(input, doubler1) - -} - -//next: -// -// test pause, resume and drian. -// - -// then make a pipe joiner: -// -// plumber (evStr1, evStr2, evStr3, evStr4, evStr5) -// -// will return a single stream that write goes to the first - -exports ['map will not call end until the callback'] = function (test) { - - var ticker = es.map(function (data, cb) { - process.nextTick(function () { - cb(null, data * 2) - }) - }) - - spec(ticker).through().validateOnExit() - - ticker.write('x') - ticker.end() - - ticker.on('end', function () { - test.done() - }) -} - - -exports ['emit error thrown'] = function (test) { - - var err = new Error('INTENSIONAL ERROR') - , mapper = - es.map(function () { - throw err - }) - - mapper.on('error', function (_err) { - it(_err).equal(err) - test.done() - }) - -// onExit(spec(mapper).basic().validate) -//need spec that says stream may error. - - mapper.write('hello') - -} - -exports ['emit error calledback'] = function (test) { - - var err = new Error('INTENSIONAL ERROR') - , mapper = - es.map(function (data, callback) { - callback(err) - }) - - mapper.on('error', function (_err) { - it(_err).equal(err) - test.done() - }) - - mapper.write('hello') - -} - -exports ['do not emit drain if not paused'] = function (test) { - - var map = es.map(function (data, callback) { - u.delay(callback)(null, 1) - return true - }) - - spec(map).through().pausable().validateOnExit() - - map.on('drain', function () { - it(false).ok('should not emit drain unless the stream is paused') - }) - - it(map.write('hello')).equal(true) - it(map.write('hello')).equal(true) - it(map.write('hello')).equal(true) - setTimeout(function () {map.end()},10) - map.on('end', test.done) -} - -exports ['emits drain if paused, when all '] = function (test) { - var active = 0 - var drained = false - var map = es.map(function (data, callback) { - active ++ - u.delay(function () { - active -- - callback(null, 1) - })() - console.log('WRITE', false) - return false - }) - - spec(map).through().validateOnExit() - - map.on('drain', function () { - drained = true - it(active).equal(0, 'should emit drain when all maps are done') - }) - - it(map.write('hello')).equal(false) - it(map.write('hello')).equal(false) - it(map.write('hello')).equal(false) - - process.nextTick(function () {map.end()},10) - - map.on('end', function () { - console.log('end') - it(drained).ok('shoud have emitted drain before end') - test.done() - }) - -} - -exports ['map applied to a stream with filtering'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - - var doubler = es.map(function (data, callback) { - if (data % 2) - callback(null, data * 2) - else - callback() - }) - - readStream(doubler, function (err, output) { - it(output).deepEqual(input.filter(function (j) { - return j % 2 - }).map(function (j) { - return j * 2 - })) - test.done() - }) - - spec(doubler).through().validateOnExit() - - writeArray(input, doubler) - -} - -exports ['simple mapSync applied to a stream'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - - var doubler = es.mapSync(function (data) { - return data * 2 - }) - - readStream(doubler, function (err, output) { - it(output).deepEqual(input.map(function (j) { - return j * 2 - })) - test.done() - }) - - spec(doubler).through().validateOnExit() - - writeArray(input, doubler) - -} - -exports ['mapSync applied to a stream with filtering'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - - var doubler = es.mapSync(function (data) { - if (data % 2) - return data * 2 - }) - - readStream(doubler, function (err, output) { - it(output).deepEqual(input.filter(function (j) { - return j % 2 - }).map(function (j) { - return j * 2 - })) - test.done() - }) - - spec(doubler).through().validateOnExit() - - writeArray(input, doubler) - -} - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/spec.asynct.js b/reverse_engineering/node_modules/event-stream/test/spec.asynct.js deleted file mode 100644 index 6d5fb6b..0000000 --- a/reverse_engineering/node_modules/event-stream/test/spec.asynct.js +++ /dev/null @@ -1,86 +0,0 @@ -/* - assert that data is called many times - assert that end is called eventually - - assert that when stream enters pause state, - on drain is emitted eventually. -*/ - -var es = require('..') -var it = require('it-is').style('colour') -var spec = require('stream-spec') - -exports['simple stream'] = function (test) { - - var stream = es.through() - var x = spec(stream).basic().pausable() - - stream.write(1) - stream.write(1) - stream.pause() - stream.write(1) - stream.resume() - stream.write(1) - stream.end(2) //this will call write() - - process.nextTick(function (){ - x.validate() - test.done() - }) -} - -exports['throw on write when !writable'] = function (test) { - - var stream = es.through() - var x = spec(stream).basic().pausable() - - stream.write(1) - stream.write(1) - stream.end(2) //this will call write() - stream.write(1) //this will be throwing..., but the spec will catch it. - - process.nextTick(function () { - x.validate() - test.done() - }) - -} - -exports['end fast'] = function (test) { - - var stream = es.through() - var x = spec(stream).basic().pausable() - - stream.end() //this will call write() - - process.nextTick(function () { - x.validate() - test.done() - }) - -} - - -/* - okay, that was easy enough, whats next? - - say, after you call paused(), write should return false - until resume is called. - - simple way to implement this: - write must return !paused - after pause() paused = true - after resume() paused = false - - on resume, if !paused drain is emitted again. - after drain, !paused - - there are lots of subtle ordering bugs in streams. - - example, set !paused before emitting drain. - - the stream api is stateful. -*/ - - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/split.asynct.js b/reverse_engineering/node_modules/event-stream/test/split.asynct.js deleted file mode 100644 index 7d44bac..0000000 --- a/reverse_engineering/node_modules/event-stream/test/split.asynct.js +++ /dev/null @@ -1,47 +0,0 @@ -var es = require('../') - , it = require('it-is').style('colour') - , d = require('ubelt') - , join = require('path').join - , fs = require('fs') - , Stream = require('stream').Stream - , spec = require('stream-spec') - -exports ['es.split() works like String#split'] = function (test) { - var readme = join(__filename) - , expected = fs.readFileSync(readme, 'utf-8').split('\n') - , cs = es.split() - , actual = [] - , ended = false - , x = spec(cs).through() - - var a = new Stream () - - a.write = function (l) { - actual.push(l.trim()) - } - a.end = function () { - - ended = true - expected.forEach(function (v,k) { - //String.split will append an empty string '' - //if the string ends in a split pattern. - //es.split doesn't which was breaking this test. - //clearly, appending the empty string is correct. - //tests are passing though. which is the current job. - if(v) - it(actual[k]).like(v) - }) - //give the stream time to close - process.nextTick(function () { - test.done() - x.validate() - }) - } - a.writable = true - - fs.createReadStream(readme, {flags: 'r'}).pipe(cs) - cs.pipe(a) - -} - -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/stringify.js b/reverse_engineering/node_modules/event-stream/test/stringify.js deleted file mode 100644 index d158185..0000000 --- a/reverse_engineering/node_modules/event-stream/test/stringify.js +++ /dev/null @@ -1,15 +0,0 @@ - - - -var es = require('../') - -exports['handle buffer'] = function (t) { - - - es.stringify().on('data', function (d) { - t.equal(d.trim(), JSON.stringify('HELLO')) - t.end() - }).write(new Buffer('HELLO')) - -} -require('./helper')(module) diff --git a/reverse_engineering/node_modules/event-stream/test/writeArray.asynct.js b/reverse_engineering/node_modules/event-stream/test/writeArray.asynct.js deleted file mode 100644 index 5d705de..0000000 --- a/reverse_engineering/node_modules/event-stream/test/writeArray.asynct.js +++ /dev/null @@ -1,31 +0,0 @@ - -var es = require('../') - , it = require('it-is').style('colour') - , d = require('ubelt') - -exports ['write an array'] = function (test) { - - var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 - - var writer = es.writeArray(function (err, array){ - if(err) throw err //unpossible - it(array).deepEqual(readThis) - test.done() - }) - - d.each(readThis, writer.write.bind(writer)) - writer.end() - -} - - -exports ['writer is writable, but not readable'] = function (test) { - var reader = es.writeArray(function () {}) - it(reader).has({ - readable: false, - writable: true - }) - - test.done() -} -require('./helper')(module) diff --git a/reverse_engineering/node_modules/find-up/index.d.ts b/reverse_engineering/node_modules/find-up/index.d.ts deleted file mode 100644 index 41e3192..0000000 --- a/reverse_engineering/node_modules/find-up/index.d.ts +++ /dev/null @@ -1,137 +0,0 @@ -import {Options as LocatePathOptions} from 'locate-path'; - -declare const stop: unique symbol; - -declare namespace findUp { - interface Options extends LocatePathOptions {} - - type StopSymbol = typeof stop; - - type Match = string | StopSymbol | undefined; -} - -declare const findUp: { - /** - Find a file or directory by walking up parent directories. - - @param name - Name of the file or directory to find. Can be multiple. - @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. - - @example - ``` - // / - // └── Users - // └── sindresorhus - // ├── unicorn.png - // └── foo - // └── bar - // ├── baz - // └── example.js - - // example.js - import findUp = require('find-up'); - - (async () => { - console.log(await findUp('unicorn.png')); - //=> '/Users/sindresorhus/unicorn.png' - - console.log(await findUp(['rainbow.png', 'unicorn.png'])); - //=> '/Users/sindresorhus/unicorn.png' - })(); - ``` - */ - (name: string | string[], options?: findUp.Options): Promise; - - /** - Find a file or directory by walking up parent directories. - - @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. - @returns The first path found or `undefined` if none could be found. - - @example - ``` - import path = require('path'); - import findUp = require('find-up'); - - (async () => { - console.log(await findUp(async directory => { - const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); - return hasUnicorns && directory; - }, {type: 'directory'})); - //=> '/Users/sindresorhus' - })(); - ``` - */ - (matcher: (directory: string) => (findUp.Match | Promise), options?: findUp.Options): Promise; - - sync: { - /** - Synchronously find a file or directory by walking up parent directories. - - @param name - Name of the file or directory to find. Can be multiple. - @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. - */ - (name: string | string[], options?: findUp.Options): string | undefined; - - /** - Synchronously find a file or directory by walking up parent directories. - - @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. - @returns The first path found or `undefined` if none could be found. - - @example - ``` - import path = require('path'); - import findUp = require('find-up'); - - console.log(findUp.sync(directory => { - const hasUnicorns = findUp.sync.exists(path.join(directory, 'unicorn.png')); - return hasUnicorns && directory; - }, {type: 'directory'})); - //=> '/Users/sindresorhus' - ``` - */ - (matcher: (directory: string) => findUp.Match, options?: findUp.Options): string | undefined; - - /** - Synchronously check if a path exists. - - @param path - Path to the file or directory. - @returns Whether the path exists. - - @example - ``` - import findUp = require('find-up'); - - console.log(findUp.sync.exists('/Users/sindresorhus/unicorn.png')); - //=> true - ``` - */ - exists(path: string): boolean; - } - - /** - Check if a path exists. - - @param path - Path to a file or directory. - @returns Whether the path exists. - - @example - ``` - import findUp = require('find-up'); - - (async () => { - console.log(await findUp.exists('/Users/sindresorhus/unicorn.png')); - //=> true - })(); - ``` - */ - exists(path: string): Promise; - - /** - Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`. - */ - readonly stop: findUp.StopSymbol; -}; - -export = findUp; diff --git a/reverse_engineering/node_modules/find-up/index.js b/reverse_engineering/node_modules/find-up/index.js deleted file mode 100644 index ce564e5..0000000 --- a/reverse_engineering/node_modules/find-up/index.js +++ /dev/null @@ -1,89 +0,0 @@ -'use strict'; -const path = require('path'); -const locatePath = require('locate-path'); -const pathExists = require('path-exists'); - -const stop = Symbol('findUp.stop'); - -module.exports = async (name, options = {}) => { - let directory = path.resolve(options.cwd || ''); - const {root} = path.parse(directory); - const paths = [].concat(name); - - const runMatcher = async locateOptions => { - if (typeof name !== 'function') { - return locatePath(paths, locateOptions); - } - - const foundPath = await name(locateOptions.cwd); - if (typeof foundPath === 'string') { - return locatePath([foundPath], locateOptions); - } - - return foundPath; - }; - - // eslint-disable-next-line no-constant-condition - while (true) { - // eslint-disable-next-line no-await-in-loop - const foundPath = await runMatcher({...options, cwd: directory}); - - if (foundPath === stop) { - return; - } - - if (foundPath) { - return path.resolve(directory, foundPath); - } - - if (directory === root) { - return; - } - - directory = path.dirname(directory); - } -}; - -module.exports.sync = (name, options = {}) => { - let directory = path.resolve(options.cwd || ''); - const {root} = path.parse(directory); - const paths = [].concat(name); - - const runMatcher = locateOptions => { - if (typeof name !== 'function') { - return locatePath.sync(paths, locateOptions); - } - - const foundPath = name(locateOptions.cwd); - if (typeof foundPath === 'string') { - return locatePath.sync([foundPath], locateOptions); - } - - return foundPath; - }; - - // eslint-disable-next-line no-constant-condition - while (true) { - const foundPath = runMatcher({...options, cwd: directory}); - - if (foundPath === stop) { - return; - } - - if (foundPath) { - return path.resolve(directory, foundPath); - } - - if (directory === root) { - return; - } - - directory = path.dirname(directory); - } -}; - -module.exports.exists = pathExists; - -module.exports.sync.exists = pathExists.sync; - -module.exports.stop = stop; diff --git a/reverse_engineering/node_modules/find-up/license b/reverse_engineering/node_modules/find-up/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/find-up/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/find-up/package.json b/reverse_engineering/node_modules/find-up/package.json deleted file mode 100644 index cd50281..0000000 --- a/reverse_engineering/node_modules/find-up/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "find-up", - "version": "4.1.0", - "description": "Find a file or directory by walking up parent directories", - "license": "MIT", - "repository": "sindresorhus/find-up", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "find", - "up", - "find-up", - "findup", - "look-up", - "look", - "file", - "search", - "match", - "package", - "resolve", - "parent", - "parents", - "folder", - "directory", - "walk", - "walking", - "path" - ], - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "devDependencies": { - "ava": "^2.1.0", - "is-path-inside": "^2.1.0", - "tempy": "^0.3.0", - "tsd": "^0.7.3", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/find-up/readme.md b/reverse_engineering/node_modules/find-up/readme.md deleted file mode 100644 index d6a21e5..0000000 --- a/reverse_engineering/node_modules/find-up/readme.md +++ /dev/null @@ -1,156 +0,0 @@ -# find-up [![Build Status](https://travis-ci.org/sindresorhus/find-up.svg?branch=master)](https://travis-ci.org/sindresorhus/find-up) - -> Find a file or directory by walking up parent directories - - -## Install - -``` -$ npm install find-up -``` - - -## Usage - -``` -/ -└── Users - └── sindresorhus - ├── unicorn.png - └── foo - └── bar - ├── baz - └── example.js -``` - -`example.js` - -```js -const path = require('path'); -const findUp = require('find-up'); - -(async () => { - console.log(await findUp('unicorn.png')); - //=> '/Users/sindresorhus/unicorn.png' - - console.log(await findUp(['rainbow.png', 'unicorn.png'])); - //=> '/Users/sindresorhus/unicorn.png' - - console.log(await findUp(async directory => { - const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); - return hasUnicorns && directory; - }, {type: 'directory'})); - //=> '/Users/sindresorhus' -})(); -``` - - -## API - -### findUp(name, options?) -### findUp(matcher, options?) - -Returns a `Promise` for either the path or `undefined` if it couldn't be found. - -### findUp([...name], options?) - -Returns a `Promise` for either the first path found (by respecting the order of the array) or `undefined` if none could be found. - -### findUp.sync(name, options?) -### findUp.sync(matcher, options?) - -Returns a path or `undefined` if it couldn't be found. - -### findUp.sync([...name], options?) - -Returns the first path found (by respecting the order of the array) or `undefined` if none could be found. - -#### name - -Type: `string` - -Name of the file or directory to find. - -#### matcher - -Type: `Function` - -A function that will be called with each directory until it returns a `string` with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases. - -When using async mode, the `matcher` may optionally be an async or promise-returning function that returns the path. - -#### options - -Type: `object` - -##### cwd - -Type: `string`
-Default: `process.cwd()` - -Directory to start from. - -##### type - -Type: `string`
-Default: `'file'`
-Values: `'file'` `'directory'` - -The type of paths that can match. - -##### allowSymlinks - -Type: `boolean`
-Default: `true` - -Allow symbolic links to match if they point to the chosen path type. - -### findUp.exists(path) - -Returns a `Promise` of whether the path exists. - -### findUp.sync.exists(path) - -Returns a `boolean` of whether the path exists. - -#### path - -Type: `string` - -Path to a file or directory. - -### findUp.stop - -A [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that can be returned by a `matcher` function to stop the search and cause `findUp` to immediately return `undefined`. Useful as a performance optimization in case the current working directory is deeply nested in the filesystem. - -```js -const path = require('path'); -const findUp = require('find-up'); - -(async () => { - await findUp(directory => { - return path.basename(directory) === 'work' ? findUp.stop : 'logo.png'; - }); -})(); -``` - - -## Related - -- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module -- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file -- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package -- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path - - ---- - -
- - Get professional support for 'find-up' with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/reverse_engineering/node_modules/from/.npmignore b/reverse_engineering/node_modules/from/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/reverse_engineering/node_modules/from/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/reverse_engineering/node_modules/from/.travis.yml b/reverse_engineering/node_modules/from/.travis.yml deleted file mode 100644 index 76db03f..0000000 --- a/reverse_engineering/node_modules/from/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - "node" - - "6" - - "5" - - "4" diff --git a/reverse_engineering/node_modules/from/LICENSE.APACHE2 b/reverse_engineering/node_modules/from/LICENSE.APACHE2 deleted file mode 100644 index 6366c04..0000000 --- a/reverse_engineering/node_modules/from/LICENSE.APACHE2 +++ /dev/null @@ -1,15 +0,0 @@ -Apache License, Version 2.0 - -Copyright (c) 2011 Dominic Tarr - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/reverse_engineering/node_modules/from/LICENSE.MIT b/reverse_engineering/node_modules/from/LICENSE.MIT deleted file mode 100644 index 6eafbd7..0000000 --- a/reverse_engineering/node_modules/from/LICENSE.MIT +++ /dev/null @@ -1,24 +0,0 @@ -The MIT License - -Copyright (c) 2011 Dominic Tarr - -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom -the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/from/index.js b/reverse_engineering/node_modules/from/index.js deleted file mode 100644 index e3e7bfd..0000000 --- a/reverse_engineering/node_modules/from/index.js +++ /dev/null @@ -1,68 +0,0 @@ - -'use strict'; - -var Stream = require('stream') - -// from -// -// a stream that reads from an source. -// source may be an array, or a function. -// from handles pause behaviour for you. - -module.exports = -function from (source) { - if(Array.isArray(source)) { - var source_index = 0, source_len = source.length; - return from (function (i) { - if(source_index < source_len) - this.emit('data', source[source_index++]) - else - this.emit('end') - return true - }) - } - var s = new Stream(), i = 0 - s.ended = false - s.started = false - s.readable = true - s.writable = false - s.paused = false - s.ended = false - s.pause = function () { - s.started = true - s.paused = true - } - function next () { - s.started = true - if(s.ended) return - while(!s.ended && !s.paused && source.call(s, i++, function () { - if(!s.ended && !s.paused) - process.nextTick(next); - })) - ; - } - s.resume = function () { - s.started = true - s.paused = false - next() - } - s.on('end', function () { - s.ended = true - s.readable = false - process.nextTick(s.destroy) - }) - s.destroy = function () { - s.ended = true - s.emit('close') - } - /* - by default, the stream will start emitting at nextTick - if you want, you can pause it, after pipeing. - you can also resume before next tick, and that will also - work. - */ - process.nextTick(function () { - if(!s.started) s.resume() - }) - return s -} diff --git a/reverse_engineering/node_modules/from/package.json b/reverse_engineering/node_modules/from/package.json deleted file mode 100644 index a265d84..0000000 --- a/reverse_engineering/node_modules/from/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "from", - "version": "0.1.7", - "description": "Easy way to make a Readable Stream", - "main": "index.js", - "scripts": { - "test": "asynct test/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/dominictarr/from.git" - }, - "keywords": [ - "stream", - "streams", - "readable", - "easy" - ], - "devDependencies": { - "asynct": "1", - "stream-spec": "0", - "assertions": "~2.3.0" - }, - "author": "Dominic Tarr (dominictarr.com)", - "license": "MIT" -} diff --git a/reverse_engineering/node_modules/from/readme.markdown b/reverse_engineering/node_modules/from/readme.markdown deleted file mode 100644 index c84fc9b..0000000 --- a/reverse_engineering/node_modules/from/readme.markdown +++ /dev/null @@ -1,40 +0,0 @@ -[![TravisCI Build Status](https://travis-ci.org/nmhnmh/from.svg?branch=master)](https://travis-ci.org/nmhnmh/from) - -# from - -An easy way to create a `readable Stream`. - -## from(function getChunk(count, next)) - -from takes a `getChunk` function and returns a stream. - -`getChunk` is called again and again, after each time the user calls `next()`, -until the user emits `'end'` - -if `pause()` is called, the `getChunk` won't be called again untill `resume()` is called. - - -```js -var from = require('from') - -var stream = - from(function getChunk(count, next) { - //do some sort of data - this.emit('data', whatever) - - if(itsOver) - this.emit('end') - - //ready to handle the next chunk - next() - //or, if it's sync: - return true - }) -``` - -## from(array) - -from also takes an `Array` whose elements it emits one after another. - -## License -MIT / Apache2 diff --git a/reverse_engineering/node_modules/from/test/index.js b/reverse_engineering/node_modules/from/test/index.js deleted file mode 100644 index 5e2f161..0000000 --- a/reverse_engineering/node_modules/from/test/index.js +++ /dev/null @@ -1,210 +0,0 @@ -var from = require('..') -var spec = require('stream-spec') -var a = require('assertions') - -function read(stream, callback) { - var actual = [] - stream.on('data', function (data) { - actual.push(data) - }) - stream.once('end', function () { - callback(null, actual) - }) - stream.once('error', function (err) { - callback(err) - }) -} - -function pause(stream) { - stream.on('data', function () { - if(Math.random() > 0.1) return - stream.pause() - process.nextTick(function () { - stream.resume() - }) - }) -} - -exports['inc'] = function (test) { - - var fs = from(function (i) { - this.emit('data', i) - if(i >= 99) - return this.emit('end') - return true - }) - - spec(fs).readable().validateOnExit() - - read(fs, function (err, arr) { - test.equal(arr.length, 100) - test.done() - }) -} - -exports['inc - async'] = function (test) { - - var fs = from(function (i, next) { - this.emit('data', i) - if(i >= 99) - return this.emit('end') - next(); - }) - - spec(fs).readable().validateOnExit() - - read(fs, function (err, arr) { - test.equal(arr.length, 100) - test.done() - }) -} - -exports['large stream - from an array'] = function (test) { - - var l = 100000 - , expected = [] - - while(l--) expected.push(l * Math.random()) - - var fs = from(expected.slice()) - - spec(fs).readable().validateOnExit() - - read(fs, function (err, arr) { - a.deepEqual(arr, expected) - test.done() - }) -} - -exports['large stream - callback return true'] = function (test) { - - var fs = from(function (i, next) { - this.emit('data', i) - if(i >= 99999) - return this.emit('end') - return true; - }) - - spec(fs).readable().validateOnExit() - - read(fs, function (err, arr) { - test.equal(arr.length, 100000) - test.done() - }) -} - -exports['large stream - callback call next()'] = function (test) { - - var fs = from(function (i, next) { - this.emit('data', i) - if(i >= 99999) - return this.emit('end') - next(); - }) - - spec(fs).readable().validateOnExit() - - read(fs, function (err, arr) { - test.equal(arr.length, 100000) - test.done() - }) -} - -exports['simple'] = function (test) { - - var l = 1000 - , expected = [] - - while(l--) expected.push(l * Math.random()) - - var t = from(expected.slice()) - - spec(t) - .readable() - .pausable({strict: true}) - .validateOnExit() - - read(t, function (err, actual) { - if(err) test.error(err) //fail - a.deepEqual(actual, expected) - test.done() - }) - -} - -exports['simple pausable'] = function (test) { - - var l = 1000 - , expected = [] - - while(l--) expected.push(l * Math.random()) - - var t = from(expected.slice()) - - spec(t) - .readable() - .pausable({strict: true}) - .validateOnExit() - - pause(t) - - read(t, function (err, actual) { - if(err) test.error(err) //fail - a.deepEqual(actual, expected) - test.done() - }) - -} - -exports['simple (not strictly pausable) setTimeout'] = function (test) { - - var l = 10 - , expected = [] - while(l--) expected.push(l * Math.random()) - - - var _expected = expected.slice() - var t = from(function (i, n) { - var self = this - setTimeout(function () { - if(_expected.length) - self.emit('data', _expected.shift()) - else - if(!self.ended) - self.emit('end') - n() - }, 3) - }) - - /* - using from in this way will not be strictly pausable. - it could be extended to buffer outputs, but I think a better - way would be to use a PauseStream that implements strict pause. - */ - - spec(t) - .readable() - .pausable({strict: false }) - .validateOnExit() - - //pause(t) - var paused = false - var i = setInterval(function () { - if(!paused) t.pause() - else t.resume() - paused = !paused - }, 2) - - t.on('end', function () { - clearInterval(i) - }) - - read(t, function (err, actual) { - if(err) test.error(err) //fail - a.deepEqual(actual, expected) - test.done() - }) - -} - - diff --git a/reverse_engineering/node_modules/get-caller-file/LICENSE.md b/reverse_engineering/node_modules/get-caller-file/LICENSE.md deleted file mode 100644 index bf3e1c0..0000000 --- a/reverse_engineering/node_modules/get-caller-file/LICENSE.md +++ /dev/null @@ -1,6 +0,0 @@ -ISC License (ISC) -Copyright 2018 Stefan Penner - -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/get-caller-file/README.md b/reverse_engineering/node_modules/get-caller-file/README.md deleted file mode 100644 index a7d8c07..0000000 --- a/reverse_engineering/node_modules/get-caller-file/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# get-caller-file - -[![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) -[![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) - -This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. - -Inspired by http://stackoverflow.com/questions/13227489 - -*note: this relies on Node/V8 specific APIs, as such other runtimes may not work* - -## Installation - -```bash -yarn add get-caller-file -``` - -## Usage - -Given: - -```js -// ./foo.js -const getCallerFile = require('get-caller-file'); - -module.exports = function() { - return getCallerFile(); // figures out who called it -}; -``` - -```js -// index.js -const foo = require('./foo'); - -foo() // => /full/path/to/this/file/index.js -``` - - -## Options: - -* `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. diff --git a/reverse_engineering/node_modules/get-caller-file/index.d.ts b/reverse_engineering/node_modules/get-caller-file/index.d.ts deleted file mode 100644 index babed69..0000000 --- a/reverse_engineering/node_modules/get-caller-file/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _default: (position?: number) => any; -export = _default; diff --git a/reverse_engineering/node_modules/get-caller-file/index.js b/reverse_engineering/node_modules/get-caller-file/index.js deleted file mode 100644 index 57304f8..0000000 --- a/reverse_engineering/node_modules/get-caller-file/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -// Call this function in a another function to find out the file from -// which that function was called from. (Inspects the v8 stack trace) -// -// Inspired by http://stackoverflow.com/questions/13227489 -module.exports = function getCallerFile(position) { - if (position === void 0) { position = 2; } - if (position >= Error.stackTraceLimit) { - throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); - } - var oldPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = function (_, stack) { return stack; }; - var stack = new Error().stack; - Error.prepareStackTrace = oldPrepareStackTrace; - if (stack !== null && typeof stack === 'object') { - // stack[0] holds this file - // stack[1] holds where this function was called - // stack[2] holds the file we're interested in - return stack[position] ? stack[position].getFileName() : undefined; - } -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/get-caller-file/index.js.map b/reverse_engineering/node_modules/get-caller-file/index.js.map deleted file mode 100644 index 89c655c..0000000 --- a/reverse_engineering/node_modules/get-caller-file/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA,qEAAqE;AACrE,qEAAqE;AACrE,EAAE;AACF,0DAA0D;AAE1D,iBAAS,SAAS,aAAa,CAAC,QAAY;IAAZ,yBAAA,EAAA,YAAY;IAC1C,IAAI,QAAQ,IAAI,KAAK,CAAC,eAAe,EAAE;QACrC,MAAM,IAAI,SAAS,CAAC,kGAAkG,GAAG,QAAQ,GAAG,oCAAoC,GAAG,KAAK,CAAC,eAAe,GAAG,GAAG,CAAC,CAAC;KACzM;IAED,IAAM,oBAAoB,GAAG,KAAK,CAAC,iBAAiB,CAAC;IACrD,KAAK,CAAC,iBAAiB,GAAG,UAAC,CAAC,EAAE,KAAK,IAAM,OAAA,KAAK,EAAL,CAAK,CAAC;IAC/C,IAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,KAAK,CAAC;IAChC,KAAK,CAAC,iBAAiB,GAAG,oBAAoB,CAAC;IAG/C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC/C,2BAA2B;QAC3B,gDAAgD;QAChD,8CAA8C;QAC9C,OAAO,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAE,KAAK,CAAC,QAAQ,CAAS,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;KAC7E;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/get-caller-file/package.json b/reverse_engineering/node_modules/get-caller-file/package.json deleted file mode 100644 index b0dd571..0000000 --- a/reverse_engineering/node_modules/get-caller-file/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "get-caller-file", - "version": "2.0.5", - "description": "", - "main": "index.js", - "directories": { - "test": "tests" - }, - "files": [ - "index.js", - "index.js.map", - "index.d.ts" - ], - "scripts": { - "prepare": "tsc", - "test": "mocha test", - "test:debug": "mocha test" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/stefanpenner/get-caller-file.git" - }, - "author": "Stefan Penner", - "license": "ISC", - "bugs": { - "url": "https://github.com/stefanpenner/get-caller-file/issues" - }, - "homepage": "https://github.com/stefanpenner/get-caller-file#readme", - "devDependencies": { - "@types/chai": "^4.1.7", - "@types/ensure-posix-path": "^1.0.0", - "@types/mocha": "^5.2.6", - "@types/node": "^11.10.5", - "chai": "^4.1.2", - "ensure-posix-path": "^1.0.1", - "mocha": "^5.2.0", - "typescript": "^3.3.3333" - }, - "engines": { - "node": "6.* || 8.* || >= 10.*" - } -} diff --git a/reverse_engineering/node_modules/ieee754/LICENSE b/reverse_engineering/node_modules/ieee754/LICENSE deleted file mode 100644 index 5aac82c..0000000 --- a/reverse_engineering/node_modules/ieee754/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -Copyright 2008 Fair Oaks Labs, Inc. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/reverse_engineering/node_modules/ieee754/README.md b/reverse_engineering/node_modules/ieee754/README.md deleted file mode 100644 index cb7527b..0000000 --- a/reverse_engineering/node_modules/ieee754/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg -[travis-url]: https://travis-ci.org/feross/ieee754 -[npm-image]: https://img.shields.io/npm/v/ieee754.svg -[npm-url]: https://npmjs.org/package/ieee754 -[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg -[downloads-url]: https://npmjs.org/package/ieee754 -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -[![saucelabs][saucelabs-image]][saucelabs-url] - -[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg -[saucelabs-url]: https://saucelabs.com/u/ieee754 - -### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. - -## install - -``` -npm install ieee754 -``` - -## methods - -`var ieee754 = require('ieee754')` - -The `ieee754` object has the following functions: - -``` -ieee754.read = function (buffer, offset, isLE, mLen, nBytes) -ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) -``` - -The arguments mean the following: - -- buffer = the buffer -- offset = offset into the buffer -- value = value to set (only for `write`) -- isLe = is little endian? -- mLen = mantissa length -- nBytes = number of bytes - -## what is ieee754? - -The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). - -## license - -BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. diff --git a/reverse_engineering/node_modules/ieee754/index.d.ts b/reverse_engineering/node_modules/ieee754/index.d.ts deleted file mode 100644 index f1e4354..0000000 --- a/reverse_engineering/node_modules/ieee754/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare namespace ieee754 { - export function read( - buffer: Uint8Array, offset: number, isLE: boolean, mLen: number, - nBytes: number): number; - export function write( - buffer: Uint8Array, value: number, offset: number, isLE: boolean, - mLen: number, nBytes: number): void; - } - - export = ieee754; \ No newline at end of file diff --git a/reverse_engineering/node_modules/ieee754/index.js b/reverse_engineering/node_modules/ieee754/index.js deleted file mode 100644 index 81d26c3..0000000 --- a/reverse_engineering/node_modules/ieee754/index.js +++ /dev/null @@ -1,85 +0,0 @@ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 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 << eLen) - 1 - var eBias = eMax >> 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 & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} diff --git a/reverse_engineering/node_modules/ieee754/package.json b/reverse_engineering/node_modules/ieee754/package.json deleted file mode 100644 index 7b23851..0000000 --- a/reverse_engineering/node_modules/ieee754/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "ieee754", - "description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object", - "version": "1.2.1", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "https://feross.org" - }, - "contributors": [ - "Romain Beauxis " - ], - "devDependencies": { - "airtap": "^3.0.0", - "standard": "*", - "tape": "^5.0.1" - }, - "keywords": [ - "IEEE 754", - "buffer", - "convert", - "floating point", - "ieee754" - ], - "license": "BSD-3-Clause", - "main": "index.js", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "git://github.com/feross/ieee754.git" - }, - "scripts": { - "test": "standard && npm run test-node && npm run test-browser", - "test-browser": "airtap -- test/*.js", - "test-browser-local": "airtap --local -- test/*.js", - "test-node": "tape test/*.js" - }, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] -} diff --git a/reverse_engineering/node_modules/inherits/LICENSE b/reverse_engineering/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/reverse_engineering/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/reverse_engineering/node_modules/inherits/README.md b/reverse_engineering/node_modules/inherits/README.md deleted file mode 100644 index b1c5665..0000000 --- a/reverse_engineering/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/reverse_engineering/node_modules/inherits/inherits.js b/reverse_engineering/node_modules/inherits/inherits.js deleted file mode 100644 index f71f2d9..0000000 --- a/reverse_engineering/node_modules/inherits/inherits.js +++ /dev/null @@ -1,9 +0,0 @@ -try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = require('./inherits_browser.js'); -} diff --git a/reverse_engineering/node_modules/inherits/inherits_browser.js b/reverse_engineering/node_modules/inherits/inherits_browser.js deleted file mode 100644 index 86bbb3d..0000000 --- a/reverse_engineering/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,27 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} diff --git a/reverse_engineering/node_modules/inherits/package.json b/reverse_engineering/node_modules/inherits/package.json deleted file mode 100644 index 37b4366..0000000 --- a/reverse_engineering/node_modules/inherits/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.4", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": "git://github.com/isaacs/inherits", - "license": "ISC", - "scripts": { - "test": "tap" - }, - "devDependencies": { - "tap": "^14.2.4" - }, - "files": [ - "inherits.js", - "inherits_browser.js" - ] -} diff --git a/reverse_engineering/node_modules/is-fullwidth-code-point/index.d.ts b/reverse_engineering/node_modules/is-fullwidth-code-point/index.d.ts deleted file mode 100644 index 729d202..0000000 --- a/reverse_engineering/node_modules/is-fullwidth-code-point/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** -Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms). - -@param codePoint - The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. - -@example -``` -import isFullwidthCodePoint from 'is-fullwidth-code-point'; - -isFullwidthCodePoint('谢'.codePointAt(0)); -//=> true - -isFullwidthCodePoint('a'.codePointAt(0)); -//=> false -``` -*/ -export default function isFullwidthCodePoint(codePoint: number): boolean; diff --git a/reverse_engineering/node_modules/is-fullwidth-code-point/index.js b/reverse_engineering/node_modules/is-fullwidth-code-point/index.js deleted file mode 100644 index 671f97f..0000000 --- a/reverse_engineering/node_modules/is-fullwidth-code-point/index.js +++ /dev/null @@ -1,50 +0,0 @@ -/* eslint-disable yoda */ -'use strict'; - -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } - - return false; -}; - -module.exports = isFullwidthCodePoint; -module.exports.default = isFullwidthCodePoint; diff --git a/reverse_engineering/node_modules/is-fullwidth-code-point/license b/reverse_engineering/node_modules/is-fullwidth-code-point/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/is-fullwidth-code-point/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/is-fullwidth-code-point/package.json b/reverse_engineering/node_modules/is-fullwidth-code-point/package.json deleted file mode 100644 index 2137e88..0000000 --- a/reverse_engineering/node_modules/is-fullwidth-code-point/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "is-fullwidth-code-point", - "version": "3.0.0", - "description": "Check if the character represented by a given Unicode code point is fullwidth", - "license": "MIT", - "repository": "sindresorhus/is-fullwidth-code-point", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd-check" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "fullwidth", - "full-width", - "full", - "width", - "unicode", - "character", - "string", - "codepoint", - "code", - "point", - "is", - "detect", - "check" - ], - "devDependencies": { - "ava": "^1.3.1", - "tsd-check": "^0.5.0", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/is-fullwidth-code-point/readme.md b/reverse_engineering/node_modules/is-fullwidth-code-point/readme.md deleted file mode 100644 index 4236bba..0000000 --- a/reverse_engineering/node_modules/is-fullwidth-code-point/readme.md +++ /dev/null @@ -1,39 +0,0 @@ -# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) - -> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) - - -## Install - -``` -$ npm install is-fullwidth-code-point -``` - - -## Usage - -```js -const isFullwidthCodePoint = require('is-fullwidth-code-point'); - -isFullwidthCodePoint('谢'.codePointAt(0)); -//=> true - -isFullwidthCodePoint('a'.codePointAt(0)); -//=> false -``` - - -## API - -### isFullwidthCodePoint(codePoint) - -#### codePoint - -Type: `number` - -The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/reverse_engineering/node_modules/isarray/.npmignore b/reverse_engineering/node_modules/isarray/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/reverse_engineering/node_modules/isarray/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/reverse_engineering/node_modules/isarray/.travis.yml b/reverse_engineering/node_modules/isarray/.travis.yml deleted file mode 100644 index cc4dba2..0000000 --- a/reverse_engineering/node_modules/isarray/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" diff --git a/reverse_engineering/node_modules/isarray/Makefile b/reverse_engineering/node_modules/isarray/Makefile deleted file mode 100644 index 787d56e..0000000 --- a/reverse_engineering/node_modules/isarray/Makefile +++ /dev/null @@ -1,6 +0,0 @@ - -test: - @node_modules/.bin/tape test.js - -.PHONY: test - diff --git a/reverse_engineering/node_modules/isarray/README.md b/reverse_engineering/node_modules/isarray/README.md deleted file mode 100644 index 16d2c59..0000000 --- a/reverse_engineering/node_modules/isarray/README.md +++ /dev/null @@ -1,60 +0,0 @@ - -# isarray - -`Array#isArray` for older browsers. - -[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) -[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) - -[![browser support](https://ci.testling.com/juliangruber/isarray.png) -](https://ci.testling.com/juliangruber/isarray) - -## Usage - -```js -var isArray = require('isarray'); - -console.log(isArray([])); // => true -console.log(isArray({})); // => false -``` - -## Installation - -With [npm](http://npmjs.org) do - -```bash -$ npm install isarray -``` - -Then bundle for the browser with -[browserify](https://github.com/substack/browserify). - -With [component](http://component.io) do - -```bash -$ component install juliangruber/isarray -``` - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/isarray/component.json b/reverse_engineering/node_modules/isarray/component.json deleted file mode 100644 index 9e31b68..0000000 --- a/reverse_engineering/node_modules/isarray/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name" : "isarray", - "description" : "Array#isArray for older browsers", - "version" : "0.0.1", - "repository" : "juliangruber/isarray", - "homepage": "https://github.com/juliangruber/isarray", - "main" : "index.js", - "scripts" : [ - "index.js" - ], - "dependencies" : {}, - "keywords": ["browser","isarray","array"], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT" -} diff --git a/reverse_engineering/node_modules/isarray/index.js b/reverse_engineering/node_modules/isarray/index.js deleted file mode 100644 index a57f634..0000000 --- a/reverse_engineering/node_modules/isarray/index.js +++ /dev/null @@ -1,5 +0,0 @@ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; diff --git a/reverse_engineering/node_modules/isarray/package.json b/reverse_engineering/node_modules/isarray/package.json deleted file mode 100644 index 1a4317a..0000000 --- a/reverse_engineering/node_modules/isarray/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "isarray", - "description": "Array#isArray for older browsers", - "version": "1.0.0", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/isarray.git" - }, - "homepage": "https://github.com/juliangruber/isarray", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "tape": "~2.13.4" - }, - "keywords": [ - "browser", - "isarray", - "array" - ], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT", - "testling": { - "files": "test.js", - "browsers": [ - "ie/8..latest", - "firefox/17..latest", - "firefox/nightly", - "chrome/22..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "scripts": { - "test": "tape test.js" - } -} diff --git a/reverse_engineering/node_modules/isarray/test.js b/reverse_engineering/node_modules/isarray/test.js deleted file mode 100644 index e0c3444..0000000 --- a/reverse_engineering/node_modules/isarray/test.js +++ /dev/null @@ -1,20 +0,0 @@ -var isArray = require('./'); -var test = require('tape'); - -test('is array', function(t){ - t.ok(isArray([])); - t.notOk(isArray({})); - t.notOk(isArray(null)); - t.notOk(isArray(false)); - - var obj = {}; - obj[0] = true; - t.notOk(isArray(obj)); - - var arr = []; - arr.foo = 'bar'; - t.ok(isArray(arr)); - - t.end(); -}); - diff --git a/reverse_engineering/node_modules/locate-path/index.d.ts b/reverse_engineering/node_modules/locate-path/index.d.ts deleted file mode 100644 index fbde526..0000000 --- a/reverse_engineering/node_modules/locate-path/index.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -declare namespace locatePath { - interface Options { - /** - Current working directory. - - @default process.cwd() - */ - readonly cwd?: string; - - /** - Type of path to match. - - @default 'file' - */ - readonly type?: 'file' | 'directory'; - - /** - Allow symbolic links to match if they point to the requested path type. - - @default true - */ - readonly allowSymlinks?: boolean; - } - - interface AsyncOptions extends Options { - /** - Number of concurrently pending promises. Minimum: `1`. - - @default Infinity - */ - readonly concurrency?: number; - - /** - Preserve `paths` order when searching. - - Disable this to improve performance if you don't care about the order. - - @default true - */ - readonly preserveOrder?: boolean; - } -} - -declare const locatePath: { - /** - Get the first path that exists on disk of multiple paths. - - @param paths - Paths to check. - @returns The first path that exists or `undefined` if none exists. - - @example - ``` - import locatePath = require('locate-path'); - - const files = [ - 'unicorn.png', - 'rainbow.png', // Only this one actually exists on disk - 'pony.png' - ]; - - (async () => { - console(await locatePath(files)); - //=> 'rainbow' - })(); - ``` - */ - (paths: Iterable, options?: locatePath.AsyncOptions): Promise< - string | undefined - >; - - /** - Synchronously get the first path that exists on disk of multiple paths. - - @param paths - Paths to check. - @returns The first path that exists or `undefined` if none exists. - */ - sync( - paths: Iterable, - options?: locatePath.Options - ): string | undefined; -}; - -export = locatePath; diff --git a/reverse_engineering/node_modules/locate-path/index.js b/reverse_engineering/node_modules/locate-path/index.js deleted file mode 100644 index 4604bbf..0000000 --- a/reverse_engineering/node_modules/locate-path/index.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; -const path = require('path'); -const fs = require('fs'); -const {promisify} = require('util'); -const pLocate = require('p-locate'); - -const fsStat = promisify(fs.stat); -const fsLStat = promisify(fs.lstat); - -const typeMappings = { - directory: 'isDirectory', - file: 'isFile' -}; - -function checkType({type}) { - if (type in typeMappings) { - return; - } - - throw new Error(`Invalid type specified: ${type}`); -} - -const matchType = (type, stat) => type === undefined || stat[typeMappings[type]](); - -module.exports = async (paths, options) => { - options = { - cwd: process.cwd(), - type: 'file', - allowSymlinks: true, - ...options - }; - checkType(options); - const statFn = options.allowSymlinks ? fsStat : fsLStat; - - return pLocate(paths, async path_ => { - try { - const stat = await statFn(path.resolve(options.cwd, path_)); - return matchType(options.type, stat); - } catch (_) { - return false; - } - }, options); -}; - -module.exports.sync = (paths, options) => { - options = { - cwd: process.cwd(), - allowSymlinks: true, - type: 'file', - ...options - }; - checkType(options); - const statFn = options.allowSymlinks ? fs.statSync : fs.lstatSync; - - for (const path_ of paths) { - try { - const stat = statFn(path.resolve(options.cwd, path_)); - - if (matchType(options.type, stat)) { - return path_; - } - } catch (_) { - } - } -}; diff --git a/reverse_engineering/node_modules/locate-path/license b/reverse_engineering/node_modules/locate-path/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/locate-path/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/locate-path/package.json b/reverse_engineering/node_modules/locate-path/package.json deleted file mode 100644 index 063b290..0000000 --- a/reverse_engineering/node_modules/locate-path/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "locate-path", - "version": "5.0.0", - "description": "Get the first path that exists on disk of multiple paths", - "license": "MIT", - "repository": "sindresorhus/locate-path", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "locate", - "path", - "paths", - "file", - "files", - "exists", - "find", - "finder", - "search", - "searcher", - "array", - "iterable", - "iterator" - ], - "dependencies": { - "p-locate": "^4.1.0" - }, - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.2", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/locate-path/readme.md b/reverse_engineering/node_modules/locate-path/readme.md deleted file mode 100644 index 2184c6f..0000000 --- a/reverse_engineering/node_modules/locate-path/readme.md +++ /dev/null @@ -1,122 +0,0 @@ -# locate-path [![Build Status](https://travis-ci.org/sindresorhus/locate-path.svg?branch=master)](https://travis-ci.org/sindresorhus/locate-path) - -> Get the first path that exists on disk of multiple paths - - -## Install - -``` -$ npm install locate-path -``` - - -## Usage - -Here we find the first file that exists on disk, in array order. - -```js -const locatePath = require('locate-path'); - -const files = [ - 'unicorn.png', - 'rainbow.png', // Only this one actually exists on disk - 'pony.png' -]; - -(async () => { - console(await locatePath(files)); - //=> 'rainbow' -})(); -``` - - -## API - -### locatePath(paths, [options]) - -Returns a `Promise` for the first path that exists or `undefined` if none exists. - -#### paths - -Type: `Iterable` - -Paths to check. - -#### options - -Type: `Object` - -##### concurrency - -Type: `number`
-Default: `Infinity`
-Minimum: `1` - -Number of concurrently pending promises. - -##### preserveOrder - -Type: `boolean`
-Default: `true` - -Preserve `paths` order when searching. - -Disable this to improve performance if you don't care about the order. - -##### cwd - -Type: `string`
-Default: `process.cwd()` - -Current working directory. - -##### type - -Type: `string`
-Default: `file`
-Values: `file` `directory` - -The type of paths that can match. - -##### allowSymlinks - -Type: `boolean`
-Default: `true` - -Allow symbolic links to match if they point to the chosen path type. - -### locatePath.sync(paths, [options]) - -Returns the first path that exists or `undefined` if none exists. - -#### paths - -Type: `Iterable` - -Paths to check. - -#### options - -Type: `Object` - -##### cwd - -Same as above. - -##### type - -Same as above. - -##### allowSymlinks - -Same as above. - - -## Related - -- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/reverse_engineering/node_modules/lodash.chunk/LICENSE b/reverse_engineering/node_modules/lodash.chunk/LICENSE deleted file mode 100644 index e0c69d5..0000000 --- a/reverse_engineering/node_modules/lodash.chunk/LICENSE +++ /dev/null @@ -1,47 +0,0 @@ -Copyright jQuery Foundation and other contributors - -Based on Underscore.js, copyright Jeremy Ashkenas, -DocumentCloud and Investigative Reporters & Editors - -This software consists of voluntary contributions made by many -individuals. For exact contribution history, see the revision history -available at https://github.com/lodash/lodash - -The following license applies to all parts of this software except as -documented below: - -==== - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -==== - -Copyright and related rights for sample code are waived via CC0. Sample -code is defined as all source code displayed within the prose of the -documentation. - -CC0: http://creativecommons.org/publicdomain/zero/1.0/ - -==== - -Files located in the node_modules and vendor directories are externally -maintained libraries used by this software which have their own -licenses; we recommend you read them, as their terms may differ from the -terms above. diff --git a/reverse_engineering/node_modules/lodash.chunk/README.md b/reverse_engineering/node_modules/lodash.chunk/README.md deleted file mode 100644 index fd4daca..0000000 --- a/reverse_engineering/node_modules/lodash.chunk/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# lodash.chunk v4.2.0 - -The [lodash](https://lodash.com/) method `_.chunk` exported as a [Node.js](https://nodejs.org/) module. - -## Installation - -Using npm: -```bash -$ {sudo -H} npm i -g npm -$ npm i --save lodash.chunk -``` - -In Node.js: -```js -var chunk = require('lodash.chunk'); -``` - -See the [documentation](https://lodash.com/docs#chunk) or [package source](https://github.com/lodash/lodash/blob/4.2.0-npm-packages/lodash.chunk) for more details. diff --git a/reverse_engineering/node_modules/lodash.chunk/index.js b/reverse_engineering/node_modules/lodash.chunk/index.js deleted file mode 100644 index 7e7e967..0000000 --- a/reverse_engineering/node_modules/lodash.chunk/index.js +++ /dev/null @@ -1,475 +0,0 @@ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - -/** `Object#toString` result references. */ -var funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - symbolTag = '[object Symbol]'; - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; - -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeCeil = Math.ceil, - nativeMax = Math.max; - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; -} - -/** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ -function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array ? array.length : 0; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; -} - -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; -} - -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; -} - -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} - -module.exports = chunk; diff --git a/reverse_engineering/node_modules/lodash.chunk/package.json b/reverse_engineering/node_modules/lodash.chunk/package.json deleted file mode 100644 index 71cd2eb..0000000 --- a/reverse_engineering/node_modules/lodash.chunk/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "lodash.chunk", - "version": "4.2.0", - "description": "The lodash method `_.chunk` exported as a module.", - "homepage": "https://lodash.com/", - "icon": "https://lodash.com/icon.svg", - "license": "MIT", - "keywords": "lodash-modularized, chunk", - "author": "John-David Dalton (http://allyoucanleet.com/)", - "contributors": [ - "John-David Dalton (http://allyoucanleet.com/)", - "Blaine Bublitz (https://github.com/phated)", - "Mathias Bynens (https://mathiasbynens.be/)" - ], - "repository": "lodash/lodash", - "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } -} diff --git a/reverse_engineering/node_modules/lodash.defaults/LICENSE b/reverse_engineering/node_modules/lodash.defaults/LICENSE deleted file mode 100644 index e0c69d5..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/LICENSE +++ /dev/null @@ -1,47 +0,0 @@ -Copyright jQuery Foundation and other contributors - -Based on Underscore.js, copyright Jeremy Ashkenas, -DocumentCloud and Investigative Reporters & Editors - -This software consists of voluntary contributions made by many -individuals. For exact contribution history, see the revision history -available at https://github.com/lodash/lodash - -The following license applies to all parts of this software except as -documented below: - -==== - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -==== - -Copyright and related rights for sample code are waived via CC0. Sample -code is defined as all source code displayed within the prose of the -documentation. - -CC0: http://creativecommons.org/publicdomain/zero/1.0/ - -==== - -Files located in the node_modules and vendor directories are externally -maintained libraries used by this software which have their own -licenses; we recommend you read them, as their terms may differ from the -terms above. diff --git a/reverse_engineering/node_modules/lodash.defaults/README.md b/reverse_engineering/node_modules/lodash.defaults/README.md deleted file mode 100644 index a129849..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# lodash.defaults v4.2.0 - -The [lodash](https://lodash.com/) method `_.defaults` exported as a [Node.js](https://nodejs.org/) module. - -## Installation - -Using npm: -```bash -$ {sudo -H} npm i -g npm -$ npm i --save lodash.defaults -``` - -In Node.js: -```js -var defaults = require('lodash.defaults'); -``` - -See the [documentation](https://lodash.com/docs#defaults) or [package source](https://github.com/lodash/lodash/blob/4.2.0-npm-packages/lodash.defaults) for more details. diff --git a/reverse_engineering/node_modules/lodash.defaults/index.js b/reverse_engineering/node_modules/lodash.defaults/index.js deleted file mode 100644 index 25eba9c..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/index.js +++ /dev/null @@ -1,668 +0,0 @@ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; -} - -/** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ -function assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; -} - -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } -} - -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; -} - -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} - -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; -} - -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; -} - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; -} - -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; -} - -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); -}); - -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest(function(args) { - args.push(undefined, assignInDefaults); - return apply(assignInWith, undefined, args); -}); - -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); -} - -module.exports = defaults; diff --git a/reverse_engineering/node_modules/lodash.defaults/package.json b/reverse_engineering/node_modules/lodash.defaults/package.json deleted file mode 100644 index 3c49784..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "lodash.defaults", - "version": "4.2.0", - "description": "The lodash method `_.defaults` exported as a module.", - "homepage": "https://lodash.com/", - "icon": "https://lodash.com/icon.svg", - "license": "MIT", - "keywords": "lodash-modularized, defaults", - "author": "John-David Dalton (http://allyoucanleet.com/)", - "contributors": [ - "John-David Dalton (http://allyoucanleet.com/)", - "Blaine Bublitz (https://github.com/phated)", - "Mathias Bynens (https://mathiasbynens.be/)" - ], - "repository": "lodash/lodash", - "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } -} diff --git a/reverse_engineering/node_modules/map-stream/.npmignore b/reverse_engineering/node_modules/map-stream/.npmignore deleted file mode 100644 index 13abef4..0000000 --- a/reverse_engineering/node_modules/map-stream/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -node_modules/* -npm_debug.log diff --git a/reverse_engineering/node_modules/map-stream/.travis.yml b/reverse_engineering/node_modules/map-stream/.travis.yml deleted file mode 100644 index 895dbd3..0000000 --- a/reverse_engineering/node_modules/map-stream/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/reverse_engineering/node_modules/map-stream/LICENCE b/reverse_engineering/node_modules/map-stream/LICENCE deleted file mode 100644 index 2af26fe..0000000 --- a/reverse_engineering/node_modules/map-stream/LICENCE +++ /dev/null @@ -1,24 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2011 Dominic Tarr - -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom -the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/map-stream/examples/pretty.js b/reverse_engineering/node_modules/map-stream/examples/pretty.js deleted file mode 100644 index ab07398..0000000 --- a/reverse_engineering/node_modules/map-stream/examples/pretty.js +++ /dev/null @@ -1,26 +0,0 @@ - -var inspect = require('util').inspect - -if(!module.parent) { - var map = require('..') //load map-stream - var es = require('event-stream') //load event-stream - es.pipe( //pipe joins streams together - process.openStdin(), //open stdin - es.split(), //split stream to break on newlines - map(function (data, callback) { //turn this async function into a stream - var j - try { - j = JSON.parse(data) //try to parse input into json - } catch (err) { - return callback(null, data) //if it fails just pass it anyway - } - callback(null, inspect(j)) //render it nicely - }), - process.stdout // pipe it to stdout ! - ) - } - -// run this -// -// curl -sS registry.npmjs.org/event-stream | node pretty.js -// diff --git a/reverse_engineering/node_modules/map-stream/index.js b/reverse_engineering/node_modules/map-stream/index.js deleted file mode 100644 index cbf3970..0000000 --- a/reverse_engineering/node_modules/map-stream/index.js +++ /dev/null @@ -1,144 +0,0 @@ -//filter will reemit the data if cb(err,pass) pass is truthy - -// reduce is more tricky -// maybe we want to group the reductions or emit progress updates occasionally -// the most basic reduce just emits one 'data' event after it has recieved 'end' - - -var Stream = require('stream').Stream - - -//create an event stream and apply function to each .write -//emitting each response as data -//unless it's an empty callback - -module.exports = function (mapper, opts) { - - var stream = new Stream() - , inputs = 0 - , outputs = 0 - , ended = false - , paused = false - , destroyed = false - , lastWritten = 0 - , inNext = false - - opts = opts || {}; - var errorEventName = opts.failures ? 'failure' : 'error'; - - // Items that are not ready to be written yet (because they would come out of - // order) get stuck in a queue for later. - var writeQueue = {} - - stream.writable = true - stream.readable = true - - function queueData (data, number) { - var nextToWrite = lastWritten + 1 - - if (number === nextToWrite) { - // If it's next, and its not undefined write it - if (data !== undefined) { - stream.emit.apply(stream, ['data', data]) - } - lastWritten ++ - nextToWrite ++ - } else { - // Otherwise queue it for later. - writeQueue[number] = data - } - - // If the next value is in the queue, write it - if (writeQueue.hasOwnProperty(nextToWrite)) { - var dataToWrite = writeQueue[nextToWrite] - delete writeQueue[nextToWrite] - return queueData(dataToWrite, nextToWrite) - } - - outputs ++ - if(inputs === outputs) { - if(paused) paused = false, stream.emit('drain') //written all the incoming events - if(ended) end() - } - } - - function next (err, data, number) { - if(destroyed) return - inNext = true - - if (!err || opts.failures) { - queueData(data, number) - } - - if (err) { - stream.emit.apply(stream, [ errorEventName, err ]); - } - - inNext = false; - } - - // Wrap the mapper function by calling its callback with the order number of - // the item in the stream. - function wrappedMapper (input, number, callback) { - return mapper.call(null, input, function(err, data){ - callback(err, data, number) - }) - } - - stream.write = function (data) { - if(ended) throw new Error('map stream is not writable') - inNext = false - inputs ++ - - try { - //catch sync errors and handle them like async errors - var written = wrappedMapper(data, inputs, next) - paused = (written === false) - return !paused - } catch (err) { - //if the callback has been called syncronously, and the error - //has occured in an listener, throw it again. - if(inNext) - throw err - next(err) - return !paused - } - } - - function end (data) { - //if end was called with args, write it, - ended = true //write will emit 'end' if ended is true - stream.writable = false - if(data !== undefined) { - return queueData(data, inputs) - } else if (inputs == outputs) { //wait for processing - stream.readable = false, stream.emit('end'), stream.destroy() - } - } - - stream.end = function (data) { - if(ended) return - end(data) - } - - stream.destroy = function () { - ended = destroyed = true - stream.writable = stream.readable = paused = false - process.nextTick(function () { - stream.emit('close') - }) - } - stream.pause = function () { - paused = true - } - - stream.resume = function () { - paused = false - } - - return stream -} - - - - diff --git a/reverse_engineering/node_modules/map-stream/package.json b/reverse_engineering/node_modules/map-stream/package.json deleted file mode 100644 index 91f46d7..0000000 --- a/reverse_engineering/node_modules/map-stream/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "map-stream", - "version": "0.0.7", - "license": "MIT", - "description": "construct pipes of streams of events", - "homepage": "http://github.com/dominictarr/map-stream", - "repository": { - "type": "git", - "url": "git://github.com/dominictarr/map-stream.git" - }, - "dependencies": {}, - "devDependencies": { - "asynct": "*", - "it-is": "1", - "ubelt": "~2.9", - "stream-spec": "~0.2", - "event-stream": "~2.1", - "from": "0.0.2" - }, - "scripts": { - "test": "asynct test/" - }, - "author": "Dominic Tarr (http://dominictarr.com)" -} diff --git a/reverse_engineering/node_modules/map-stream/readme.markdown b/reverse_engineering/node_modules/map-stream/readme.markdown deleted file mode 100644 index 1897158..0000000 --- a/reverse_engineering/node_modules/map-stream/readme.markdown +++ /dev/null @@ -1,37 +0,0 @@ -# MapStream - -Refactored out of [event-stream](https://github.com/dominictarr/event-stream) - -##map (asyncFunction[, options]) - -Create a through stream from an asyncronous function. - -``` js -var map = require('map-stream') - -map(function (data, callback) { - //transform data - // ... - callback(null, data) -}) - -``` - -Each map MUST call the callback. It may callback with data, with an error or with no arguments, - - * `callback()` drop this data. - this makes the map work like `filter`, - note:`callback(null,null)` is not the same, and will emit `null` - - * `callback(null, newData)` turn data into newData - - * `callback(error)` emit an error for this item. - ->Note: if a callback is not called, `map` will think that it is still being processed, ->every call must be answered or the stream will not know when to end. -> ->Also, if the callback is called more than once, every call but the first will be ignored. - -##Options - - * `failures` - `boolean` continue mapping even if error occured. On error `map-stream` will emit `failure` event. (default: `false`) diff --git a/reverse_engineering/node_modules/map-stream/test/simple-map.asynct.js b/reverse_engineering/node_modules/map-stream/test/simple-map.asynct.js deleted file mode 100644 index 2b9a292..0000000 --- a/reverse_engineering/node_modules/map-stream/test/simple-map.asynct.js +++ /dev/null @@ -1,318 +0,0 @@ -'use strict'; - -var map = require('../') - , it = require('it-is') - , u = require('ubelt') - , spec = require('stream-spec') - , from = require('from') - , Stream = require('stream') - , es = require('event-stream') - -//REFACTOR THIS TEST TO USE es.readArray and es.writeArray - -function writeArray(array, stream) { - - array.forEach( function (j) { - stream.write(j) - }) - stream.end() - -} - -function readStream(stream, done) { - - var array = [] - stream.on('data', function (data) { - array.push(data) - }) - stream.on('error', done) - stream.on('end', function (data) { - done(null, array) - }) - -} - -//call sink on each write, -//and complete when finished. - -function pauseStream (prob, delay) { - var pauseIf = ( - 'number' == typeof prob - ? function () { - return Math.random() < prob - } - : 'function' == typeof prob - ? prob - : 0.1 - ) - var delayer = ( - !delay - ? process.nextTick - : 'number' == typeof delay - ? function (next) { setTimeout(next, delay) } - : delay - ) - - return es.through(function (data) { - if(!this.paused && pauseIf()) { - console.log('PAUSE STREAM PAUSING') - this.pause() - var self = this - delayer(function () { - console.log('PAUSE STREAM RESUMING') - self.resume() - }) - } - console.log("emit ('data', " + data + ')') - this.emit('data', data) - }) -} - -exports ['simple map applied to a stream'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - //create event stream from - - var doubler = map(function (data, cb) { - cb(null, data * 2) - }) - - spec(doubler).through().validateOnExit() - - //a map is only a middle man, so it is both readable and writable - - it(doubler).has({ - readable: true, - writable: true, - }) - - readStream(doubler, function (err, output) { - it(output).deepEqual(input.map(function (j) { - return j * 2 - })) -// process.nextTick(x.validate) - test.done() - }) - - writeArray(input, doubler) - -} - -exports ['stream comes back in the correct order'] = function (test) { - var input = [3, 2, 1] - - var delayer = map(function(data, cb){ - setTimeout(function () { - cb(null, data) - }, 100 * data) - }) - - readStream(delayer, function (err, output) { - it(output).deepEqual(input) - test.done() - }) - - writeArray(input, delayer) -} - -exports ['continues on error event with failures `true`'] = function (test) { - var input = [1, 2, 3] - - var delayer = map(function(data, cb){ - cb(new Error('Something gone wrong'), data) - }, { failures: true }) - - readStream(delayer, function (err, output) { - it(output).deepEqual(input) - test.done() - }) - - writeArray(input, delayer) -} - -exports['pipe two maps together'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - //create event stream from - function dd (data, cb) { - cb(null, data * 2) - } - var doubler1 = map(dd), doubler2 = map(dd) - - doubler1.pipe(doubler2) - - spec(doubler1).through().validateOnExit() - spec(doubler2).through().validateOnExit() - - readStream(doubler2, function (err, output) { - it(output).deepEqual(input.map(function (j) { - return j * 4 - })) - test.done() - }) - - writeArray(input, doubler1) - -} - -//next: -// -// test pause, resume and drian. -// - -// then make a pipe joiner: -// -// plumber (evStr1, evStr2, evStr3, evStr4, evStr5) -// -// will return a single stream that write goes to the first - -exports ['map will not call end until the callback'] = function (test) { - - var ticker = map(function (data, cb) { - process.nextTick(function () { - cb(null, data * 2) - }) - }) - - spec(ticker).through().validateOnExit() - - ticker.write('x') - ticker.end() - - ticker.on('end', function () { - test.done() - }) -} - -exports ['emit failures with opts.failures === `ture`'] = function (test) { - - var err = new Error('INTENSIONAL ERROR') - , mapper = - map(function () { - throw err - }, { failures: true }) - - mapper.on('failure', function (_err) { - it(_err).equal(err) - test.done() - }) - - mapper.write('hello') - -} - -exports ['emit error thrown'] = function (test) { - - var err = new Error('INTENSIONAL ERROR') - , mapper = - map(function () { - throw err - }) - - mapper.on('error', function (_err) { - it(_err).equal(err) - test.done() - }) - - mapper.write('hello') - -} - -exports ['emit error calledback'] = function (test) { - - var err = new Error('INTENSIONAL ERROR') - , mapper = - map(function (data, callback) { - callback(err) - }) - - mapper.on('error', function (_err) { - it(_err).equal(err) - test.done() - }) - - mapper.write('hello') - -} - -exports ['do not emit drain if not paused'] = function (test) { - - var maps = map(function (data, callback) { - u.delay(callback)(null, 1) - return true - }) - - spec(maps).through().pausable().validateOnExit() - - maps.on('drain', function () { - it(false).ok('should not emit drain unless the stream is paused') - }) - - it(maps.write('hello')).equal(true) - it(maps.write('hello')).equal(true) - it(maps.write('hello')).equal(true) - setTimeout(function () {maps.end()},10) - maps.on('end', test.done) -} - -exports ['emits drain if paused, when all '] = function (test) { - var active = 0 - var drained = false - var maps = map(function (data, callback) { - active ++ - u.delay(function () { - active -- - callback(null, 1) - })() - console.log('WRITE', false) - return false - }) - - spec(maps).through().validateOnExit() - - maps.on('drain', function () { - drained = true - it(active).equal(0, 'should emit drain when all maps are done') - }) - - it(maps.write('hello')).equal(false) - it(maps.write('hello')).equal(false) - it(maps.write('hello')).equal(false) - - process.nextTick(function () {maps.end()},10) - - maps.on('end', function () { - console.log('end') - it(drained).ok('shoud have emitted drain before end') - test.done() - }) - -} - -exports ['map applied to a stream with filtering'] = function (test) { - - var input = [1,2,3,7,5,3,1,9,0,2,4,6] - - var doubler = map(function (data, callback) { - if (data % 2) - callback(null, data * 2) - else - callback() - }) - - readStream(doubler, function (err, output) { - it(output).deepEqual(input.filter(function (j) { - return j % 2 - }).map(function (j) { - return j * 2 - })) - test.done() - }) - - spec(doubler).through().validateOnExit() - - writeArray(input, doubler) - -} - - diff --git a/reverse_engineering/node_modules/memory-pager/.travis.yml b/reverse_engineering/node_modules/memory-pager/.travis.yml deleted file mode 100644 index 1c4ab31..0000000 --- a/reverse_engineering/node_modules/memory-pager/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - '4' - - '6' diff --git a/reverse_engineering/node_modules/memory-pager/LICENSE b/reverse_engineering/node_modules/memory-pager/LICENSE deleted file mode 100644 index 56fce08..0000000 --- a/reverse_engineering/node_modules/memory-pager/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/memory-pager/README.md b/reverse_engineering/node_modules/memory-pager/README.md deleted file mode 100644 index aed1761..0000000 --- a/reverse_engineering/node_modules/memory-pager/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# memory-pager - -Access memory using small fixed sized buffers instead of allocating a huge buffer. -Useful if you are implementing sparse data structures (such as large bitfield). - -![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) - -``` -npm install memory-pager -``` - -## Usage - -``` js -var pager = require('paged-memory') - -var pages = pager(1024) // use 1kb per page - -var page = pages.get(10) // get page #10 - -console.log(page.offset) // 10240 -console.log(page.buffer) // a blank 1kb buffer -``` - -## API - -#### `var pages = pager(pageSize)` - -Create a new pager. `pageSize` defaults to `1024`. - -#### `var page = pages.get(pageNumber, [noAllocate])` - -Get a page. The page will be allocated at first access. - -Optionally you can set the `noAllocate` flag which will make the -method return undefined if no page has been allocated already - -A page looks like this - -``` js -{ - offset: byteOffset, - buffer: bufferWithPageSize -} -``` - -#### `pages.set(pageNumber, buffer)` - -Explicitly set the buffer for a page. - -#### `pages.updated(page)` - -Mark a page as updated. - -#### `pages.lastUpdate()` - -Get the last page that was updated. - -#### `var buf = pages.toBuffer()` - -Concat all pages allocated pages into a single buffer - -## License - -MIT diff --git a/reverse_engineering/node_modules/memory-pager/index.js b/reverse_engineering/node_modules/memory-pager/index.js deleted file mode 100644 index 687f346..0000000 --- a/reverse_engineering/node_modules/memory-pager/index.js +++ /dev/null @@ -1,160 +0,0 @@ -module.exports = Pager - -function Pager (pageSize, opts) { - if (!(this instanceof Pager)) return new Pager(pageSize, opts) - - this.length = 0 - this.updates = [] - this.path = new Uint16Array(4) - this.pages = new Array(32768) - this.maxPages = this.pages.length - this.level = 0 - this.pageSize = pageSize || 1024 - this.deduplicate = opts ? opts.deduplicate : null - this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null -} - -Pager.prototype.updated = function (page) { - while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { - page.deduplicate++ - if (page.deduplicate === this.deduplicate.length) { - page.deduplicate = 0 - if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate - break - } - } - if (page.updated || !this.updates) return - page.updated = true - this.updates.push(page) -} - -Pager.prototype.lastUpdate = function () { - if (!this.updates || !this.updates.length) return null - var page = this.updates.pop() - page.updated = false - return page -} - -Pager.prototype._array = function (i, noAllocate) { - if (i >= this.maxPages) { - if (noAllocate) return - grow(this, i) - } - - factor(i, this.path) - - var arr = this.pages - - for (var j = this.level; j > 0; j--) { - var p = this.path[j] - var next = arr[p] - - if (!next) { - if (noAllocate) return - next = arr[p] = new Array(32768) - } - - arr = next - } - - return arr -} - -Pager.prototype.get = function (i, noAllocate) { - var arr = this._array(i, noAllocate) - var first = this.path[0] - var page = arr && arr[first] - - if (!page && !noAllocate) { - page = arr[first] = new Page(i, alloc(this.pageSize)) - if (i >= this.length) this.length = i + 1 - } - - if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { - page.buffer = copy(page.buffer) - page.deduplicate = 0 - } - - return page -} - -Pager.prototype.set = function (i, buf) { - var arr = this._array(i, false) - var first = this.path[0] - - if (i >= this.length) this.length = i + 1 - - if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { - arr[first] = undefined - return - } - - if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { - buf = this.deduplicate - } - - var page = arr[first] - var b = truncate(buf, this.pageSize) - - if (page) page.buffer = b - else arr[first] = new Page(i, b) -} - -Pager.prototype.toBuffer = function () { - var list = new Array(this.length) - var empty = alloc(this.pageSize) - var ptr = 0 - - while (ptr < list.length) { - var arr = this._array(ptr, true) - for (var i = 0; i < 32768 && ptr < list.length; i++) { - list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty - } - } - - return Buffer.concat(list) -} - -function grow (pager, index) { - while (pager.maxPages < index) { - var old = pager.pages - pager.pages = new Array(32768) - pager.pages[0] = old - pager.level++ - pager.maxPages *= 32768 - } -} - -function truncate (buf, len) { - if (buf.length === len) return buf - if (buf.length > len) return buf.slice(0, len) - var cpy = alloc(len) - buf.copy(cpy) - return cpy -} - -function alloc (size) { - if (Buffer.alloc) return Buffer.alloc(size) - var buf = new Buffer(size) - buf.fill(0) - return buf -} - -function copy (buf) { - var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) - buf.copy(cpy) - return cpy -} - -function Page (i, buf) { - this.offset = i * buf.length - this.buffer = buf - this.updated = false - this.deduplicate = 0 -} - -function factor (n, out) { - n = (n - (out[0] = (n & 32767))) / 32768 - n = (n - (out[1] = (n & 32767))) / 32768 - out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 -} diff --git a/reverse_engineering/node_modules/memory-pager/package.json b/reverse_engineering/node_modules/memory-pager/package.json deleted file mode 100644 index f4847e8..0000000 --- a/reverse_engineering/node_modules/memory-pager/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "memory-pager", - "version": "1.5.0", - "description": "Access memory using small fixed sized buffers", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/mafintosh/memory-pager.git" - }, - "author": "Mathias Buus (@mafintosh)", - "license": "MIT", - "bugs": { - "url": "https://github.com/mafintosh/memory-pager/issues" - }, - "homepage": "https://github.com/mafintosh/memory-pager" -} diff --git a/reverse_engineering/node_modules/memory-pager/test.js b/reverse_engineering/node_modules/memory-pager/test.js deleted file mode 100644 index 1638210..0000000 --- a/reverse_engineering/node_modules/memory-pager/test.js +++ /dev/null @@ -1,80 +0,0 @@ -var tape = require('tape') -var pager = require('./') - -tape('get page', function (t) { - var pages = pager(1024) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.end() -}) - -tape('get page twice', function (t) { - var pages = pager(1024) - t.same(pages.length, 0) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1) - - var other = pages.get(0) - - t.same(other, page) - t.end() -}) - -tape('get no mutable page', function (t) { - var pages = pager(1024) - - t.ok(!pages.get(141, true)) - t.ok(pages.get(141)) - t.ok(pages.get(141, true)) - - t.end() -}) - -tape('get far out page', function (t) { - var pages = pager(1024) - - var page = pages.get(1000000) - - t.same(page.offset, 1000000 * 1024) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - - var other = pages.get(1) - - t.same(other.offset, 1024) - t.same(other.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - t.ok(other !== page) - - t.end() -}) - -tape('updates', function (t) { - var pages = pager(1024) - - t.same(pages.lastUpdate(), null) - - var page = pages.get(10) - - page.buffer[42] = 1 - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - page.buffer[42] = 2 - pages.updated(page) - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - t.end() -}) diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/.eslintrc b/reverse_engineering/node_modules/mongodb-collection-sample/.eslintrc deleted file mode 100644 index cbb6b1b..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/.eslintrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "env": { - "mocha": true - }, - "extends": "mongodb-js/node" -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/CONTRIBUTING.md b/reverse_engineering/node_modules/mongodb-collection-sample/CONTRIBUTING.md deleted file mode 100644 index 2ee43ce..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/CONTRIBUTING.md +++ /dev/null @@ -1,36 +0,0 @@ -# Contributing - -Great to have you here. These are a few ways you can help make this project better: - -- [Implement a #starter feature](http://github.com/mongodb-js/mongodb-collection-sample/labels/starter) -- Add an example to `README.md` - -## Workflow - -1. [Fork the repository on GitHub](http://github.com/mongodb-js/mongodb-collection-sample) -1. Create a new branch with a name that breifly describes your feature -1. Implement your feature or bug fix -1. Add new cases to `./test/index.test.js` and run them with `npm test` -1. Add comments around your new code that explain what's happening -1. Commit and push your changes to your branch -1. Submit a pull request - -Don’t get discouraged! We estimate that the response time from the -maintainers is less than 24 hours. - -## Bugs - -You can report new bugs by -[creating a new issue](http://github.com/mongodb-js/mongodb-collection-sample/issues). -Please include as much information as possible about your environment -("I am using node.js v 0.12.0 on OSX Mavericks"). Actual code is always -more valuable than an explanation, so please include a link to a GitHub -gist or include a snippet directly in your issue description. - -## Versioning - -This library aims to adhere to [Semantic Versioning2.0.0](http://semver.org/). -Violations of this scheme should be reported as bugs. Specifically, if a -minor or patch version is released that breaks backward compatibility, -that version should be immediately yanked and/or a new version should be -immediately released that restores compatibility. diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/LICENSE b/reverse_engineering/node_modules/mongodb-collection-sample/LICENSE deleted file mode 100644 index c3c978f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2015 MongoDB Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/README.md b/reverse_engineering/node_modules/mongodb-collection-sample/README.md deleted file mode 100644 index d033dca..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/README.md +++ /dev/null @@ -1,141 +0,0 @@ -# mongodb-collection-sample [![][npm_img]][npm_url] [![][travis_img]][travis_url] - -> Sample documents from a MongoDB collection. - -## Install - -``` -npm install --save mongodb-collection-sample -``` - -## Example - -``` -npm install mongodb lodash mongodb-collection-sample -``` - -```javascript -var sample = require('mongodb-collection-sample'); -var mongodb = require('mongodb'); -var _ = require('lodash'); - -// Connect to mongodb -mongodb.connect('mongodb://localhost:27017', function(err, db){ - if(err){ - console.error('Could not connect to mongodb:', err); - return process.exit(1); - } - - // Generate 1000 documents - var docs = _range(0, 1000).map(function(i) { - return { - _id: 'needle_' + i, - is_even: i % 2 - }; - }); - - // Insert them into a collection - db.collection('haystack').insert(docs, function(err){ - if(err){ - console.error('Could not insert example documents', err); - return process.exit(1); - } - - var options = {}; - // Size of the sample to capture [default: `5`]. - options.size = 5; - - // Query to restrict sample source [default: `{}`] - options.query = {}; - - // Get a stream of sample documents from the collection. - var stream = sample(db, 'haystack', options); - stream.on('error', function(err){ - console.error('Error in sample stream', err); - return process.exit(1); - }); - stream.on('data', function(doc){ - console.log('Got sampled document `%j`', doc); - }); - stream.on('end', function(){ - console.log('Sampling complete! Goodbye!'); - db.close(); - process.exit(0); - }); - }); -}); -``` - -## Options - -Supported options that can be passed to `sample(db, coll, options)` are - -- `query`: the filter to be used, default is `{}` -- `size`: the number of documents to sample, default is `5` -- `fields`: the fields you want returned (projection object), default is `null` -- `raw`: boolean to return documents as raw BSON buffers, default is `false` -- `sort`: the sort field and direction, default is `{_id: -1}` -- `maxTimeMS`: the maxTimeMS value after which the operation is terminated, default is `undefined` -- `promoteValues`: boolean whether certain BSON values should be cast to native Javascript values or not. Default is `true` - - -## How It Works - -#### Native Sampler - -MongoDB version 3.1.6 and above generally uses the `$sample` aggregation operator: - -``` -db.collectionName.aggregate([ - {$match: }, - {$sample: {size: }}, - {$project: }, - {$sort: } -]) -``` - -However, if more documents are requested than are available, the `$sample` stage -is omitted for performance optimization. If the sample size is above 5% of the -result set count (but less than 100%), the algorithm falls back to the reservoir -sampling, to avoid a blocking sort stage on the server. - - -#### Reservoir Sampling - -For MongoDB version 3.1.5 and below we use a client-size reservoir sampling algorithm. - -- Query for a stream of _id values, limit 10,000. -- Read stream of `_id`s and save `sampleSize` randomly chosen values. -- Then query selected random documents by _id. - -The two modes, illustrated: - -[![][sampling_post_316_png]][sampling_post_316_svg] -[![][sampling_pre_316_png]][sampling_pre_316_svg] - -## Performance Notes - -For peak performance of the client-side reservoir sampler, keep the following guidelines in mind. - -- The initial query for a stream of `_id` values must be limited to some finite value. (Default 10k) -- This query should be covered by an index -- Since there's a limit, you may wish to bias for recent documents via a sort. (Default: {_id: -1}) -- [Don't sort on {$natural: -1}](https://docs.mongodb.org/manual/reference/operator/meta/natural): this forces a collection scan! - -> Queries that include a sort by $natural order do not use indexes to fulfill the query predicate - -- When retrieving docs: batch using one $in to reduce network chattiness. - -## License - -Apache 2 - -[travis_img]: https://secure.travis-ci.org/mongodb-js/collection-sample.svg?branch=master -[travis_url]: https://travis-ci.org/mongodb-js/collection-sample -[npm_img]: https://img.shields.io/npm/v/mongodb-collection-sample.svg -[npm_url]: https://www.npmjs.org/package/mongodb-collection-sample -[gitter_img]: https://badges.gitter.im/Join%20Chat.svg -[sampling_post_316_png]: docs/sampling_analyzing_post_316.png?raw=true -[sampling_post_316_svg]: docs/sampling_analyzing_post_316.svg -[sampling_pre_316_png]: docs/sampling_analyzing_pre_316.png?raw=true -[sampling_pre_316_svg]: docs/sampling_analyzing_pre_316.svg diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/bin/mongodb-collection-sample.js b/reverse_engineering/node_modules/mongodb-collection-sample/bin/mongodb-collection-sample.js deleted file mode 100755 index 5c7cea1..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/bin/mongodb-collection-sample.js +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env node - -var es = require('event-stream'); -var mongodb = require('mongodb'); -var sample = require('../'); -var toNS = require('mongodb-ns'); -var EJSON = require('bson').EJSON; -var pkg = require('../package.json'); - -// var debug = require('debug')('mongodb-collection-sample:bin'); - -/* eslint no-console: 0*/ - -var argv = require('yargs') - .usage('Usage: $0 [options]') - .demand(2) - .option('n', { - alias: 'size', - default: 100, - describe: 'The number of documents to sample.' - }) - .option('f', { - alias: 'fields', - type: 'string', - describe: 'field projection object', - default: null - }) - .option('q', { - alias: 'query', - type: 'string', - describe: 'query filter', - default: '{}' - }) - .option('o', { - alias: 'output', - type: 'boolean', - describe: 'Print the sampled documents to stdout.', - default: true - }) - .describe('debug', 'Enable debug messages.') - .describe('version', 'Show version.') - .alias('h', 'help') - .describe('h', 'Show this screen.') - .help('h').argv; - -if (argv.debug) { - process.env.DEBUG = '*'; -} - -var uri = argv._[0]; -if (!uri.startsWith('mongodb://')) { - uri = 'mongodb://' + uri; -} -var sampleSize = parseInt(argv.size, 10); - -if (argv.version) { - console.error(pkg.version); - process.exit(1); -} - -mongodb.connect(uri, function(err, conn) { - if (err) { - console.error('Failed to connect to MongoDB: ', err); - process.exit(1); - } - - var ns = toNS(argv._[1]); - var db = conn.db(ns.database); - - var options = { - size: sampleSize, - query: JSON.parse(argv.query) - }; - - if (argv.fields !== null) { - options.fields = JSON.parse(argv.fields); - } - - sample(db, ns.collection, options) - .pipe( - es.map(function(data, cb) { - if (data && argv.output) { - console.log(EJSON.stringify(data, null, 2)); - } - cb(null, data); - }) - ) - .pipe( - es.wait(function(sampleErr) { - if (sampleErr) { - console.error('Error sampling data:', sampleErr); - process.exit(1); - } - process.exit(0); - }) - ); -}); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/index.js b/reverse_engineering/node_modules/mongodb-collection-sample/index.js deleted file mode 100644 index bb0a047..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib'); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/lib/base-sampler.js b/reverse_engineering/node_modules/mongodb-collection-sample/lib/base-sampler.js deleted file mode 100644 index 7663ff1..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/lib/base-sampler.js +++ /dev/null @@ -1,42 +0,0 @@ -var _defaults = require('lodash.defaults'); -var Readable = require('stream').Readable; -var inherits = require('util').inherits; - -function BaseSampler(db, collectionName, opts) { - this.db = db; - this.collectionName = collectionName; - this.opts = opts; - - opts = _defaults(opts || {}, { - query: {}, - size: 5, - fields: null, - raw: false, - sort: { - _id: -1 - }, - maxTimeMS: undefined, - promoteValues: true - }); - - this.query = opts.query || {}; - this.size = opts.size; - this.raw = opts.raw; - this.fields = opts.fields; - this.sort = opts.sort; - this.maxTimeMS = opts.maxTimeMS; - this.promoteValues = opts.promoteValues; - - Readable.call(this, { - objectMode: true - }); -} -inherits(BaseSampler, Readable); - -Object.defineProperty(BaseSampler.prototype, 'collection', { - get: function() { - return this.db.collection(this.collectionName, {}); - } -}); - -module.exports = BaseSampler; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/lib/index.js b/reverse_engineering/node_modules/mongodb-collection-sample/lib/index.js deleted file mode 100644 index 9f0f22b..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/lib/index.js +++ /dev/null @@ -1,62 +0,0 @@ -var es = require('event-stream'); -var semver = require('semver'); -var debug = require('debug')('mongodb-collection-sample'); -var ReservoirSampler = require('./reservoir-sampler'); -var NativeSampler = require('./native-sampler'); - -/** - * Test the MongoDB kernel version `db` is using and return - * a `stream.Readable` that will use the native `$sample` aggregation - * operator if available or fall back to a client-side reservoir sample. - * - * @param {mongodb.DB} db - * @param {String} collectionName to source from. - * @param {Object} opts - * @param {Function} done callback - * - * @option {Object} query to refine possible samples [default: `{}`]. - * @option {Number} size of the sample to capture [default: `5`]. - * @option {Boolean} raw BSON buffers to return [default: `false`]. - * @option {Object} cursor specification when providing a raw option [default: `{}`]. - */ -function getSampler(db, collectionName, opts, done) { - db.admin().serverInfo(function(err, res) { - if (err) return done(err); - var supported = semver.gte(res.version, '3.1.6'); - - debug('has native $sample?', supported); - if (!supported) { - return done(null, new ReservoirSampler(db, collectionName, opts)); - } - return done(null, new NativeSampler(db, collectionName, opts)); - }); -} - -/** - * Take an `_id` and emit the source document. - * - * @param {mongodb.Db} db - * @param {String} collectionName to source from. - * @param {Object} [opts] - * @option {Object} query to refine possible samples [default: `{}`]. - * @option {Number} size of the sample to capture [default: `5`]. - * @option {Boolean} raw BSON buffers to return [default: `false`]. - * @return {stream.Readable} - * @api public - */ -module.exports = function(db, collectionName, opts) { - var readable = es.readable(function() { - getSampler(db, collectionName, opts, function(err, src) { - if (err) { - return readable.emit('error', err); - } - - src.on('data', readable.emit.bind(readable, 'data')); - src.on('error', readable.emit.bind(readable, 'error')); - src.on('end', readable.emit.bind(readable, 'end')); - }); - }); - return readable; -}; - -module.exports.getSampler = getSampler; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/lib/native-sampler.js b/reverse_engineering/node_modules/mongodb-collection-sample/lib/native-sampler.js deleted file mode 100644 index e1ff863..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/lib/native-sampler.js +++ /dev/null @@ -1,96 +0,0 @@ -var BaseSampler = require('./base-sampler'); -var rawTransform = require('./raw-transform'); -var ReservoirSampler = require('./reservoir-sampler'); -var inherits = require('util').inherits; -var debug = require('debug')('mongodb-collection-sample:native-sampler'); - -/** - * A readable stream of sample of documents from a collection using the - * `$sample` aggregation operator. - * - * @param {mongodb.DB} db - * @param {String} collectionName to source from. - * @param {Object} opts - * @option {Object} query to refine possible samples [default: `{}`]. - * @option {Array} fields to only return certain fields [default: null] - * @option {Number} size of the sample to capture [default: `5`]. - * @option {Boolean} return document results as raw BSON buffers [default: `false`]. - * @api public - */ -function NativeSampler(db, collectionName, opts) { - BaseSampler.call(this, db, collectionName, opts); - this.running = false; -} -inherits(NativeSampler, BaseSampler); - -NativeSampler.prototype._read = function() { - if (this.running) { - return; - } - - this.running = true; - - var options = { - maxTimeMS: this.maxTimeMS, - allowDiskUse: true, - promoteValues: this.promoteValues - }; - - this.collection.countDocuments(this.query, options, function(err, count) { - if (err) { - return this.emit('error', err); - } - debug('sampling %d documents from a collection with %d documents', - this.size, count); - - // if we need more than 5% of all docs (but not all of them), use - // ReservoirSampler to avoid the blocking sort stage (SERVER-22815). - // if need raw output, always do native sampling - if (count > this.size && count <= this.size * 20) { - var reservoirSampler = new ReservoirSampler(this.db, this.collectionName, this.opts); - return reservoirSampler - .on('error', this.emit.bind(this, 'error')) - .on('data', this.push.bind(this)) - .on('end', this.push.bind(this, null)); - } - // else, use native sampler - - // add $match stage if a query was specified - this.pipeline = []; - if (Object.keys(this.query).length > 0) { - this.pipeline.push({ - $match: this.query - }); - } - - // only add $sample stage if the result set contains more - // documents than requested - if (count > this.size) { - this.pipeline.push({ - $sample: { - size: this.size - } - }); - } - - // add $project stage if projection (fields) was specified - if (this.fields && Object.keys(this.fields).length > 0) { - this.pipeline.push({ - $project: this.fields - }); - } - - options.raw = this.raw; - options.cursor = this.cursor; - options.batchSize = this.size; - - var cursor = this.collection.aggregate(this.pipeline, options); - - cursor.pipe(rawTransform(this.raw)) - .on('error', this.emit.bind(this, 'error')) - .on('data', this.push.bind(this)) - .on('end', this.push.bind(this, null)); - }.bind(this)); -}; - -module.exports = NativeSampler; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/lib/raw-transform.js b/reverse_engineering/node_modules/mongodb-collection-sample/lib/raw-transform.js deleted file mode 100644 index de5538a..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/lib/raw-transform.js +++ /dev/null @@ -1,25 +0,0 @@ -var Transform = require('stream').Transform; -var BSON = require('bson'); - -module.exports = function rawTransform(raw) { - // split up incoming raw bytes and return documents one by one; NODE-1906 - // this is only necessary for native sampler - function transform(chunk, encoding, cb) { - // only transform for raw bytes - if (raw) { - var response = BSON.deserialize(chunk); - response.cursor.firstBatch.forEach(function(doc) { - this.push(BSON.serialize(doc)); - }.bind(this)); - return cb(); - } - // otherwise go back to the main stream - return cb(null, chunk); - } - - return new Transform({ - readableObjectMode: true, - writableObjectMode: true, - transform: transform - }); -}; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/lib/reservoir-sampler.js b/reverse_engineering/node_modules/mongodb-collection-sample/lib/reservoir-sampler.js deleted file mode 100644 index 46a40d6..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/lib/reservoir-sampler.js +++ /dev/null @@ -1,131 +0,0 @@ -var BaseSampler = require('./base-sampler'); -var inherits = require('util').inherits; -var es = require('event-stream'); -var Reservoir = require('reservoir'); -var _defaults = require('lodash.defaults'); -var _chunk = require('lodash.chunk'); - -var debug = require('debug')('mongodb-collection-sample:reservoir-sampler'); - -var RESERVOIR_SAMPLE_LIMIT = 10000; -var RESERVOIR_CHUNK_SIZE = 1000; - -/** - * Does reservoir sampling and fetches the resulting documents from the - * collection. - * - * The query runs with a limit of `RESERVOIR_SAMPLE_LIMIT`. The reservoir - * then samples `size` _ids from the query result. These _ids get grouped - * into chunks of at most `RESERVOIR_CHUNK_SIZE`. For each chunk, a cursor - * is opened to fetch the actual documents. The cursor streams are combined - * and all the resulting documents are emitted downstream. - - * @param {mongodb.Collection} collection The collection to sample from. - * @param {Number} size How many documents should be returned. - * @param {Object} opts - * @option {Object} query to refine possible samples [default: `{}`]. - * @option {Number} size of the sample to capture [default: `5`]. - * @option {Object} fields to return for each document [default: `null`]. - * @option {Boolean} return document results as raw BSON buffers [default: `false`]. - * @option {Number} chunkSize For chunked $in queries [default: `1000`]. - * @return {stream.Readable} - * @api private - */ -function reservoirStream(collection, size, opts) { - opts = _defaults(opts || {}, { - chunkSize: RESERVOIR_CHUNK_SIZE, - promoteValues: true - }); - var reservoir = new Reservoir(size); - - var stream = es.through( - function write(data) { - // fill reservoir with ids - reservoir.pushSome(data); - }, - function end() { - // split the reservoir of ids into smaller chunks - var chunks = _chunk(reservoir, opts.chunkSize); - // create cursors for chunks - var cursors = chunks.map(function(ids) { - var cursor = collection.find({ _id: { $in: ids }}, { promoteValues: opts.promoteValues, raw: opts.raw }); - if (opts.fields) { - cursor.project(opts.fields); - } - if (opts.maxTimeMS) { - cursor.maxTimeMS(opts.maxTimeMS); - } - return cursor.stream(); - }); - // merge all cursors (order arbitrary) and emit docs - es.merge(cursors).pipe(es.through(function(doc) { - stream.emit('data', doc); - })).on('end', function() { - stream.emit('end'); - }); - } - ); - return stream; -} - -/** - * A readable stream of sample of documents from a collection via - * [reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling). - * - * @param {mongodb.DB} db - * @param {String} collectionName to source from. - * @param {Object} opts - * @option {Object} query to refine possible samples [default: `{}`]. - * @option {Number} size of the sample to capture [default: `5`]. - * @option {Object} fields to return for each document [default: `null`]. - * @option {Number} chunkSize for chunked $in queries [default: `1000`]. - * @api public - */ -function ReservoirSampler(db, collectionName, opts) { - this.running = false; - this.chunkSize = opts ? opts.chunkSize : undefined; - BaseSampler.call(this, db, collectionName, opts); -} -inherits(ReservoirSampler, BaseSampler); - -ReservoirSampler.prototype._read = function() { - if (this.running) { - return; - } - this.running = true; - - debug('using query `%j`', this.query); - this.collection.countDocuments(this.query, function(err, count) { - if (err) { - return this.emit('error', err); - } - - debug('sampling %d documents from a collection with %d documents', - this.size, count); - - this.collection.find(this.query, { - projection: { _id: 1 }, - sort: this.sort, - limit: RESERVOIR_SAMPLE_LIMIT - }) - .stream() - .pipe(es.map(function(obj, cb) { - return cb(null, obj._id); - })) - .pipe(reservoirStream(this.collection, this.size, { - chunkSize: this.chunkSize, - fields: this.fields, - maxTimeMS: this.maxTimeMS, - raw: this.raw, - promoteValues: this.promoteValues - })) - .on('error', this.emit.bind(this, 'error')) - .on('data', this.push.bind(this)) - .on('end', function() { - this.running = false; - this.push(null); - }.bind(this)); - }.bind(this)); -}; - -module.exports = ReservoirSampler; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/HISTORY.md b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/HISTORY.md deleted file mode 100644 index b91cb1d..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/HISTORY.md +++ /dev/null @@ -1,572 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -## [4.6.0](https://github.com/mongodb/js-bson/compare/v4.5.4...v4.6.0) (2021-11-23) - - -### Features - -* **NODE-3740:** Implement root and top level key utf-8 validation settings for BSON ([#472](https://github.com/mongodb/js-bson/issues/472)) ([07019a0](https://github.com/mongodb/js-bson/commit/07019a036ca4a4a15976707099bd949d2c042699)) - - -### Bug Fixes - -* **NODE-3724:** Fix BSONTypeError and BSONError to correctly handle instanceof checks ([#471](https://github.com/mongodb/js-bson/issues/471)) ([d8f334b](https://github.com/mongodb/js-bson/commit/d8f334bd3086ee7764849dd145ad513dd1067eaf)) - -### [4.5.4](https://github.com/mongodb/js-bson/compare/v4.5.3...v4.5.4) (2021-11-03) - - -### Bug Fixes - -* **NODE-3640:** Fix Int32 constructor to coerce its argument to int32 ([#466](https://github.com/mongodb/js-bson/issues/466)) ([d388f1e](https://github.com/mongodb/js-bson/commit/d388f1efc1831ceecec11b79dc564d3116a97779)) -* **NODE-3662:** error checking to make sure that ObjectId results in object with correct properties ([#467](https://github.com/mongodb/js-bson/issues/467)) ([5f99b1b](https://github.com/mongodb/js-bson/commit/5f99b1bfa74bcf75700174f8d4a8b974f9753e7f)) - -### [4.5.3](https://github.com/mongodb/js-bson/compare/v4.5.2...v4.5.3) (2021-10-05) - - -### Bug Fixes - -* **NODE-3493:** code and symbol tests are partially testing the wrong types ([#459](https://github.com/mongodb/js-bson/issues/459)) ([80d7f03](https://github.com/mongodb/js-bson/commit/80d7f039af5472fd51b8a1f7873f4340ed5f0d5e)) -* **NODE-3534:** add subtype 0x6 and 0x7 constants on Binary class ([#461](https://github.com/mongodb/js-bson/issues/461)) ([52cfe9c](https://github.com/mongodb/js-bson/commit/52cfe9c02a2483e197140e9838bf969c6f8e750e)) -* **NODE-3629:** correct corpus runner and add null checks ([#464](https://github.com/mongodb/js-bson/issues/464)) ([d75102d](https://github.com/mongodb/js-bson/commit/d75102d6bb995c5146d7bc1fb8606c1851c8bbc0)) - -### [4.5.2](https://github.com/mongodb/js-bson/compare/v4.5.1...v4.5.2) (2021-09-14) - - -### Bug Fixes - -* **NODE-3021:** fix a long standing bug in Decimal128.fromString() ([#458](https://github.com/mongodb/js-bson/issues/458)) ([824939a](https://github.com/mongodb/js-bson/commit/824939a4a47759b0c422010129480eb121620c83)) -* **NODE-3582:** fix internal marked APIs, add toString methods to Int32 and Double ([#457](https://github.com/mongodb/js-bson/issues/457)) ([b46ab5f](https://github.com/mongodb/js-bson/commit/b46ab5feff2090351be464ab5b180b4aeb675f69)) - -### [4.5.1](https://github.com/mongodb/js-bson/compare/v4.5.0...v4.5.1) (2021-08-24) - - -### Bug Fixes - -* **NODE-3561:** umd bundle fails to require util ([#455](https://github.com/mongodb/js-bson/issues/455)) ([1c15155](https://github.com/mongodb/js-bson/commit/1c151555c76f2b80e699ae9090a256f7dbdfb8ca)) - -## [4.5.0](https://github.com/mongodb/js-bson/compare/v4.4.1...v4.5.0) (2021-08-19) - - -### Features - -* **NODE-3504:** add unambiguous `Timestamp()` constructor overload ([#449](https://github.com/mongodb/js-bson/issues/449)) ([0298dd8](https://github.com/mongodb/js-bson/commit/0298dd8293523869433beccb8c17671b7f9b6fbd)) - - -### Bug Fixes - -* **NODE-3451:** fix performance regression from v1 ([#451](https://github.com/mongodb/js-bson/issues/451)) ([2330ab1](https://github.com/mongodb/js-bson/commit/2330ab1274166c285cbd8a0c3eff5a52573cf34d)) -* **NODE-3520:** global not defined in esm bundles ([#452](https://github.com/mongodb/js-bson/issues/452)) ([cb82a80](https://github.com/mongodb/js-bson/commit/cb82a802aff4039bc397bea2402c5f76450bb0f0)) - -### [4.4.1](https://github.com/mongodb/js-bson/compare/v4.4.0...v4.4.1) (2021-07-06) - - -### Bug Fixes - -* **NODE-3247:** DBRef special handling ([#443](https://github.com/mongodb/js-bson/issues/443)) ([f5d984d](https://github.com/mongodb/js-bson/commit/f5d984d88b2e20310ec5cc3a39b91b0fd1e0b3c9)) -* **NODE-3282:** BSONRegExp options not alphabetized ([#441](https://github.com/mongodb/js-bson/issues/441)) ([18c3512](https://github.com/mongodb/js-bson/commit/18c3512befe54908e4b816056dbde0d1b998d81b)) -* **NODE-3376:** use standard JS methods for copying Buffers ([#444](https://github.com/mongodb/js-bson/issues/444)) ([804050d](https://github.com/mongodb/js-bson/commit/804050d40b03a02116995e63671e05ffa033dc45)) -* **NODE-3390:** serialize non-finite doubles correctly in EJSON ([#445](https://github.com/mongodb/js-bson/issues/445)) ([7eb7998](https://github.com/mongodb/js-bson/commit/7eb79981e16d73a391c567b7f9748943997a424d)) - -## [4.4.0](https://github.com/mongodb/js-bson/compare/v4.3.0...v4.4.0) (2021-05-18) - - -### Features - -* **NODE-3264:** allow Decimal128(string), Long(string), Long(bigint) ([#437](https://github.com/mongodb/js-bson/issues/437)) ([392c1bc](https://github.com/mongodb/js-bson/commit/392c1bcbe003b185f38d64a8a24bc21a6661cb26)) -* make circular input errors for EJSON expressive ([#433](https://github.com/mongodb/js-bson/issues/433)) ([7b351cc](https://github.com/mongodb/js-bson/commit/7b351cc217786e5ee992f0fb64588f9c3fddd828)) - - -### Bug Fixes - -* make Long inspect result evaluable ([3a2eff1](https://github.com/mongodb/js-bson/commit/3a2eff127175c7f94c9ccc940074537b7ad972f1)) -* **NODE-3153:** correctly deserialize `__proto__` properties ([#431](https://github.com/mongodb/js-bson/issues/431)) ([f34cabc](https://github.com/mongodb/js-bson/commit/f34cabc31e66bc809d8e3cc6b0d203739f40aa41)) -* accept Uint8Array where Buffer is accepted ([#432](https://github.com/mongodb/js-bson/issues/432)) ([4613763](https://github.com/mongodb/js-bson/commit/46137636ac8e59010ba3bfdd317d5d13d9d3066d)) -* clean up instanceof usage ([9b6d52a](https://github.com/mongodb/js-bson/commit/9b6d52a84a20641b22732355e56c3bae3fe857f1)) -* improve ArrayBuffer brand check in ensureBuffer ([#429](https://github.com/mongodb/js-bson/issues/429)) ([99722f6](https://github.com/mongodb/js-bson/commit/99722f66d9f5eeb0ab57e74bab26049a425fa3e8)) - -## [4.3.0](https://github.com/mongodb/js-bson/compare/v4.2.3...v4.3.0) (2021-04-06) - - -### Features - -* UUID convenience class ([#425](https://github.com/mongodb/js-bson/issues/425)) ([76e1826](https://github.com/mongodb/js-bson/commit/76e1826eed852d4cca9fafabbcf826af1367c9af)) - -### [4.2.3](https://github.com/mongodb/js-bson/compare/v4.2.2...v4.2.3) (2021-03-02) - - -### Bug Fixes - -* allow library to be loaded in web workeds ([#423](https://github.com/mongodb/js-bson/issues/423)) ([023f57e](https://github.com/mongodb/js-bson/commit/5ae057d3c6dd87e1407dcdc7b8d9da668023f57e)) - -* make inspection result of BSON types evaluable ([#416](https://github.com/mongodb/js-bson/issues/416)) ([616665f](https://github.com/mongodb/js-bson/commit/616665f5e6f7dd06a88de450aaccaa203fa6c652)) -* permit BSON types to be created without new ([#424](https://github.com/mongodb/js-bson/issues/424)) ([d2bc284](https://github.com/mongodb/js-bson/commit/d2bc284943649ac27116701a4ed91ff731a4bdf7)) - -### [4.2.2](https://github.com/mongodb/js-bson/compare/v4.2.1...v4.2.2) (2020-12-01) - - -### Bug Fixes - -* remove tslib usage and fix Long method alias ([#415](https://github.com/mongodb/js-bson/issues/415)) ([2d9a8e6](https://github.com/mongodb/js-bson/commit/2d9a8e678417ec43a0b82377743ab9c30a3c3b6b)) - -### [4.2.1](https://github.com/mongodb/js-bson/compare/v4.2.0...v4.2.1) (2020-12-01) - - -### Bug Fixes - -* backwards compatibility with older BSON package versions ([#411](https://github.com/mongodb/js-bson/issues/411)) ([5167be2](https://github.com/mongodb/js-bson/commit/5167be2752369d5832057f7b69da0e240ed4c204)) -* Downlevel type definitions ([#410](https://github.com/mongodb/js-bson/issues/410)) ([203402f](https://github.com/mongodb/js-bson/commit/203402f5cd9dd496a4103dc1008bad382d3c69c4)) -* make inspect method for ObjectId work ([#412](https://github.com/mongodb/js-bson/issues/412)) ([a585a0c](https://github.com/mongodb/js-bson/commit/a585a0cf8cd1212617fb8f37581194e6c31e33fa)) -* remove stringify overloads ([2df6b42](https://github.com/mongodb/js-bson/commit/2df6b42de4cbf81a307d2db144d15470d543976e)) - -## [4.2.0](https://github.com/mongodb/js-bson/compare/v4.1.0...v4.2.0) (2020-10-13) - - -### Features - -* add extended json parsing for $uuid ([b1b2a0e](https://github.com/mongodb/js-bson/commit/b1b2a0ee5f497c971aa28961cf80bde522fc1779)) -* convert to TypeScript ([#393](https://github.com/mongodb/js-bson/issues/393)) ([9aad874](https://github.com/mongodb/js-bson/commit/9aad8746bbb2159012193a53a206509130a95fb0)) -* Improve TS Typings ([#389](https://github.com/mongodb/js-bson/issues/389)) ([ae9ae2d](https://github.com/mongodb/js-bson/commit/ae9ae2df0d5d0a88adf27523d7fca7f3ad59a57a)) - - -### Bug Fixes - -* adds interfaces for EJSON objects ([7f5f1a3](https://github.com/mongodb/js-bson/commit/7f5f1a38d99d1d50b8bf261cc72916f5bce506ae)) -* Correct API Extractor config to omit definition file from dist ([#407](https://github.com/mongodb/js-bson/issues/407)) ([ace8647](https://github.com/mongodb/js-bson/commit/ace8647646e20df61e77d0ce8ed7ea84a3ff7738)) -* coverage ([992e2e0](https://github.com/mongodb/js-bson/commit/992e2e040806701d1c69e09d07186a6e1deacc0e)) -* deprecate cacheFunctionsCrc32 ([ea83bf5](https://github.com/mongodb/js-bson/commit/ea83bf5200f4a936692f710063941ba802386da4)) -* Rework rollup config to output named and default exports ([#404](https://github.com/mongodb/js-bson/issues/404)) ([a48676b](https://github.com/mongodb/js-bson/commit/a48676b0d442e06a71a413500194d35a7bea7587)) -* Throw on BigInt type values ([#397](https://github.com/mongodb/js-bson/issues/397)) ([2dd54e5](https://github.com/mongodb/js-bson/commit/2dd54e5275fc72dd8cd579a1636d2a73b7b0e790)) -* type issues with SerializeOptions and Long methods accepting Timestamp ([c18ba71](https://github.com/mongodb/js-bson/commit/c18ba71229129c8ea34e40265a9503c10e29a9e0)) - - -# [4.1.0](https://github.com/mongodb/js-bson/compare/v4.0.4...v4.1.0) (2020-08-10) - - -### Bug Fixes - -* spelling in deserializer errors ([4c6f2e4](https://github.com/mongodb/js-bson/commit/4c6f2e4)) -* **object-id:** harden the duck-typing ([4b800ae](https://github.com/mongodb/js-bson/commit/4b800ae)) -* parse value of Int32 in constructor ([5cda40f](https://github.com/mongodb/js-bson/commit/5cda40f)) -* Reduce floating point precision required of extended json implementations ([#369](https://github.com/mongodb/js-bson/issues/369)) ([5e35d1a](https://github.com/mongodb/js-bson/commit/5e35d1a)) - - -### Features - -* add support for primitives to EJSON.stringify ([329857d](https://github.com/mongodb/js-bson/commit/329857d)) - - - - -## [4.0.4](https://github.com/mongodb/js-bson/compare/v4.0.3...v4.0.4) (2020-03-26) - - -### Bug Fixes - -* improve EJSON generation for previously skipped edge cases ([30f5a8f](https://github.com/mongodb/js-bson/commit/30f5a8f)) -* only upgrade `symbol` to `string` if `promoteValues` is true ([067a7ba](https://github.com/mongodb/js-bson/commit/067a7ba)) - - - - -## [4.0.3](https://github.com/mongodb/js-bson/compare/v4.0.2...v4.0.3) (2020-01-09) - - -### Bug Fixes - -* support Number object in Int32 and Double constructors ([fe3f0dc](https://github.com/mongodb/js-bson/commit/fe3f0dc)) -* **Timestamp:** make sure timestamp is always unsigned ([36b2d43](https://github.com/mongodb/js-bson/commit/36b2d43)) - - - - -## [4.0.2](https://github.com/mongodb/js-bson/compare/v4.0.0...v4.0.2) (2019-03-08) - - -### Bug Fixes - -* **buffer:** don't use deprecated Buffer constructors ([7bb9c57](https://github.com/mongodb/js-bson/commit/7bb9c57)) -* **Buffer:** import buffer for binary, decimal128, and fnv1a ([6be7b8d](https://github.com/mongodb/js-bson/commit/6be7b8d)) -* **ejson:** enable serialization of legacy `ObjectID` ([ba98ccb](https://github.com/mongodb/js-bson/commit/ba98ccb)), closes [#303](https://github.com/mongodb/js-bson/issues/303) -* **ejson:** support array for replacer parameter in `EJSON.stringify` ([9f43809](https://github.com/mongodb/js-bson/commit/9f43809)), closes [#303](https://github.com/mongodb/js-bson/issues/303) [#302](https://github.com/mongodb/js-bson/issues/302) [#303](https://github.com/mongodb/js-bson/issues/303) -* **ejson-serialize:** prevent double serialization for nested documents ([ab790c9](https://github.com/mongodb/js-bson/commit/ab790c9)), closes [#303](https://github.com/mongodb/js-bson/issues/303) -* **object-id:** correct serialization of old ObjectID types ([8d57a8c](https://github.com/mongodb/js-bson/commit/8d57a8c)) -* **timestamp:** getTimestamp support times beyond 2038 ([a0820d5](https://github.com/mongodb/js-bson/commit/a0820d5)) -* 4.x-1.x interop (incl. ObjectID _bsontype) ([f4b16d9](https://github.com/mongodb/js-bson/commit/f4b16d9)) - - - - -## [4.0.1](https://github.com/mongodb/js-bson/compare/v4.0.0...v4.0.1) (2018-12-06) - - -### Bug Fixes - -* **object-id:** correct serialization of old ObjectID types ([8d57a8c](https://github.com/mongodb/js-bson/commit/8d57a8c)) - - - - -# [4.0.0](https://github.com/mongodb/js-bson/compare/v3.0.2...v4.0.0) (2018-11-13) - -### Migration Guide - -Please see the [migration guide](https://github.com/mongodb/js-bson/blob/master/docs/upgrade-to-v4.md) for detailed discussion of breaking changes in this release. - -### Bug Fixes - -* **buffer:** replace deprecated Buffer constructor ([5acdebf](https://github.com/mongodb/js-bson/commit/5acdebf)) -* **dbPointer:** fix utf8 bug for dbPointer ([018c769](https://github.com/mongodb/js-bson/commit/018c769)) -* **deserialize:** fix deserialization of 0xFFFD ([c682ae3](https://github.com/mongodb/js-bson/commit/c682ae3)), closes [#277](https://github.com/mongodb/js-bson/issues/277) -* **ext-json:** deserialize doubles as `Number` in relaxed mode ([a767fa1](https://github.com/mongodb/js-bson/commit/a767fa1)) -* **ObjectId:** will now throw if an invalid character is passed ([6f30b4e](https://github.com/mongodb/js-bson/commit/6f30b4e)) -* **ObjectID:** ObjectId.isValid should check buffer length ([06af813](https://github.com/mongodb/js-bson/commit/06af813)) -* **package:** `browser` section needs to point to correct index ([08337e3](https://github.com/mongodb/js-bson/commit/08337e3)) -* **random-bytes:** fallback to insecure path if require is null ([963b12b](https://github.com/mongodb/js-bson/commit/963b12b)) -* **random-bytes:** wrap crypto require in try/catch for fallback ([47fd5f7](https://github.com/mongodb/js-bson/commit/47fd5f7)) -* **serializer:** do not use checkKeys for $clusterTime ([cbb4724](https://github.com/mongodb/js-bson/commit/cbb4724)) -* **serializer:** map insert expects only string keys ([aba3a18](https://github.com/mongodb/js-bson/commit/aba3a18)) - - -### Code Refactoring - -* **symbol:** rename Symbol to BSONSymbol ([5d5b3d2](https://github.com/mongodb/js-bson/commit/5d5b3d2)) - - -### Features - -* **BSON:** simplify and flatten module exports ([f8920c6](https://github.com/mongodb/js-bson/commit/f8920c6)) -* **bsontype:** move all `_bsontypes` to non-enumerable properties ([16f5bf6](https://github.com/mongodb/js-bson/commit/16f5bf6)) -* **ext-json:** add extended JSON codecs directly to BSON types ([10e5f00](https://github.com/mongodb/js-bson/commit/10e5f00)) -* **ext-json:** add extended JSON support to the bson library ([d6b71ab](https://github.com/mongodb/js-bson/commit/d6b71ab)) -* **ext-json:** export EJSON at top level of module ([c356a5a](https://github.com/mongodb/js-bson/commit/c356a5a)) -* **karma:** test bson in the browser ([cd593ca](https://github.com/mongodb/js-bson/commit/cd593ca)) -* **long:** replace long implementatin with long.js ([545900d](https://github.com/mongodb/js-bson/commit/545900d)) - - -### BREAKING CHANGES - -* **ObjectId:** Where code was previously silently erroring, users may now -experience TypeErrors -* **symbol:** This was conflicting with the ES6 Symbol type - - - - -## [3.0.2](https://github.com/mongodb/js-bson/compare/v3.0.1...v3.0.2) (2018-07-13) - - -### Bug Fixes - -* **revert:** Reverting v3.0.1 ([efb0720](https://github.com/mongodb/js-bson/commit/efb0720)) - - - - -# [3.0.0](https://github.com/mongodb/js-bson/compare/v2.0.8...v3.0.0) (2018-06-13) - - -### Features - -* **ObjectID:** use FNV-1a hash for objectId ([4f545b1](https://github.com/mongodb/js-bson/commit/4f545b1)) -* **rollup:** initial commit of rollup-generated bundle ([474b8f7](https://github.com/mongodb/js-bson/commit/474b8f7)) -* **rollup:** switch from webpack to rollup for bundling ([98068fa](https://github.com/mongodb/js-bson/commit/98068fa)) - - - - -## [2.0.8](https://github.com/mongodb/js-bson/compare/v2.0.7...v2.0.8) (2018-06-06) - - -### Bug Fixes - -* **readme:** clarify documentation about deserialize methods ([e311056](https://github.com/mongodb/js-bson/commit/e311056)) -* **serialization:** normalize function stringification ([21eb0b0](https://github.com/mongodb/js-bson/commit/21eb0b0)) - - - - -## [2.0.7](https://github.com/mongodb/js-bson/compare/v2.0.6...v2.0.7) (2018-05-31) - - -### Bug Fixes - -* **binary:** add type checking for buffer ([cbfb25d](https://github.com/mongodb/js-bson/commit/cbfb25d)) - - - - -## [2.0.6](https://github.com/mongodb/js-bson/compare/v2.0.5...v2.0.6) (2018-04-27) - - -### Bug Fixes - -* **deserializeStream:** allow multiple documents to be deserialized ([6fc5984](https://github.com/mongodb/js-bson/commit/6fc5984)), closes [#244](https://github.com/mongodb/js-bson/issues/244) - - - - -## [2.0.5](https://github.com/mongodb/js-bson/compare/v2.0.4...v2.0.5) (2018-04-06) - - -### Bug Fixes - -* **regexp:** properly construct new BSONRegExp when constructor called without new ([#242](https://github.com/mongodb/js-bson/issues/242)) ([93ae799](https://github.com/mongodb/js-bson/commit/93ae799)) - - - - -## [2.0.4](https://github.com/mongodb/js-bson/compare/v2.0.3...v2.0.4) (2018-03-12) - - - - -## [2.0.3](https://github.com/mongodb/js-bson/compare/v2.0.2...v2.0.3) (2018-03-12) - - -### Features - -* **serialization:** support arbitrary sizes for the internal serialization buffer ([a6bd45c](https://github.com/mongodb/js-bson/commit/a6bd45c)) - - - - -## [2.0.2](https://github.com/mongodb/js-bson/compare/v2.0.1...v2.0.2) (2018-03-02) - - -### Bug Fixes - -* make sure all functions are named consistently ([6df9022](https://github.com/mongodb/js-bson/commit/6df9022)) - - - - -## [2.0.1](https://github.com/mongodb/js-bson/compare/v2.0.0...v2.0.1) (2018-02-28) - - -### Bug Fixes - -* **serializer:** ensure RegExp options are alphabetically sorted ([d60659d](https://github.com/mongodb/js-bson/commit/d60659d)) - - -### Features - -* **db-ref:** support passing a namespace into a DBRef ctor ([604831b](https://github.com/mongodb/js-bson/commit/604831b)) - - - - -# 2.0.0 (2018-02-26) - - -### Bug Fixes - -* **browser:** fixing browser property in package.json ([095fba9](https://github.com/mongodb/js-bson/commit/095fba9)) -* **dbref:** only upgrade objects with allowed $keys to DBRefs ([98eb9e2](https://github.com/mongodb/js-bson/commit/98eb9e2)) -* **decimal128:** add basic guard against REDOS attacks ([511ecc4](https://github.com/mongodb/js-bson/commit/511ecc4)) -* **Decimal128:** update toString and fromString methods to correctly handle the case of too many significant digits ([25ed43e](https://github.com/mongodb/js-bson/commit/25ed43e)) -* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) -* **serializeWithBufferAndIndex:** write documents to start of intermediate buffer ([b4e4ac5](https://github.com/mongodb/js-bson/commit/b4e4ac5)) - - - -1.0.4 2016-01-11 ----------------- -- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. - -1.0.3 2016-01-03 ----------------- -- Fixed toString for ObjectId so it will work with inspect. - -1.0.2 2016-01-02 ----------------- -- Minor optimizations for ObjectID to use Buffer.from where available. - -1.0.1 2016-12-06 ----------------- -- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. - -1.0.0 2016-12-06 ----------------- -- Introduced new BSON API and documentation. - -0.5.7 2016-11-18 ------------------ -- NODE-848 BSON Regex flags must be alphabetically ordered. - -0.5.6 2016-10-19 ------------------ -- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. -- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). - -0.5.5 2016-09-15 ------------------ -- Added DBPointer up conversion to DBRef - -0.5.4 2016-08-23 ------------------ -- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. - -0.5.3 2016-07-11 ------------------ -- Throw error if ObjectId is not a string or a buffer. - -0.5.2 2016-07-11 ------------------ -- All values encoded big-endian style for ObjectId. - -0.5.1 2016-07-11 ------------------ -- Fixed encoding/decoding issue in ObjectId timestamp generation. -- Removed BinaryParser dependency from the serializer/deserializer. - -0.5.0 2016-07-05 ------------------ -- Added Decimal128 type and extended test suite to include entire bson corpus. - -0.4.23 2016-04-08 ------------------ -- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. -- Remove one package from dependency due to having been pulled from NPM. - -0.4.22 2016-03-04 ------------------ -- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). -- Fixed issue with undefined type on deserializing. - -0.4.21 2016-01-12 ------------------ -- Minor optimizations to avoid non needed object creation. - -0.4.20 2015-10-15 ------------------ -- Added bower file to repository. -- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) - -0.4.19 2015-10-15 ------------------ -- Remove all support for bson-ext. - -0.4.18 2015-10-15 ------------------ -- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 -- add option for deserializing binary into Buffer object #116 - -0.4.17 2015-10-15 ------------------ -- Validate regexp string for null bytes and throw if there is one. - -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/LICENSE.md b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/LICENSE.md deleted file mode 100644 index 261eeb9..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/README.md b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/README.md deleted file mode 100644 index cd7242f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/README.md +++ /dev/null @@ -1,376 +0,0 @@ -# BSON parser - -BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org). - -This browser version of the BSON parser is compiled using [rollup](https://rollupjs.org/) and the current version is pre-compiled in the `dist` directory. - -This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). - -### Table of Contents -- [Usage](#usage) -- [Bugs/Feature Requests](#bugs--feature-requests) -- [Installation](#installation) -- [Documentation](#documentation) -- [FAQ](#faq) - -## Bugs / Feature Requests - -Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA: - -1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org) -2. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE) -3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are **public**. - -## Usage - -To build a new version perform the following operations: - -``` -npm install -npm run build -``` - -### Node (no bundling) -A simple example of how to use BSON in `Node.js`: - -```js -const BSON = require('bson'); -const Long = BSON.Long; - -// Serialize a document -const doc = { long: Long.fromNumber(100) }; -const data = BSON.serialize(doc); -console.log('data:', data); - -// Deserialize the resulting Buffer -const doc_2 = BSON.deserialize(data); -console.log('doc_2:', doc_2); -``` - -### Browser (no bundling) - -If you are not using a bundler like webpack, you can include `dist/bson.bundle.js` using a script tag. It includes polyfills for built-in node types like `Buffer`. - -```html - - - -``` - -### Using webpack - -If using webpack, you can use your normal import/require syntax of your project to pull in the `bson` library. - -ES6 Example: - -```js -import { Long, serialize, deserialize } from 'bson'; - -// Serialize a document -const doc = { long: Long.fromNumber(100) }; -const data = serialize(doc); -console.log('data:', data); - -// De serialize it again -const doc_2 = deserialize(data); -console.log('doc_2:', doc_2); -``` - -ES5 Example: - -```js -const BSON = require('bson'); -const Long = BSON.Long; - -// Serialize a document -const doc = { long: Long.fromNumber(100) }; -const data = BSON.serialize(doc); -console.log('data:', data); - -// Deserialize the resulting Buffer -const doc_2 = BSON.deserialize(data); -console.log('doc_2:', doc_2); -``` - -Depending on your settings, webpack will under the hood resolve to one of the following: - -- `dist/bson.browser.esm.js` If your project is in the browser and using ES6 modules (Default for `webworker` and `web` targets) -- `dist/bson.browser.umd.js` If your project is in the browser and not using ES6 modules -- `dist/bson.esm.js` If your project is in Node.js and using ES6 modules (Default for `node` targets) -- `lib/bson.js` (the normal include path) If your project is in Node.js and not using ES6 modules - -For more information, see [this page on webpack's `resolve.mainFields`](https://webpack.js.org/configuration/resolve/#resolvemainfields) and [the `package.json` for this project](./package.json#L52) - -### Usage with Angular - -Starting with Angular 6, Angular CLI removed the shim for `global` and other node built-in variables (original comment [here](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063)). If you are using BSON with Angular, you may need to add the following shim to your `polyfills.ts` file: - -```js -// In polyfills.ts -(window as any).global = window; -``` - -- [Original Comment by Angular CLI](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063) -- [Original Source for Solution](https://stackoverflow.com/a/50488337/4930088) - -## Installation - -`npm install bson` - -## Documentation - -### Objects - -
-
EJSON : object
-
-
- -### Functions - -
-
setInternalBufferSize(size)
-

Sets the size of the internal serialization buffer.

-
-
serialize(object)Buffer
-

Serialize a Javascript object.

-
-
serializeWithBufferAndIndex(object, buffer)Number
-

Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.

-
-
deserialize(buffer)Object
-

Deserialize data as BSON.

-
-
calculateObjectSize(object)Number
-

Calculate the bson size for a passed in Javascript object.

-
-
deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options])Number
-

Deserialize stream data as BSON documents.

-
-
- - - -### EJSON - -* [EJSON](#EJSON) - - * [.parse(text, [options])](#EJSON.parse) - - * [.stringify(value, [replacer], [space], [options])](#EJSON.stringify) - - * [.serialize(bson, [options])](#EJSON.serialize) - - * [.deserialize(ejson, [options])](#EJSON.deserialize) - - - - -#### *EJSON*.parse(text, [options]) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| text | string | | | -| [options] | object | | Optional settings | -| [options.relaxed] | boolean | true | Attempt to return native JS types where possible, rather than BSON types (if true) | - -Parse an Extended JSON string, constructing the JavaScript value or object described by that -string. - -**Example** -```js -const { EJSON } = require('bson'); -const text = '{ "int32": { "$numberInt": "10" } }'; - -// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } -console.log(EJSON.parse(text, { relaxed: false })); - -// prints { int32: 10 } -console.log(EJSON.parse(text)); -``` - - -#### *EJSON*.stringify(value, [replacer], [space], [options]) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| value | object | | The value to convert to extended JSON | -| [replacer] | function \| array | | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | -| [space] | string \| number | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | -| [options] | object | | Optional settings | -| [options.relaxed] | boolean | true | Enabled Extended JSON's `relaxed` mode | -| [options.legacy] | boolean | true | Output in Extended JSON v1 | - -Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer -function is specified or optionally including only the specified properties if a replacer array -is specified. - -**Example** -```js -const { EJSON } = require('bson'); -const Int32 = require('mongodb').Int32; -const doc = { int32: new Int32(10) }; - -// prints '{"int32":{"$numberInt":"10"}}' -console.log(EJSON.stringify(doc, { relaxed: false })); - -// prints '{"int32":10}' -console.log(EJSON.stringify(doc)); -``` - - -#### *EJSON*.serialize(bson, [options]) - -| Param | Type | Description | -| --- | --- | --- | -| bson | object | The object to serialize | -| [options] | object | Optional settings passed to the `stringify` function | - -Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - - - -#### *EJSON*.deserialize(ejson, [options]) - -| Param | Type | Description | -| --- | --- | --- | -| ejson | object | The Extended JSON object to deserialize | -| [options] | object | Optional settings passed to the parse method | - -Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - - - -### setInternalBufferSize(size) - -| Param | Type | Description | -| --- | --- | --- | -| size | number | The desired size for the internal serialization buffer | - -Sets the size of the internal serialization buffer. - - - -### serialize(object) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| object | Object | | the Javascript object to serialize. | -| [options.checkKeys] | Boolean | | the serializer will check if keys are valid. | -| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | -| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | - -Serialize a Javascript object. - -**Returns**: Buffer - returns the Buffer object containing the serialized object. - - -### serializeWithBufferAndIndex(object, buffer) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| object | Object | | the Javascript object to serialize. | -| buffer | Buffer | | the Buffer you pre-allocated to store the serialized BSON object. | -| [options.checkKeys] | Boolean | | the serializer will check if keys are valid. | -| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | -| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | -| [options.index] | Number | | the index in the buffer where we wish to start serializing into. | - -Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - -**Returns**: Number - returns the index pointing to the last written byte in the buffer. - - -### deserialize(buffer) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| buffer | Buffer | | the buffer containing the serialized set of BSON documents. | -| [options.evalFunctions] | Object | false | evaluate functions in the BSON document scoped to the object deserialized. | -| [options.cacheFunctions] | Object | false | cache evaluated functions for reuse. | -| [options.promoteLongs] | Object | true | when deserializing a Long will fit it into a Number if it's smaller than 53 bits | -| [options.promoteBuffers] | Object | false | when deserializing a Binary will return it as a node.js Buffer instance. | -| [options.promoteValues] | Object | false | when deserializing will promote BSON values to their Node.js closest equivalent types. | -| [options.fieldsAsRaw] | Object | | allow to specify if there what fields we wish to return as unserialized raw buffer. | -| [options.bsonRegExp] | Object | false | return BSON regular expressions as BSONRegExp instances. | -| [options.allowObjectSmallerThanBufferSize] | boolean | false | allows the buffer to be larger than the parsed BSON object | - -Deserialize data as BSON. - -**Returns**: Object - returns the deserialized Javascript Object. - - -### calculateObjectSize(object) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| object | Object | | the Javascript object to calculate the BSON byte size for. | -| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | -| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | - -Calculate the bson size for a passed in Javascript object. - -**Returns**: Number - returns the number of bytes the BSON object will take up. - - -### deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options]) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| data | Buffer | | the buffer containing the serialized set of BSON documents. | -| startIndex | Number | | the start index in the data Buffer where the deserialization is to start. | -| numberOfDocuments | Number | | number of documents to deserialize. | -| documents | Array | | an array where to store the deserialized documents. | -| docStartIndex | Number | | the index in the documents array from where to start inserting documents. | -| [options] | Object | | additional options used for the deserialization. | -| [options.evalFunctions] | Object | false | evaluate functions in the BSON document scoped to the object deserialized. | -| [options.cacheFunctions] | Object | false | cache evaluated functions for reuse. | -| [options.promoteLongs] | Object | true | when deserializing a Long will fit it into a Number if it's smaller than 53 bits | -| [options.promoteBuffers] | Object | false | when deserializing a Binary will return it as a node.js Buffer instance. | -| [options.promoteValues] | Object | false | when deserializing will promote BSON values to their Node.js closest equivalent types. | -| [options.fieldsAsRaw] | Object | | allow to specify if there what fields we wish to return as unserialized raw buffer. | -| [options.bsonRegExp] | Object | false | return BSON regular expressions as BSONRegExp instances. | - -Deserialize stream data as BSON documents. - -**Returns**: Number - returns the next index in the buffer after deserialization **x** numbers of documents. - -## FAQ - -#### Why does `undefined` get converted to `null`? - -The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. - -#### How do I add custom serialization logic? - -This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. - -```javascript -const BSON = require('bson'); - -class CustomSerialize { - toBSON() { - return 42; - } -} - -const obj = { answer: new CustomSerialize() }; -// "{ answer: 42 }" -console.log(BSON.deserialize(BSON.serialize(obj))); -``` diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/bower.json b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/bower.json deleted file mode 100644 index 31eab34..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/bower.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "author": "Christian Amor Kvalheim ", - "main": "./dist/bson.js", - "license": "Apache-2.0", - "moduleType": [ - "globals", - "node" - ], - "ignore": [ - "**/.*", - "alternate_parsers", - "benchmarks", - "bower_components", - "node_modules", - "test", - "tools" - ], - "version": "4.6.0" -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/bson.d.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/bson.d.ts deleted file mode 100644 index 1fabab1..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/bson.d.ts +++ /dev/null @@ -1,1118 +0,0 @@ -import { Buffer } from 'buffer'; -/** - * A class representation of the BSON Binary type. - * @public - */ -export declare class Binary { - _bsontype: 'Binary'; - /* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */ - /** Initial buffer default size */ - static readonly BUFFER_SIZE = 256; - /** Default BSON type */ - static readonly SUBTYPE_DEFAULT = 0; - /** Function BSON type */ - static readonly SUBTYPE_FUNCTION = 1; - /** Byte Array BSON type */ - static readonly SUBTYPE_BYTE_ARRAY = 2; - /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ - static readonly SUBTYPE_UUID_OLD = 3; - /** UUID BSON type */ - static readonly SUBTYPE_UUID = 4; - /** MD5 BSON type */ - static readonly SUBTYPE_MD5 = 5; - /** Encrypted BSON type */ - static readonly SUBTYPE_ENCRYPTED = 6; - /** Column BSON type */ - static readonly SUBTYPE_COLUMN = 7; - /** User BSON type */ - static readonly SUBTYPE_USER_DEFINED = 128; - buffer: Buffer; - sub_type: number; - position: number; - /** - * @param buffer - a buffer object containing the binary data. - * @param subType - the option binary type. - */ - constructor(buffer?: string | BinarySequence, subType?: number); - /** - * Updates this binary with byte_value. - * - * @param byteValue - a single byte we wish to write. - */ - put(byteValue: string | number | Uint8Array | Buffer | number[]): void; - /** - * Writes a buffer or string to the binary. - * - * @param sequence - a string or buffer to be written to the Binary BSON object. - * @param offset - specify the binary of where to write the content. - */ - write(sequence: string | BinarySequence, offset: number): void; - /** - * Reads **length** bytes starting at **position**. - * - * @param position - read from the given position in the Binary. - * @param length - the number of bytes to read. - */ - read(position: number, length: number): BinarySequence; - /** - * Returns the value of this binary as a string. - * @param asRaw - Will skip converting to a string - * @remarks - * This is handy when calling this function conditionally for some key value pairs and not others - */ - value(asRaw?: boolean): string | BinarySequence; - /** the length of the binary sequence */ - length(): number; - toJSON(): string; - toString(format?: string): string; - /* Excluded from this release type: toExtendedJSON */ - toUUID(): UUID; - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface BinaryExtended { - $binary: { - subType: string; - base64: string; - }; -} -/** @public */ -export declare interface BinaryExtendedLegacy { - $type: string; - $binary: string; -} -/** @public */ -export declare type BinarySequence = Uint8Array | Buffer | number[]; -/** - * BSON default export - * @deprecated Please use named exports - * @privateRemarks - * We want to someday deprecate the default export, - * so none of the new TS types are being exported on the default - * @public - */ -declare const BSON: { - Binary: typeof Binary; - Code: typeof Code; - DBRef: typeof DBRef; - Decimal128: typeof Decimal128; - Double: typeof Double; - Int32: typeof Int32; - Long: typeof Long; - UUID: typeof UUID; - Map: MapConstructor; - MaxKey: typeof MaxKey; - MinKey: typeof MinKey; - ObjectId: typeof ObjectId; - ObjectID: typeof ObjectId; - BSONRegExp: typeof BSONRegExp; - BSONSymbol: typeof BSONSymbol; - Timestamp: typeof Timestamp; - EJSON: typeof EJSON; - setInternalBufferSize: typeof setInternalBufferSize; - serialize: typeof serialize; - serializeWithBufferAndIndex: typeof serializeWithBufferAndIndex; - deserialize: typeof deserialize; - calculateObjectSize: typeof calculateObjectSize; - deserializeStream: typeof deserializeStream; - BSONError: typeof BSONError; - BSONTypeError: typeof BSONTypeError; -}; -export default BSON; -/* Excluded from this release type: BSON_BINARY_SUBTYPE_BYTE_ARRAY */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_COLUMN */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_ENCRYPTED */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_FUNCTION */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_MD5 */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_USER_DEFINED */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_UUID */ -/* Excluded from this release type: BSON_BINARY_SUBTYPE_UUID_NEW */ -/* Excluded from this release type: BSON_DATA_ARRAY */ -/* Excluded from this release type: BSON_DATA_BINARY */ -/* Excluded from this release type: BSON_DATA_BOOLEAN */ -/* Excluded from this release type: BSON_DATA_CODE */ -/* Excluded from this release type: BSON_DATA_CODE_W_SCOPE */ -/* Excluded from this release type: BSON_DATA_DATE */ -/* Excluded from this release type: BSON_DATA_DBPOINTER */ -/* Excluded from this release type: BSON_DATA_DECIMAL128 */ -/* Excluded from this release type: BSON_DATA_INT */ -/* Excluded from this release type: BSON_DATA_LONG */ -/* Excluded from this release type: BSON_DATA_MAX_KEY */ -/* Excluded from this release type: BSON_DATA_MIN_KEY */ -/* Excluded from this release type: BSON_DATA_NULL */ -/* Excluded from this release type: BSON_DATA_NUMBER */ -/* Excluded from this release type: BSON_DATA_OBJECT */ -/* Excluded from this release type: BSON_DATA_OID */ -/* Excluded from this release type: BSON_DATA_REGEXP */ -/* Excluded from this release type: BSON_DATA_STRING */ -/* Excluded from this release type: BSON_DATA_SYMBOL */ -/* Excluded from this release type: BSON_DATA_TIMESTAMP */ -/* Excluded from this release type: BSON_DATA_UNDEFINED */ -/* Excluded from this release type: BSON_INT32_MAX */ -/* Excluded from this release type: BSON_INT32_MIN */ -/* Excluded from this release type: BSON_INT64_MAX */ -/* Excluded from this release type: BSON_INT64_MIN */ -/** @public */ -export declare class BSONError extends Error { - constructor(message: string); - readonly name: string; -} -/** - * A class representation of the BSON RegExp type. - * @public - */ -export declare class BSONRegExp { - _bsontype: 'BSONRegExp'; - pattern: string; - options: string; - /** - * @param pattern - The regular expression pattern to match - * @param options - The regular expression options - */ - constructor(pattern: string, options?: string); - static parseOptions(options?: string): string; -} -/** @public */ -export declare interface BSONRegExpExtended { - $regularExpression: { - pattern: string; - options: string; - }; -} -/** @public */ -export declare interface BSONRegExpExtendedLegacy { - $regex: string | BSONRegExp; - $options: string; -} -/** - * A class representation of the BSON Symbol type. - * @public - */ -export declare class BSONSymbol { - _bsontype: 'Symbol'; - value: string; - /** - * @param value - the string representing the symbol. - */ - constructor(value: string); - /** Access the wrapped string value. */ - valueOf(): string; - toString(): string; - /* Excluded from this release type: inspect */ - toJSON(): string; -} -/** @public */ -export declare interface BSONSymbolExtended { - $symbol: string; -} -/** @public */ -export declare class BSONTypeError extends TypeError { - constructor(message: string); - readonly name: string; -} -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param object - the Javascript object to calculate the BSON byte size for - * @returns size of BSON object in bytes - * @public - */ -export declare function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number; -/** @public */ -export declare type CalculateObjectSizeOptions = Pick; -/** - * A class representation of the BSON Code type. - * @public - */ -export declare class Code { - _bsontype: 'Code'; - code: string | Function; - scope?: Document; - /** - * @param code - a string or function. - * @param scope - an optional scope for the function. - */ - constructor(code: string | Function, scope?: Document); - toJSON(): { - code: string | Function; - scope?: Document; - }; - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface CodeExtended { - $code: string | Function; - $scope?: Document; -} -/** - * A class representation of the BSON DBRef type. - * @public - */ -export declare class DBRef { - _bsontype: 'DBRef'; - collection: string; - oid: ObjectId; - db?: string; - fields: Document; - /** - * @param collection - the collection name. - * @param oid - the reference ObjectId. - * @param db - optional db name, if omitted the reference is local to the current db. - */ - constructor(collection: string, oid: ObjectId, db?: string, fields?: Document); - /* Excluded from this release type: namespace */ - /* Excluded from this release type: namespace */ - toJSON(): DBRefLike & Document; - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface DBRefLike { - $ref: string; - $id: ObjectId; - $db?: string; -} -/** - * A class representation of the BSON Decimal128 type. - * @public - */ -export declare class Decimal128 { - _bsontype: 'Decimal128'; - readonly bytes: Buffer; - /** - * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, - * or a string representation as returned by .toString() - */ - constructor(bytes: Buffer | string); - /** - * Create a Decimal128 instance from a string representation - * - * @param representation - a numeric string representation. - */ - static fromString(representation: string): Decimal128; - /** Create a string representation of the raw Decimal128 value */ - toString(): string; - toJSON(): Decimal128Extended; - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface Decimal128Extended { - $numberDecimal: string; -} -/** - * Deserialize data as BSON. - * - * @param buffer - the buffer containing the serialized set of BSON documents. - * @returns returns the deserialized Javascript Object. - * @public - */ -export declare function deserialize(buffer: Buffer | ArrayBufferView | ArrayBuffer, options?: DeserializeOptions): Document; -/** @public */ -export declare interface DeserializeOptions { - /** evaluate functions in the BSON document scoped to the object deserialized. */ - evalFunctions?: boolean; - /** cache evaluated functions for reuse. */ - cacheFunctions?: boolean; - /** - * use a crc32 code for caching, otherwise use the string of the function. - * @deprecated this option to use the crc32 function never worked as intended - * due to the fact that the crc32 function itself was never implemented. - * */ - cacheFunctionsCrc32?: boolean; - /** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */ - promoteLongs?: boolean; - /** when deserializing a Binary will return it as a node.js Buffer instance. */ - promoteBuffers?: boolean; - /** when deserializing will promote BSON values to their Node.js closest equivalent types. */ - promoteValues?: boolean; - /** allow to specify if there what fields we wish to return as unserialized raw buffer. */ - fieldsAsRaw?: Document; - /** return BSON regular expressions as BSONRegExp instances. */ - bsonRegExp?: boolean; - /** allows the buffer to be larger than the parsed BSON object */ - allowObjectSmallerThanBufferSize?: boolean; - /** Offset into buffer to begin reading document from */ - index?: number; - raw?: boolean; - /** Allows for opt-out utf-8 validation for all keys or - * specified keys. Must be all true or all false. - * - * @example - * ```js - * // disables validation on all keys - * validation: { utf8: false } - * - * // enables validation only on specified keys a, b, and c - * validation: { utf8: { a: true, b: true, c: true } } - * - * // disables validation only on specified keys a, b - * validation: { utf8: { a: false, b: false } } - * ``` - */ - validation?: { - utf8: boolean | Record | Record; - }; -} -/** - * Deserialize stream data as BSON documents. - * - * @param data - the buffer containing the serialized set of BSON documents. - * @param startIndex - the start index in the data Buffer where the deserialization is to start. - * @param numberOfDocuments - number of documents to deserialize. - * @param documents - an array where to store the deserialized documents. - * @param docStartIndex - the index in the documents array from where to start inserting documents. - * @param options - additional options used for the deserialization. - * @returns next index in the buffer after deserialization **x** numbers of documents. - * @public - */ -export declare function deserializeStream(data: Buffer | ArrayBufferView | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number; -/** @public */ -export declare interface Document { - [key: string]: any; -} -/** - * A class representation of the BSON Double type. - * @public - */ -export declare class Double { - _bsontype: 'Double'; - value: number; - /** - * Create a Double type - * - * @param value - the number we want to represent as a double. - */ - constructor(value: number); - /** - * Access the number value. - * - * @returns returns the wrapped double number. - */ - valueOf(): number; - toJSON(): number; - toString(radix?: number): string; - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface DoubleExtended { - $numberDouble: string; -} -/** - * EJSON parse / stringify API - * @public - */ -export declare namespace EJSON { - export interface Options { - /** Output using the Extended JSON v1 spec */ - legacy?: boolean; - /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */ - relaxed?: boolean; - /** - * Disable Extended JSON's `relaxed` mode, which attempts to return BSON types where possible, rather than native JS types - * @deprecated Please use the relaxed property instead - */ - strict?: boolean; - } - /** - * Parse an Extended JSON string, constructing the JavaScript value or object described by that - * string. - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const text = '{ "int32": { "$numberInt": "10" } }'; - * - * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } - * console.log(EJSON.parse(text, { relaxed: false })); - * - * // prints { int32: 10 } - * console.log(EJSON.parse(text)); - * ``` - */ - export function parse(text: string, options?: EJSON.Options): SerializableTypes; - export type JSONPrimitive = string | number | boolean | null; - export type SerializableTypes = Document | Array | JSONPrimitive; - /** - * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer - * function is specified or optionally including only the specified properties if a replacer array - * is specified. - * - * @param value - The value to convert to extended JSON - * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string - * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. - * @param options - Optional settings - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const Int32 = require('mongodb').Int32; - * const doc = { int32: new Int32(10) }; - * - * // prints '{"int32":{"$numberInt":"10"}}' - * console.log(EJSON.stringify(doc, { relaxed: false })); - * - * // prints '{"int32":10}' - * console.log(EJSON.stringify(doc)); - * ``` - */ - export function stringify(value: SerializableTypes, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSON.Options, space?: string | number, options?: EJSON.Options): string; - /** - * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - * - * @param value - The object to serialize - * @param options - Optional settings passed to the `stringify` function - */ - export function serialize(value: SerializableTypes, options?: EJSON.Options): Document; - /** - * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - * - * @param ejson - The Extended JSON object to deserialize - * @param options - Optional settings passed to the parse method - */ - export function deserialize(ejson: Document, options?: EJSON.Options): SerializableTypes; -} -/** @public */ -export declare type EJSONOptions = EJSON.Options; -/** - * A class representation of a BSON Int32 type. - * @public - */ -export declare class Int32 { - _bsontype: 'Int32'; - value: number; - /** - * Create an Int32 type - * - * @param value - the number we want to represent as an int32. - */ - constructor(value: number | string); - /** - * Access the number value. - * - * @returns returns the wrapped int32 number. - */ - valueOf(): number; - toString(radix?: number): string; - toJSON(): number; - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface Int32Extended { - $numberInt: string; -} -declare const kId: unique symbol; -declare const kId_2: unique symbol; -/** - * A class representing a 64-bit integer - * @public - * @remarks - * The internal representation of a long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16 bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. - */ -export declare class Long { - _bsontype: 'Long'; - /** An indicator used to reliably determine if an object is a Long or not. */ - __isLong__: true; - /** - * The high 32 bits as a signed value. - */ - high: number; - /** - * The low 32 bits as a signed value. - */ - low: number; - /** - * Whether unsigned or not. - */ - unsigned: boolean; - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * - * Acceptable signatures are: - * - Long(low, high, unsigned?) - * - Long(bigint, unsigned?) - * - Long(string, unsigned?) - * - * @param low - The low (signed) 32 bits of the long - * @param high - The high (signed) 32 bits of the long - * @param unsigned - Whether unsigned or not, defaults to signed - */ - constructor(low?: number | bigint | string, high?: number | boolean, unsigned?: boolean); - static TWO_PWR_24: Long; - /** Maximum unsigned value. */ - static MAX_UNSIGNED_VALUE: Long; - /** Signed zero */ - static ZERO: Long; - /** Unsigned zero. */ - static UZERO: Long; - /** Signed one. */ - static ONE: Long; - /** Unsigned one. */ - static UONE: Long; - /** Signed negative one. */ - static NEG_ONE: Long; - /** Maximum signed value. */ - static MAX_VALUE: Long; - /** Minimum signed value. */ - static MIN_VALUE: Long; - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. - * Each is assumed to use 32 bits. - * @param lowBits - The low 32 bits - * @param highBits - The high 32 bits - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; - /** - * Returns a Long representing the given 32 bit integer value. - * @param value - The 32 bit integer in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromInt(value: number, unsigned?: boolean): Long; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromNumber(value: number, unsigned?: boolean): Long; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBigInt(value: bigint, unsigned?: boolean): Long; - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param str - The textual representation of the Long - * @param unsigned - Whether unsigned or not, defaults to signed - * @param radix - The radix in which the text is written (2-36), defaults to 10 - * @returns The corresponding Long value - */ - static fromString(str: string, unsigned?: boolean, radix?: number): Long; - /** - * Creates a Long from its byte representation. - * @param bytes - Byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @param le - Whether little or big endian, defaults to big endian - * @returns The corresponding Long value - */ - static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long; - /** - * Creates a Long from its little endian byte representation. - * @param bytes - Little endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBytesLE(bytes: number[], unsigned?: boolean): Long; - /** - * Creates a Long from its big endian byte representation. - * @param bytes - Big endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBytesBE(bytes: number[], unsigned?: boolean): Long; - /** - * Tests if the specified object is a Long. - */ - static isLong(value: any): value is Long; - /** - * Converts the specified value to a Long. - * @param unsigned - Whether unsigned or not, defaults to signed - */ - static fromValue(val: number | string | { - low: number; - high: number; - unsigned?: boolean; - }, unsigned?: boolean): Long; - /** Returns the sum of this and the specified Long. */ - add(addend: string | number | Long | Timestamp): Long; - /** - * Returns the sum of this and the specified Long. - * @returns Sum - */ - and(other: string | number | Long | Timestamp): Long; - /** - * Compares this Long's value with the specified's. - * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater - */ - compare(other: string | number | Long | Timestamp): 0 | 1 | -1; - /** This is an alias of {@link Long.compare} */ - comp(other: string | number | Long | Timestamp): 0 | 1 | -1; - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. - * @returns Quotient - */ - divide(divisor: string | number | Long | Timestamp): Long; - /**This is an alias of {@link Long.divide} */ - div(divisor: string | number | Long | Timestamp): Long; - /** - * Tests if this Long's value equals the specified's. - * @param other - Other value - */ - equals(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long.equals} */ - eq(other: string | number | Long | Timestamp): boolean; - /** Gets the high 32 bits as a signed integer. */ - getHighBits(): number; - /** Gets the high 32 bits as an unsigned integer. */ - getHighBitsUnsigned(): number; - /** Gets the low 32 bits as a signed integer. */ - getLowBits(): number; - /** Gets the low 32 bits as an unsigned integer. */ - getLowBitsUnsigned(): number; - /** Gets the number of bits needed to represent the absolute value of this Long. */ - getNumBitsAbs(): number; - /** Tests if this Long's value is greater than the specified's. */ - greaterThan(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long.greaterThan} */ - gt(other: string | number | Long | Timestamp): boolean; - /** Tests if this Long's value is greater than or equal the specified's. */ - greaterThanOrEqual(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - gte(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - ge(other: string | number | Long | Timestamp): boolean; - /** Tests if this Long's value is even. */ - isEven(): boolean; - /** Tests if this Long's value is negative. */ - isNegative(): boolean; - /** Tests if this Long's value is odd. */ - isOdd(): boolean; - /** Tests if this Long's value is positive. */ - isPositive(): boolean; - /** Tests if this Long's value equals zero. */ - isZero(): boolean; - /** Tests if this Long's value is less than the specified's. */ - lessThan(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long#lessThan}. */ - lt(other: string | number | Long | Timestamp): boolean; - /** Tests if this Long's value is less than or equal the specified's. */ - lessThanOrEqual(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long.lessThanOrEqual} */ - lte(other: string | number | Long | Timestamp): boolean; - /** Returns this Long modulo the specified. */ - modulo(divisor: string | number | Long | Timestamp): Long; - /** This is an alias of {@link Long.modulo} */ - mod(divisor: string | number | Long | Timestamp): Long; - /** This is an alias of {@link Long.modulo} */ - rem(divisor: string | number | Long | Timestamp): Long; - /** - * Returns the product of this and the specified Long. - * @param multiplier - Multiplier - * @returns Product - */ - multiply(multiplier: string | number | Long | Timestamp): Long; - /** This is an alias of {@link Long.multiply} */ - mul(multiplier: string | number | Long | Timestamp): Long; - /** Returns the Negation of this Long's value. */ - negate(): Long; - /** This is an alias of {@link Long.negate} */ - neg(): Long; - /** Returns the bitwise NOT of this Long. */ - not(): Long; - /** Tests if this Long's value differs from the specified's. */ - notEquals(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long.notEquals} */ - neq(other: string | number | Long | Timestamp): boolean; - /** This is an alias of {@link Long.notEquals} */ - ne(other: string | number | Long | Timestamp): boolean; - /** - * Returns the bitwise OR of this Long and the specified. - */ - or(other: number | string | Long): Long; - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - shiftLeft(numBits: number | Long): Long; - /** This is an alias of {@link Long.shiftLeft} */ - shl(numBits: number | Long): Long; - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - shiftRight(numBits: number | Long): Long; - /** This is an alias of {@link Long.shiftRight} */ - shr(numBits: number | Long): Long; - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - shiftRightUnsigned(numBits: Long | number): Long; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - shr_u(numBits: number | Long): Long; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - shru(numBits: number | Long): Long; - /** - * Returns the difference of this and the specified Long. - * @param subtrahend - Subtrahend - * @returns Difference - */ - subtract(subtrahend: string | number | Long | Timestamp): Long; - /** This is an alias of {@link Long.subtract} */ - sub(subtrahend: string | number | Long | Timestamp): Long; - /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ - toInt(): number; - /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ - toNumber(): number; - /** Converts the Long to a BigInt (arbitrary precision). */ - toBigInt(): bigint; - /** - * Converts this Long to its byte representation. - * @param le - Whether little or big endian, defaults to big endian - * @returns Byte representation - */ - toBytes(le?: boolean): number[]; - /** - * Converts this Long to its little endian byte representation. - * @returns Little endian byte representation - */ - toBytesLE(): number[]; - /** - * Converts this Long to its big endian byte representation. - * @returns Big endian byte representation - */ - toBytesBE(): number[]; - /** - * Converts this Long to signed. - */ - toSigned(): Long; - /** - * Converts the Long to a string written in the specified radix. - * @param radix - Radix (2-36), defaults to 10 - * @throws RangeError If `radix` is out of range - */ - toString(radix?: number): string; - /** Converts this Long to unsigned. */ - toUnsigned(): Long; - /** Returns the bitwise XOR of this Long and the given one. */ - xor(other: Long | number | string): Long; - /** This is an alias of {@link Long.isZero} */ - eqz(): boolean; - /** This is an alias of {@link Long.lessThanOrEqual} */ - le(other: string | number | Long | Timestamp): boolean; - toExtendedJSON(options?: EJSONOptions): number | LongExtended; - static fromExtendedJSON(doc: { - $numberLong: string; - }, options?: EJSONOptions): number | Long; - inspect(): string; -} -/** @public */ -export declare interface LongExtended { - $numberLong: string; -} -/** @public */ -export declare type LongWithoutOverrides = new (low: unknown, high?: number, unsigned?: boolean) => { - [P in Exclude]: Long[P]; -}; -/** @public */ -export declare const LongWithoutOverridesClass: LongWithoutOverrides; -/** @public */ -declare let Map_2: MapConstructor; -export { Map_2 as Map }; -/** - * A class representation of the BSON MaxKey type. - * @public - */ -export declare class MaxKey { - _bsontype: 'MaxKey'; - constructor(); - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface MaxKeyExtended { - $maxKey: 1; -} -/** - * A class representation of the BSON MinKey type. - * @public - */ -export declare class MinKey { - _bsontype: 'MinKey'; - constructor(); - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface MinKeyExtended { - $minKey: 1; -} -/** - * A class representation of the BSON ObjectId type. - * @public - */ -declare class ObjectId { - _bsontype: 'ObjectId'; - /* Excluded from this release type: index */ - static cacheHexString: boolean; - /* Excluded from this release type: [kId] */ - /* Excluded from this release type: __id */ - /** - * Create an ObjectId type - * - * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. - */ - constructor(inputId?: string | Buffer | number | ObjectIdLike | ObjectId); - /* - * The ObjectId bytes - * @readonly - */ - id: Buffer; - /* - * The generation time of this ObjectId instance - * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch - */ - generationTime: number; - /** Returns the ObjectId id as a 24 character hex string representation */ - toHexString(): string; - /* Excluded from this release type: getInc */ - /** - * Generate a 12 byte id buffer used in ObjectId's - * - * @param time - pass in a second based timestamp. - */ - static generate(time?: number): Buffer; - /** - * Converts the id into a 24 character hex string for printing - * - * @param format - The Buffer toString format parameter. - */ - toString(format?: string): string; - /** Converts to its JSON the 24 character hex string representation. */ - toJSON(): string; - /** - * Compares the equality of this ObjectId with `otherID`. - * - * @param otherId - ObjectId instance to compare against. - */ - equals(otherId: string | ObjectId | ObjectIdLike): boolean; - /** Returns the generation date (accurate up to the second) that this ID was generated. */ - getTimestamp(): Date; - /* Excluded from this release type: createPk */ - /** - * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. - * - * @param time - an integer number representing a number of seconds. - */ - static createFromTime(time: number): ObjectId; - /** - * Creates an ObjectId from a hex string representation of an ObjectId. - * - * @param hexString - create a ObjectId from a passed in 24 character hexstring. - */ - static createFromHexString(hexString: string): ObjectId; - /** - * Checks if a value is a valid bson ObjectId - * - * @param id - ObjectId instance to validate. - */ - static isValid(id: number | string | ObjectId | Uint8Array | ObjectIdLike): boolean; - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -export { ObjectId as ObjectID }; -export { ObjectId }; -/** @public */ -export declare interface ObjectIdExtended { - $oid: string; -} -/** @public */ -export declare interface ObjectIdLike { - id: string | Buffer; - __id?: string; - toHexString(): string; -} -/** - * Serialize a Javascript object. - * - * @param object - the Javascript object to serialize. - * @returns Buffer object containing the serialized object. - * @public - */ -export declare function serialize(object: Document, options?: SerializeOptions): Buffer; -/** @public */ -export declare interface SerializeOptions { - /** the serializer will check if keys are valid. */ - checkKeys?: boolean; - /** serialize the javascript functions **(default:false)**. */ - serializeFunctions?: boolean; - /** serialize will not emit undefined fields **(default:true)** */ - ignoreUndefined?: boolean; - /* Excluded from this release type: minInternalBufferSize */ - /** the index in the buffer where we wish to start serializing into */ - index?: number; -} -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, - * useful when pre-allocating the space for serialization. - * - * @param object - the Javascript object to serialize. - * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. - * @returns the index pointing to the last written byte in the buffer. - * @public - */ -export declare function serializeWithBufferAndIndex(object: Document, finalBuffer: Buffer, options?: SerializeOptions): number; -/** - * Sets the size of the internal serialization buffer. - * - * @param size - The desired size for the internal serialization buffer - * @public - */ -export declare function setInternalBufferSize(size: number): void; -/** @public */ -export declare class Timestamp extends LongWithoutOverridesClass { - _bsontype: 'Timestamp'; - static readonly MAX_VALUE: Long; - /** - * @param low - A 64-bit Long representing the Timestamp. - */ - constructor(long: Long); - /** - * @param value - A pair of two values indicating timestamp and increment. - */ - constructor(value: { - t: number; - i: number; - }); - /** - * @param low - the low (signed) 32 bits of the Timestamp. - * @param high - the high (signed) 32 bits of the Timestamp. - * @deprecated Please use `Timestamp({ t: high, i: low })` or `Timestamp(Long(low, high))` instead. - */ - constructor(low: number, high: number); - toJSON(): { - $timestamp: string; - }; - /** Returns a Timestamp represented by the given (32-bit) integer value. */ - static fromInt(value: number): Timestamp; - /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ - static fromNumber(value: number): Timestamp; - /** - * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. - * - * @param lowBits - the low 32-bits. - * @param highBits - the high 32-bits. - */ - static fromBits(lowBits: number, highBits: number): Timestamp; - /** - * Returns a Timestamp from the given string, optionally using the given radix. - * - * @param str - the textual representation of the Timestamp. - * @param optRadix - the radix in which the text is written. - */ - static fromString(str: string, optRadix: number): Timestamp; - /* Excluded from this release type: toExtendedJSON */ - /* Excluded from this release type: fromExtendedJSON */ - inspect(): string; -} -/** @public */ -export declare interface TimestampExtended { - $timestamp: { - t: number; - i: number; - }; -} -/** @public */ -export declare type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; -/** - * A class representation of the BSON UUID type. - * @public - */ -export declare class UUID { - _bsontype: 'UUID'; - static cacheHexString: boolean; - /* Excluded from this release type: [kId] */ - /* Excluded from this release type: __id */ - /** - * Create an UUID type - * - * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. - */ - constructor(input?: string | Buffer | UUID); - /* - * The UUID bytes - * @readonly - */ - id: Buffer; - /** - * Generate a 16 byte uuid v4 buffer used in UUIDs - */ - /** - * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) - * @param includeDashes - should the string exclude dash-separators. - * */ - toHexString(includeDashes?: boolean): string; - /** - * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. - */ - toString(encoding?: string): string; - /** - * Converts the id into its JSON string representation. - * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - */ - toJSON(): string; - /** - * Compares the equality of this UUID with `otherID`. - * - * @param otherId - UUID instance to compare against. - */ - equals(otherId: string | Buffer | UUID): boolean; - /** - * Creates a Binary instance from the current UUID. - */ - toBinary(): Binary; - /** - * Generates a populated buffer containing a v4 uuid - */ - static generate(): Buffer; - /** - * Checks if a value is a valid bson UUID - * @param input - UUID, string or Buffer to validate. - */ - static isValid(input: string | Buffer | UUID): boolean; - /** - * Creates an UUID from a hex string representation of an UUID. - * @param hexString - 32 or 36 character hex string (dashes excluded/included). - */ - static createFromHexString(hexString: string): UUID; - inspect(): string; -} -/** @public */ -export declare type UUIDExtended = { - $uuid: string; -}; -export {}; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.esm.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.esm.js deleted file mode 100644 index ad0555d..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.esm.js +++ /dev/null @@ -1,7513 +0,0 @@ -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -var byteLength_1 = byteLength; -var toByteArray_1 = toByteArray; -var fromByteArray_1 = fromByteArray; -var lookup = []; -var revLookup = []; -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; -} // Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications - - -revLookup['-'.charCodeAt(0)] = 62; -revLookup['_'.charCodeAt(0)] = 63; - -function getLens(b64) { - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4'); - } // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - - - var validLen = b64.indexOf('='); - if (validLen === -1) validLen = len; - var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; -} // base64 is 4/3 + up to two characters of the original data - - -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; // if there are placeholders, only get up to the last complete 4 chars - - var len = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i; - - for (i = 0; i < len; i += 4) { - tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; - arr[curByte++] = tmp >> 16 & 0xFF; - arr[curByte++] = tmp >> 8 & 0xFF; - arr[curByte++] = tmp & 0xFF; - } - - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; - arr[curByte++] = tmp & 0xFF; - } - - 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 & 0xFF; - arr[curByte++] = tmp & 0xFF; - } - - return arr; -} - -function tripletToBase64(num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; -} - -function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); - output.push(tripletToBase64(tmp)); - } - - return output.join(''); -} - -function fromByteArray(uint8) { - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); - } // pad the end with zeros, but make sure to not forget the extra bytes - - - if (extraBytes === 1) { - tmp = uint8[len - 1]; - parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); - } - - return parts.join(''); -} - -var base64Js = { - byteLength: byteLength_1, - toByteArray: toByteArray_1, - fromByteArray: fromByteArray_1 -}; - -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -var read = function read(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 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); -}; - -var write = function write(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 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 & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = e << mLen | m; - eLen += mLen; - - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; -}; - -var ieee754 = { - read: read, - write: write -}; - -var buffer$1 = createCommonjsModule(function (module, exports) { - - var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation - Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation - : null; - exports.Buffer = Buffer; - exports.SlowBuffer = SlowBuffer; - exports.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 0x7fffffff; - exports.kMaxLength = K_MAX_LENGTH; - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ - - 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() { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1); - var proto = { - foo: function foo() { - return 42; - } - }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e) { - return false; - } - } - - Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function get() { - if (!Buffer.isBuffer(this)) return undefined; - return this.buffer; - } - }); - Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function get() { - 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"'); - } // Return an augmented `Uint8Array` instance - - - var buf = new Uint8Array(length); - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; - } - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - - function Buffer(arg, encodingOrOffset, length) { - // Common case. - 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); - } - - Buffer.poolSize = 8192; // not used by this implementation - - function from(value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset); - } - - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - - if (value == null) { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); - } - - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - - if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - 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 ' + babelHelpers["typeof"](value)); - } - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - - - Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length); - }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: - // https://github.com/feross/buffer/pull/148 - - - Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer, 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) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpreted as a start offset. - return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - - return createBuffer(size); - } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - - - Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding); - }; - - function allocUnsafe(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - - - Buffer.allocUnsafe = function (size) { - return allocUnsafe(size); - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - - - 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) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - 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 < length; i += 1) { - buf[i] = array[i] & 255; - } - - return buf; - } - - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - - return fromArrayLike(arrayView); - } - - function fromArrayBuffer(array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - - var buf; - - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array); - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length); - } // Return an augmented `Uint8Array` instance - - - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; - } - - function fromObject(obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); - - if (buf.length === 0) { - return buf; - } - - obj.copy(buf, 0, 0, len); - return buf; - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0); - } - - return fromArrayLike(obj); - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - - function checked(length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= 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) { - // eslint-disable-line eqeqeq - length = 0; - } - - return Buffer.alloc(+length); - } - - Buffer.isBuffer = function isBuffer(b) { - return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false - }; - - 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); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - - Buffer.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true; - - default: - return false; - } - }; - - Buffer.concat = function concat(list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - - if (list.length === 0) { - return Buffer.alloc(0); - } - - var i; - - if (length === undefined) { - length = 0; - - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer.from(buf).copy(buffer, pos); - } else { - Uint8Array.prototype.set.call(buffer, buf, pos); - } - } else if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - - pos += buf.length; - } - - return buffer; - }; - - function byteLength(string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length; - } - - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength; - } - - if (typeof string !== 'string') { - throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string)); - } - - var len = string.length; - var mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion - - 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; // assume utf8 - } - - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - - Buffer.byteLength = byteLength; - - function slowToString(encoding, start, end) { - var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - - if (start === undefined || start < 0) { - start = 0; - } // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - - - if (start > this.length) { - return ''; - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return ''; - } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. - - - 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; - } - } - } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) - // to detect a Buffer instance. It's not possible to use `instanceof Buffer` - // reliably in a browserify context because there could be multiple different - // copies of the 'buffer' package in use. This method works even for Buffer - // instances that were created from another copy of the `buffer` package. - // See: https://github.com/feross/buffer/issues/154 - - - 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; i < len; i += 2) { - swap(this, i, i + 1); - } - - return this; - }; - - Buffer.prototype.swap32 = function swap32() { - var len = this.length; - - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits'); - } - - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - - return this; - }; - - Buffer.prototype.swap64 = function swap64() { - var len = this.length; - - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits'); - } - - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - - return this; - }; - - Buffer.prototype.toString = function toString() { - var length = this.length; - if (length === 0) return ''; - if (arguments.length === 0) return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); - }; - - Buffer.prototype.toLocaleString = Buffer.prototype.toString; - - Buffer.prototype.equals = function equals(b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); - if (this === b) return true; - return Buffer.compare(this, b) === 0; - }; - - Buffer.prototype.inspect = function inspect() { - var str = ''; - var max = exports.INSPECT_MAX_BYTES; - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); - if (this.length > max) str += ' ... '; - return ''; - }; - - if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; - } - - 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 ' + babelHelpers["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; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - - - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1; // Normalize byteOffset - - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - - byteOffset = +byteOffset; // Coerce to Number. - - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : buffer.length - 1; - } // Normalize byteOffset: negative offsets start from the end of the buffer - - - 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; - } // Normalize val - - - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } // Finally, search either indexOf (if dir is true) or lastIndexOf - - - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1; - } - - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-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; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - - for (i = byteOffset; i >= 0; i--) { - var found = true; - - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - - if (found) return i; - } - } - - return -1; - } - - Buffer.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - - Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - - Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - - if (!length) { - length = remaining; - } else { - length = Number(length); - - if (length > remaining) { - length = remaining; - } - } - - var strLen = string.length; - - if (length > strLen / 2) { - length = strLen / 2; - } - - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i; - buf[offset + i] = parsed; - } - - return i; - } - - function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); - } - - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length); - } - - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); - } - - function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); - } - - Buffer.prototype.write = function write(string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 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': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length); - - case 'base64': - // Warning: maxLength not taken into account in base64Write - 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 base64Js.fromByteArray(buf); - } else { - return base64Js.fromByteArray(buf.slice(start, end)); - } - } - - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i = start; - - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - - break; - - case 2: - secondByte = buf[i + 1]; - - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; - - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - - break; - - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; - - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - - break; - - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; - - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray(res); - } // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - - - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); // avoid extra slice() - } // Decode in chunks to avoid "call stack size exceeded". - - - var res = ''; - var i = 0; - - while (i < len) { - res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); - } - - return res; - } - - function asciiSlice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - - return ret; - } - - function latin1Slice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - - return ret; - } - - function hexSlice(buf, start, end) { - var len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - var out = ''; - - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - - return out; - } - - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - - for (var i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - - return res; - } - - Buffer.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance - - Object.setPrototypeOf(newBuf, Buffer.prototype); - return newBuf; - }; - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - - - function checkOffset(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); - } - - Buffer.prototype.readUintLE = 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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val; - }; - - Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val; - }; - - Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset]; - }; - - Buffer.prototype.readUint16LE = 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 = 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 = 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] * 0x1000000; - }; - - Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] * 0x1000000 + (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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - mul *= 0x80; - if (val >= 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 *= 0x100)) { - val += this[offset + --i] * mul; - } - - mul *= 0x80; - 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] & 0x80)) return this[offset]; - return (0xff - 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 & 0x8000 ? val | 0xFFFF0000 : 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 & 0x8000 ? val | 0xFFFF0000 : 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 || value < min) throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) throw new RangeError('Index out of range'); - } - - Buffer.prototype.writeUintLE = 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 & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(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 i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - - Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 0xff; - return offset + 4; - }; - - Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - 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 & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - 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 & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (value < 0) value = 0xff + value + 1; - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - this[offset] = value & 0xff; - 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, 0x7fff, -0x8000); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - this[offset] = value & 0xff; - 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, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - 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); - } - - 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); - } - - 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); - }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - - - 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 < start) end = start; // Copy 0 bytes; we're done - - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions - - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds'); - } - - if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); - if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? - - if (end > this.length) end = this.length; - - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); - } - - return len; - }; // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - - - Buffer.prototype.fill = function fill(val, start, end, encoding) { - // Handle string cases: - 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') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code; - } - } - } else if (typeof val === 'number') { - val = val & 255; - } else if (typeof val === 'boolean') { - val = Number(val); - } // Invalid ranges are not set to a default, so can range check early. - - - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index'); - } - - if (end <= start) { - return this; - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - if (!val) val = 0; - var i; - - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); - var len = bytes.length; - - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this; - }; // HELPER FUNCTIONS - // ================ - - - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - - function base64clean(str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not - - str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' - - if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - - while (str.length % 4 !== 0) { - str = str + '='; - } - - return str; - } - - function utf8ToBytes(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); // is surrogate component - - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } // valid lead - - - leadSurrogate = codePoint; - continue; - } // 2 leads in a row - - - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue; - } // valid surrogate pair - - - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; // encode utf8 - - if (codePoint < 0x80) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break; - bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break; - bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break; - bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else { - throw new Error('Invalid code point'); - } - } - - return bytes; - } - - function asciiToBytes(str) { - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - - return byteArray; - } - - function utf16leToBytes(str, units) { - var c, hi, lo; - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray; - } - - function base64ToBytes(str) { - return base64Js.toByteArray(base64clean(str)); - } - - function blitBuffer(src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) break; - dst[i + offset] = src[i]; - } - - return i; - } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass - // the `instanceof` check but they should be treated as of that type. - // See: https://github.com/feross/buffer/issues/166 - - - 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) { - // For IE11 support - return obj !== obj; // eslint-disable-line no-self-compare - } // Create lookup table for `toString('hex')` - // See: https://github.com/feross/buffer/issues/219 - - - var hexSliceLookupTable = function () { - var alphabet = '0123456789abcdef'; - var table = new Array(256); - - for (var i = 0; i < 16; ++i) { - var i16 = i * 16; - - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; - } - } - - return table; - }(); -}); -var buffer_1 = buffer$1.Buffer; -buffer$1.SlowBuffer; -buffer$1.INSPECT_MAX_BYTES; -buffer$1.kMaxLength; - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -/* global Reflect, Promise */ -var _extendStatics = function extendStatics(d, b) { - _extendStatics = Object.setPrototypeOf || { - __proto__: [] - } instanceof Array && function (d, b) { - d.__proto__ = b; - } || function (d, b) { - for (var p in b) { - if (b.hasOwnProperty(p)) d[p] = b[p]; - } - }; - - return _extendStatics(d, b); -}; - -function __extends(d, b) { - _extendStatics(d, b); - - function __() { - this.constructor = d; - } - - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var _assign = function __assign() { - _assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - - for (var p in s) { - if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - } - - return t; - }; - - return _assign.apply(this, arguments); -}; - -/** @public */ -var BSONError = /** @class */ (function (_super) { - __extends(BSONError, _super); - function BSONError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONError.prototype); - return _this; - } - Object.defineProperty(BSONError.prototype, "name", { - get: function () { - return 'BSONError'; - }, - enumerable: false, - configurable: true - }); - return BSONError; -}(Error)); -/** @public */ -var BSONTypeError = /** @class */ (function (_super) { - __extends(BSONTypeError, _super); - function BSONTypeError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONTypeError.prototype); - return _this; - } - Object.defineProperty(BSONTypeError.prototype, "name", { - get: function () { - return 'BSONTypeError'; - }, - enumerable: false, - configurable: true - }); - return BSONTypeError; -}(TypeError)); - -function checkForMath(potentialGlobal) { - // eslint-disable-next-line eqeqeq - return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; -} -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -function getGlobal() { - // eslint-disable-next-line no-undef - return (checkForMath(typeof globalThis === 'object' && globalThis) || - checkForMath(typeof window === 'object' && window) || - checkForMath(typeof self === 'object' && self) || - checkForMath(typeof global === 'object' && global) || - Function('return this')()); -} - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param fn - The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace('function(', 'function ('); -} -function isReactNative() { - var g = getGlobal(); - return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; -} -var insecureRandomBytes = function insecureRandomBytes(size) { - var insecureWarning = isReactNative() - ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' - : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; - console.warn(insecureWarning); - var result = buffer_1.alloc(size); - for (var i = 0; i < size; ++i) - result[i] = Math.floor(Math.random() * 256); - return result; -}; -var detectRandomBytes = function () { - if (typeof window !== 'undefined') { - // browser crypto implementation(s) - var target_1 = window.crypto || window.msCrypto; // allow for IE11 - if (target_1 && target_1.getRandomValues) { - return function (size) { return target_1.getRandomValues(buffer_1.alloc(size)); }; - } - } - if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { - // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global - return function (size) { return global.crypto.getRandomValues(buffer_1.alloc(size)); }; - } - var requiredRandomBytes; - try { - // eslint-disable-next-line @typescript-eslint/no-var-requires - requiredRandomBytes = require('crypto').randomBytes; - } - catch (e) { - // keep the fallback - } - // NOTE: in transpiled cases the above require might return null/undefined - return requiredRandomBytes || insecureRandomBytes; -}; -var randomBytes = detectRandomBytes(); -function isAnyArrayBuffer(value) { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); -} -function isUint8Array(value) { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; -} -function isBigInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigInt64Array]'; -} -function isBigUInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigUint64Array]'; -} -function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} -function isMap(d) { - return Object.prototype.toString.call(d) === '[object Map]'; -} -// To ensure that 0.4 of node works correctly -function isDate(d) { - return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; -} -/** - * @internal - * this is to solve the `'someKey' in x` problem where x is unknown. - * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 - */ -function isObjectLike(candidate) { - return typeof candidate === 'object' && candidate !== null; -} -function deprecate(fn, message) { - var warned = false; - function deprecated() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!warned) { - console.warn(message); - warned = true; - } - return fn.apply(this, args); - } - return deprecated; -} - -/** - * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. - * - * @param potentialBuffer - The potential buffer - * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that - * wraps a passed in Uint8Array - * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in - */ -function ensureBuffer(potentialBuffer) { - if (ArrayBuffer.isView(potentialBuffer)) { - return buffer_1.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - if (isAnyArrayBuffer(potentialBuffer)) { - return buffer_1.from(potentialBuffer); - } - throw new BSONTypeError('Must use either Buffer or TypedArray'); -} - -// Validation regex for v4 uuid (validates with or without dashes) -var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; -var uuidValidateString = function (str) { - return typeof str === 'string' && VALIDATION_REGEX.test(str); -}; -var uuidHexStringToBuffer = function (hexString) { - if (!uuidValidateString(hexString)) { - throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); - } - var sanitizedHexString = hexString.replace(/-/g, ''); - return buffer_1.from(sanitizedHexString, 'hex'); -}; -var bufferToUuidHexString = function (buffer, includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - return includeDashes - ? buffer.toString('hex', 0, 4) + - '-' + - buffer.toString('hex', 4, 6) + - '-' + - buffer.toString('hex', 6, 8) + - '-' + - buffer.toString('hex', 8, 10) + - '-' + - buffer.toString('hex', 10, 16) - : buffer.toString('hex'); -}; - -var BYTE_LENGTH = 16; -var kId$1 = Symbol('id'); -/** - * A class representation of the BSON UUID type. - * @public - */ -var UUID = /** @class */ (function () { - /** - * Create an UUID type - * - * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. - */ - function UUID(input) { - if (typeof input === 'undefined') { - // The most common use case (blank id, new UUID() instance) - this.id = UUID.generate(); - } - else if (input instanceof UUID) { - this[kId$1] = buffer_1.from(input.id); - this.__id = input.__id; - } - else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { - this.id = ensureBuffer(input); - } - else if (typeof input === 'string') { - this.id = uuidHexStringToBuffer(input); - } - else { - throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); - } - } - Object.defineProperty(UUID.prototype, "id", { - /** - * The UUID bytes - * @readonly - */ - get: function () { - return this[kId$1]; - }, - set: function (value) { - this[kId$1] = value; - if (UUID.cacheHexString) { - this.__id = bufferToUuidHexString(value); - } - }, - enumerable: false, - configurable: true - }); - /** - * Generate a 16 byte uuid v4 buffer used in UUIDs - */ - /** - * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) - * @param includeDashes - should the string exclude dash-separators. - * */ - UUID.prototype.toHexString = function (includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - var uuidHexString = bufferToUuidHexString(this.id, includeDashes); - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - return uuidHexString; - }; - /** - * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. - */ - UUID.prototype.toString = function (encoding) { - return encoding ? this.id.toString(encoding) : this.toHexString(); - }; - /** - * Converts the id into its JSON string representation. - * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - */ - UUID.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this UUID with `otherID`. - * - * @param otherId - UUID instance to compare against. - */ - UUID.prototype.equals = function (otherId) { - if (!otherId) { - return false; - } - if (otherId instanceof UUID) { - return otherId.id.equals(this.id); - } - try { - return new UUID(otherId).id.equals(this.id); - } - catch (_a) { - return false; - } - }; - /** - * Creates a Binary instance from the current UUID. - */ - UUID.prototype.toBinary = function () { - return new Binary(this.id, Binary.SUBTYPE_UUID); - }; - /** - * Generates a populated buffer containing a v4 uuid - */ - UUID.generate = function () { - var bytes = randomBytes(BYTE_LENGTH); - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - return buffer_1.from(bytes); - }; - /** - * Checks if a value is a valid bson UUID - * @param input - UUID, string or Buffer to validate. - */ - UUID.isValid = function (input) { - if (!input) { - return false; - } - if (input instanceof UUID) { - return true; - } - if (typeof input === 'string') { - return uuidValidateString(input); - } - if (isUint8Array(input)) { - // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) - if (input.length !== BYTE_LENGTH) { - return false; - } - try { - // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx - // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx - return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; - } - catch (_a) { - return false; - } - } - return false; - }; - /** - * Creates an UUID from a hex string representation of an UUID. - * @param hexString - 32 or 36 character hex string (dashes excluded/included). - */ - UUID.createFromHexString = function (hexString) { - var buffer = uuidHexStringToBuffer(hexString); - return new UUID(buffer); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 36 character hex string representation. - * @internal - */ - UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - UUID.prototype.inspect = function () { - return "new UUID(\"" + this.toHexString() + "\")"; - }; - return UUID; -}()); -Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); - -/** - * A class representation of the BSON Binary type. - * @public - */ -var Binary = /** @class */ (function () { - /** - * @param buffer - a buffer object containing the binary data. - * @param subType - the option binary type. - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) - return new Binary(buffer, subType); - if (!(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer)) { - throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); - } - this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer == null) { - // create an empty binary buffer - this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE); - this.position = 0; - } - else { - if (typeof buffer === 'string') { - // string - this.buffer = buffer_1.from(buffer, 'binary'); - } - else if (Array.isArray(buffer)) { - // number[] - this.buffer = buffer_1.from(buffer); - } - else { - // Buffer | TypedArray | ArrayBuffer - this.buffer = ensureBuffer(buffer); - } - this.position = this.buffer.byteLength; - } - } - /** - * Updates this binary with byte_value. - * - * @param byteValue - a single byte we wish to write. - */ - Binary.prototype.put = function (byteValue) { - // If it's a string and a has more than one character throw an error - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new BSONTypeError('only accepts single character String'); - } - else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new BSONTypeError('only accepts single character Uint8Array or Array'); - // Decode the byte value once - var decodedByte; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } - else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } - else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); - } - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decodedByte; - } - else { - var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decodedByte; - } - }; - /** - * Writes a buffer or string to the binary. - * - * @param sequence - a string or buffer to be written to the Binary BSON object. - * @param offset - specify the binary of where to write the content. - */ - Binary.prototype.write = function (sequence, offset) { - offset = typeof offset === 'number' ? offset : this.position; - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + sequence.length) { - var buffer = buffer_1.alloc(this.buffer.length + sequence.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - // Assign the new buffer - this.buffer = buffer; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ensureBuffer(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } - else if (typeof sequence === 'string') { - this.buffer.write(sequence, offset, sequence.length, 'binary'); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - }; - /** - * Reads **length** bytes starting at **position**. - * - * @param position - read from the given position in the Binary. - * @param length - the number of bytes to read. - */ - Binary.prototype.read = function (position, length) { - length = length && length > 0 ? length : this.position; - // Let's return the data based on the type we have - return this.buffer.slice(position, position + length); - }; - /** - * Returns the value of this binary as a string. - * @param asRaw - Will skip converting to a string - * @remarks - * This is handy when calling this function conditionally for some key value pairs and not others - */ - Binary.prototype.value = function (asRaw) { - asRaw = !!asRaw; - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - // If it's a node.js buffer object - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return this.buffer.toString('binary', 0, this.position); - }; - /** the length of the binary sequence */ - Binary.prototype.length = function () { - return this.position; - }; - Binary.prototype.toJSON = function () { - return this.buffer.toString('base64'); - }; - Binary.prototype.toString = function (format) { - return this.buffer.toString(format); - }; - /** @internal */ - Binary.prototype.toExtendedJSON = function (options) { - options = options || {}; - var base64String = this.buffer.toString('base64'); - var subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - }; - Binary.prototype.toUUID = function () { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID(this.buffer.slice(0, this.position)); - } - throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); - }; - /** @internal */ - Binary.fromExtendedJSON = function (doc, options) { - options = options || {}; - var data; - var type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = buffer_1.from(doc.$binary, 'base64'); - } - else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = buffer_1.from(doc.$binary.base64, 'base64'); - } - } - } - else if ('$uuid' in doc) { - type = 4; - data = uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); - } - return new Binary(data, type); - }; - /** @internal */ - Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Binary.prototype.inspect = function () { - var asBuffer = this.value(true); - return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; - }; - /** - * Binary default subtype - * @internal - */ - Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** Initial buffer default size */ - Binary.BUFFER_SIZE = 256; - /** Default BSON type */ - Binary.SUBTYPE_DEFAULT = 0; - /** Function BSON type */ - Binary.SUBTYPE_FUNCTION = 1; - /** Byte Array BSON type */ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ - Binary.SUBTYPE_UUID_OLD = 3; - /** UUID BSON type */ - Binary.SUBTYPE_UUID = 4; - /** MD5 BSON type */ - Binary.SUBTYPE_MD5 = 5; - /** Encrypted BSON type */ - Binary.SUBTYPE_ENCRYPTED = 6; - /** Column BSON type */ - Binary.SUBTYPE_COLUMN = 7; - /** User BSON type */ - Binary.SUBTYPE_USER_DEFINED = 128; - return Binary; -}()); -Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); - -/** - * A class representation of the BSON Code type. - * @public - */ -var Code = /** @class */ (function () { - /** - * @param code - a string or function. - * @param scope - an optional scope for the function. - */ - function Code(code, scope) { - if (!(this instanceof Code)) - return new Code(code, scope); - this.code = code; - this.scope = scope; - } - Code.prototype.toJSON = function () { - return { code: this.code, scope: this.scope }; - }; - /** @internal */ - Code.prototype.toExtendedJSON = function () { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - }; - /** @internal */ - Code.fromExtendedJSON = function (doc) { - return new Code(doc.$code, doc.$scope); - }; - /** @internal */ - Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Code.prototype.inspect = function () { - var codeJson = this.toJSON(); - return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; - }; - return Code; -}()); -Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); - -/** @internal */ -function isDBRefLike(value) { - return (isObjectLike(value) && - value.$id != null && - typeof value.$ref === 'string' && - (value.$db == null || typeof value.$db === 'string')); -} -/** - * A class representation of the BSON DBRef type. - * @public - */ -var DBRef = /** @class */ (function () { - /** - * @param collection - the collection name. - * @param oid - the reference ObjectId. - * @param db - optional db name, if omitted the reference is local to the current db. - */ - function DBRef(collection, oid, db, fields) { - if (!(this instanceof DBRef)) - return new DBRef(collection, oid, db, fields); - // check if namespace has been provided - var parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - Object.defineProperty(DBRef.prototype, "namespace", { - // Property provided for compatibility with the 1.x parser - // the 1.x parser used a "namespace" property, while 4.x uses "collection" - /** @internal */ - get: function () { - return this.collection; - }, - set: function (value) { - this.collection = value; - }, - enumerable: false, - configurable: true - }); - DBRef.prototype.toJSON = function () { - var o = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o.$db = this.db; - return o; - }; - /** @internal */ - DBRef.prototype.toExtendedJSON = function (options) { - options = options || {}; - var o = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o; - } - if (this.db) - o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - }; - /** @internal */ - DBRef.fromExtendedJSON = function (doc) { - var copy = Object.assign({}, doc); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - }; - /** @internal */ - DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - DBRef.prototype.inspect = function () { - // NOTE: if OID is an ObjectId class it will just print the oid string. - var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; - }; - return DBRef; -}()); -Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); - -/** - * wasm optimizations, to do native i64 multiplication and divide - */ -var wasm = undefined; -try { - wasm = new WebAssembly.Instance(new WebAssembly.Module( - // prettier-ignore - new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; -} -catch (_a) { - // no wasm support -} -var TWO_PWR_16_DBL = 1 << 16; -var TWO_PWR_24_DBL = 1 << 24; -var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; -var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; -var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; -/** A cache of the Long representations of small integer values. */ -var INT_CACHE = {}; -/** A cache of the Long representations of small unsigned integer values. */ -var UINT_CACHE = {}; -/** - * A class representing a 64-bit integer - * @public - * @remarks - * The internal representation of a long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16 bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. - */ -var Long = /** @class */ (function () { - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * - * Acceptable signatures are: - * - Long(low, high, unsigned?) - * - Long(bigint, unsigned?) - * - Long(string, unsigned?) - * - * @param low - The low (signed) 32 bits of the long - * @param high - The high (signed) 32 bits of the long - * @param unsigned - Whether unsigned or not, defaults to signed - */ - function Long(low, high, unsigned) { - if (low === void 0) { low = 0; } - if (!(this instanceof Long)) - return new Long(low, high, unsigned); - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } - else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } - else { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - Object.defineProperty(this, '__isLong__', { - value: true, - configurable: false, - writable: false, - enumerable: false - }); - } - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. - * Each is assumed to use 32 bits. - * @param lowBits - The low 32 bits - * @param highBits - The high 32 bits - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBits = function (lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - }; - /** - * Returns a Long representing the given 32 bit integer value. - * @param value - The 32 bit integer in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromInt = function (value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } - else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromNumber = function (value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } - else { - if (value <= -TWO_PWR_63_DBL) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; - } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBigInt = function (value, unsigned) { - return Long.fromString(value.toString(), unsigned); - }; - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param str - The textual representation of the Long - * @param unsigned - Whether unsigned or not, defaults to signed - * @param radix - The radix in which the text is written (2-36), defaults to 10 - * @returns The corresponding Long value - */ - Long.fromString = function (str, unsigned, radix) { - if (str.length === 0) - throw Error('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - (radix = unsigned), (unsigned = false); - } - else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - var p; - if ((p = str.indexOf('-')) > 0) - throw Error('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } - else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - }; - /** - * Creates a Long from its byte representation. - * @param bytes - Byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @param le - Whether little or big endian, defaults to big endian - * @returns The corresponding Long value - */ - Long.fromBytes = function (bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - }; - /** - * Creates a Long from its little endian byte representation. - * @param bytes - Little endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesLE = function (bytes, unsigned) { - return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); - }; - /** - * Creates a Long from its big endian byte representation. - * @param bytes - Big endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesBE = function (bytes, unsigned) { - return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); - }; - /** - * Tests if the specified object is a Long. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Long.isLong = function (value) { - return isObjectLike(value) && value['__isLong__'] === true; - }; - /** - * Converts the specified value to a Long. - * @param unsigned - Whether unsigned or not, defaults to signed - */ - Long.fromValue = function (val, unsigned) { - if (typeof val === 'number') - return Long.fromNumber(val, unsigned); - if (typeof val === 'string') - return Long.fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); - }; - /** Returns the sum of this and the specified Long. */ - Long.prototype.add = function (addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** - * Returns the sum of this and the specified Long. - * @returns Sum - */ - Long.prototype.and = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - /** - * Compares this Long's value with the specified's. - * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater - */ - Long.prototype.compare = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - // At this point the sign bits are the same - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; - /** This is an alias of {@link Long.compare} */ - Long.prototype.comp = function (other) { - return this.compare(other); - }; - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. - * @returns Quotient - */ - Long.prototype.divide = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw Error('division by zero'); - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if (!this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } - else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } - else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } - else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } - else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return Long.UONE; - res = Long.UZERO; - } - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - /**This is an alias of {@link Long.divide} */ - Long.prototype.div = function (divisor) { - return this.divide(divisor); - }; - /** - * Tests if this Long's value equals the specified's. - * @param other - Other value - */ - Long.prototype.equals = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - /** This is an alias of {@link Long.equals} */ - Long.prototype.eq = function (other) { - return this.equals(other); - }; - /** Gets the high 32 bits as a signed integer. */ - Long.prototype.getHighBits = function () { - return this.high; - }; - /** Gets the high 32 bits as an unsigned integer. */ - Long.prototype.getHighBitsUnsigned = function () { - return this.high >>> 0; - }; - /** Gets the low 32 bits as a signed integer. */ - Long.prototype.getLowBits = function () { - return this.low; - }; - /** Gets the low 32 bits as an unsigned integer. */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low >>> 0; - }; - /** Gets the number of bits needed to represent the absolute value of this Long. */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - // Unsigned Longs are never negative - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - var val = this.high !== 0 ? this.high : this.low; - var bit; - for (bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - }; - /** Tests if this Long's value is greater than the specified's. */ - Long.prototype.greaterThan = function (other) { - return this.comp(other) > 0; - }; - /** This is an alias of {@link Long.greaterThan} */ - Long.prototype.gt = function (other) { - return this.greaterThan(other); - }; - /** Tests if this Long's value is greater than or equal the specified's. */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.comp(other) >= 0; - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.gte = function (other) { - return this.greaterThanOrEqual(other); - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.ge = function (other) { - return this.greaterThanOrEqual(other); - }; - /** Tests if this Long's value is even. */ - Long.prototype.isEven = function () { - return (this.low & 1) === 0; - }; - /** Tests if this Long's value is negative. */ - Long.prototype.isNegative = function () { - return !this.unsigned && this.high < 0; - }; - /** Tests if this Long's value is odd. */ - Long.prototype.isOdd = function () { - return (this.low & 1) === 1; - }; - /** Tests if this Long's value is positive. */ - Long.prototype.isPositive = function () { - return this.unsigned || this.high >= 0; - }; - /** Tests if this Long's value equals zero. */ - Long.prototype.isZero = function () { - return this.high === 0 && this.low === 0; - }; - /** Tests if this Long's value is less than the specified's. */ - Long.prototype.lessThan = function (other) { - return this.comp(other) < 0; - }; - /** This is an alias of {@link Long#lessThan}. */ - Long.prototype.lt = function (other) { - return this.lessThan(other); - }; - /** Tests if this Long's value is less than or equal the specified's. */ - Long.prototype.lessThanOrEqual = function (other) { - return this.comp(other) <= 0; - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.lte = function (other) { - return this.lessThanOrEqual(other); - }; - /** Returns this Long modulo the specified. */ - Long.prototype.modulo = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.mod = function (divisor) { - return this.modulo(divisor); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.rem = function (divisor) { - return this.modulo(divisor); - }; - /** - * Returns the product of this and the specified Long. - * @param multiplier - Multiplier - * @returns Product - */ - Long.prototype.multiply = function (multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - // use wasm support if present - if (wasm) { - var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } - else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - // If both longs are small, use float multiplication - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** This is an alias of {@link Long.multiply} */ - Long.prototype.mul = function (multiplier) { - return this.multiply(multiplier); - }; - /** Returns the Negation of this Long's value. */ - Long.prototype.negate = function () { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); - }; - /** This is an alias of {@link Long.negate} */ - Long.prototype.neg = function () { - return this.negate(); - }; - /** Returns the bitwise NOT of this Long. */ - Long.prototype.not = function () { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - }; - /** Tests if this Long's value differs from the specified's. */ - Long.prototype.notEquals = function (other) { - return !this.equals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.neq = function (other) { - return this.notEquals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.ne = function (other) { - return this.notEquals(other); - }; - /** - * Returns the bitwise OR of this Long and the specified. - */ - Long.prototype.or = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftLeft = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - }; - /** This is an alias of {@link Long.shiftLeft} */ - Long.prototype.shl = function (numBits) { - return this.shiftLeft(numBits); - }; - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRight = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - }; - /** This is an alias of {@link Long.shiftRight} */ - Long.prototype.shr = function (numBits) { - return this.shiftRight(numBits); - }; - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } - else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shr_u = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shru = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** - * Returns the difference of this and the specified Long. - * @param subtrahend - Subtrahend - * @returns Difference - */ - Long.prototype.subtract = function (subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - /** This is an alias of {@link Long.subtract} */ - Long.prototype.sub = function (subtrahend) { - return this.subtract(subtrahend); - }; - /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ - Long.prototype.toInt = function () { - return this.unsigned ? this.low >>> 0 : this.low; - }; - /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ - Long.prototype.toNumber = function () { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - /** Converts the Long to a BigInt (arbitrary precision). */ - Long.prototype.toBigInt = function () { - return BigInt(this.toString()); - }; - /** - * Converts this Long to its byte representation. - * @param le - Whether little or big endian, defaults to big endian - * @returns Byte representation - */ - Long.prototype.toBytes = function (le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - /** - * Converts this Long to its little endian byte representation. - * @returns Little endian byte representation - */ - Long.prototype.toBytesLE = function () { - var hi = this.high, lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - }; - /** - * Converts this Long to its big endian byte representation. - * @returns Big endian byte representation - */ - Long.prototype.toBytesBE = function () { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - }; - /** - * Converts this Long to signed. - */ - Long.prototype.toSigned = function () { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); - }; - /** - * Converts the Long to a string written in the specified radix. - * @param radix - Radix (2-36), defaults to 10 - * @throws RangeError If `radix` is out of range - */ - Long.prototype.toString = function (radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } - else - return '-' + this.neg().toString(radix); - } - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - // eslint-disable-next-line @typescript-eslint/no-this-alias - var rem = this; - var result = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - var digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - }; - /** Converts this Long to unsigned. */ - Long.prototype.toUnsigned = function () { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - }; - /** Returns the bitwise XOR of this Long and the given one. */ - Long.prototype.xor = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - /** This is an alias of {@link Long.isZero} */ - Long.prototype.eqz = function () { - return this.isZero(); - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.le = function (other) { - return this.lessThanOrEqual(other); - }; - /* - **************************************************************** - * BSON SPECIFIC ADDITIONS * - **************************************************************** - */ - Long.prototype.toExtendedJSON = function (options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; - }; - Long.fromExtendedJSON = function (doc, options) { - var result = Long.fromString(doc.$numberLong); - return options && options.relaxed ? result.toNumber() : result; - }; - /** @internal */ - Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Long.prototype.inspect = function () { - return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; - }; - Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); - /** Maximum unsigned value. */ - Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); - /** Signed zero */ - Long.ZERO = Long.fromInt(0); - /** Unsigned zero. */ - Long.UZERO = Long.fromInt(0, true); - /** Signed one. */ - Long.ONE = Long.fromInt(1); - /** Unsigned one. */ - Long.UONE = Long.fromInt(1, true); - /** Signed negative one. */ - Long.NEG_ONE = Long.fromInt(-1); - /** Maximum signed value. */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - /** Minimum signed value. */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - return Long; -}()); -Object.defineProperty(Long.prototype, '__isLong__', { value: true }); -Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); - -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Detect if the value is a digit -function isDigit(value) { - return !isNaN(parseInt(value, 10)); -} -// Divide two uint128 values -function divideu128(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (var i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - return { quotient: value, rem: _rem }; -} -// Multiply two Long values and return the 128 bit value -function multiply64x2(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - // Return the 128 bit result - return { high: productHigh, low: productLow }; -} -function lessThan(left, right) { - // Make values unsigned - var uhleft = left.high >>> 0; - var uhright = right.high >>> 0; - // Compare high bits first - if (uhleft < uhright) { - return true; - } - else if (uhleft === uhright) { - var ulleft = left.low >>> 0; - var ulright = right.low >>> 0; - if (ulleft < ulright) - return true; - } - return false; -} -function invalidErr(string, message) { - throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); -} -/** - * A class representation of the BSON Decimal128 type. - * @public - */ -var Decimal128 = /** @class */ (function () { - /** - * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, - * or a string representation as returned by .toString() - */ - function Decimal128(bytes) { - if (!(this instanceof Decimal128)) - return new Decimal128(bytes); - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } - else { - this.bytes = bytes; - } - } - /** - * Create a Decimal128 instance from a string representation - * - * @param representation - a numeric string representation. - */ - Decimal128.fromString = function (representation) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = new Long(0, 0); - // The low 17 digits of the significand - var significandLow = new Long(0, 0); - // The biased exponent - var biasedExponent = 0; - // Read index - var index = 0; - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (representation.length >= 7000) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - // Results - var stringMatch = representation.match(PARSE_STRING_REGEXP); - var infMatch = representation.match(PARSE_INF_REGEXP); - var nanMatch = representation.match(PARSE_NAN_REGEXP); - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - if (stringMatch) { - // full_match = stringMatch[0] - // sign = stringMatch[1] - var unsignedNumber = stringMatch[2]; - // stringMatch[3] is undefined if a whole number (ex "1", 12") - // but defined if a number w/ decimal in it (ex "1.0, 12.2") - var e = stringMatch[4]; - var expSign = stringMatch[5]; - var expNumber = stringMatch[6]; - // they provided e, but didn't give an exponent number. for ex "1e" - if (e && expNumber === undefined) - invalidErr(representation, 'missing exponent power'); - // they provided e, but didn't give a number before it. for ex "e1" - if (e && unsignedNumber === undefined) - invalidErr(representation, 'missing exponent base'); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - // Get the negative or positive sign - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - // Check if user passed Infinity or NaN - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - else if (representation[index] === 'N') { - return new Decimal128(buffer_1.from(NAN_BUFFER)); - } - } - // Read all the digits - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) - invalidErr(representation, 'contains multiple periods'); - sawRadix = true; - index = index + 1; - continue; - } - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - // Only store 34 digits - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - if (sawRadix && !nDigitsRead) - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - // Read exponent if exists - if (representation[index] === 'e' || representation[index] === 'E') { - // Read exponent digits - var match = representation.substr(++index).match(EXPONENT_REGEX); - // No digits read - if (!match || !match[2]) - return new Decimal128(buffer_1.from(NAN_BUFFER)); - // Get exponent - exponent = parseInt(match[0], 10); - // Adjust the index - index = index + match[0].length; - } - // Return not a number - if (representation[index]) - return new Decimal128(buffer_1.from(NAN_BUFFER)); - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } - else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } - else { - exponent = exponent - radixPosition; - } - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit. can only do this if < significant digits than # stored. - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } - else { - // adjust to round - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } - else { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits) { - var endOfString = nDigitsRead; - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - // if negative, we need to increment again to account for - sign at start. - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - var dIdx = lastDigit; - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } - else { - return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - } - } - } - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } - else if (lastDigit - firstDigit < 17) { - var dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - else { - var dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - significandLow = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } - else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - dec.low = significand.low; - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - // Encode into a buffer - var buffer = buffer_1.alloc(16); - index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - // Return the new Decimal128 - return new Decimal128(buffer); - }; - /** Create a string representation of the raw Decimal128 value */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) - significand[i] = 0; - // read pointer into significand - var index = 0; - // true if the number is zero - var is_zero = false; - // the most significant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: [0, 0, 0, 0] }; - // indexing variables - var j, k; - // Output string - var string = []; - // Unpack index - index = 0; - // Buffer reference - var buffer = this.bytes; - // Unpack the low 64bits into a long - // bits 96 - 127 - var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 64 - 95 - var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack the high 64bits into a long - // bits 32 - 63 - var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 0 - 31 - var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack index - index = 0; - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - // Decode combination field and exponent - // bits 1 - 5 - var combination = (high >> 26) & COMBINATION_MASK; - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } - else if (combination === COMBINATION_NAN) { - return 'NaN'; - } - else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } - else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - // unbiased exponent - var exponent = biased_exponent - EXPONENT_BIAS; - // Create string of significand digits - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0) { - is_zero = true; - } - else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Perform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) - continue; - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } - else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - // the exponent if scientific notation is used - var scientific_exponent = significand_digits - 1 + exponent; - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - // if there are too many significant digits, we should just be treating numbers - // as + or - 0 and using the non-scientific exponent (this is for the "invalid - // representation should be treated as 0/-0" spec cases in decimal128-1.json) - if (significand_digits > 34) { - string.push("" + 0); - if (exponent > 0) - string.push('E+' + exponent); - else if (exponent < 0) - string.push('E' + exponent); - return string.join(''); - } - string.push("" + significand[index++]); - significand_digits = significand_digits - 1; - if (significand_digits) { - string.push('.'); - } - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } - else { - string.push("" + scientific_exponent); - } - } - else { - // Regular format with no decimal place - if (exponent >= 0) { - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - } - else { - var radix_position = significand_digits + exponent; - // non-zero digits before radix - if (radix_position > 0) { - for (var i = 0; i < radix_position; i++) { - string.push("" + significand[index++]); - } - } - else { - string.push('0'); - } - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push("" + significand[index++]); - } - } - } - return string.join(''); - }; - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.prototype.toExtendedJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.fromExtendedJSON = function (doc) { - return Decimal128.fromString(doc.$numberDecimal); - }; - /** @internal */ - Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Decimal128.prototype.inspect = function () { - return "new Decimal128(\"" + this.toString() + "\")"; - }; - return Decimal128; -}()); -Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); - -/** - * A class representation of the BSON Double type. - * @public - */ -var Double = /** @class */ (function () { - /** - * Create a Double type - * - * @param value - the number we want to represent as a double. - */ - function Double(value) { - if (!(this instanceof Double)) - return new Double(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; - } - /** - * Access the number value. - * - * @returns returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - Double.prototype.toJSON = function () { - return this.value; - }; - Double.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - /** @internal */ - Double.prototype.toExtendedJSON = function (options) { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user - // explicitly provided `-0` then we need to ensure the sign makes it into the output - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: "-" + this.value.toFixed(1) }; - } - var $numberDouble; - if (Number.isInteger(this.value)) { - $numberDouble = this.value.toFixed(1); - if ($numberDouble.length >= 13) { - $numberDouble = this.value.toExponential(13).toUpperCase(); - } - } - else { - $numberDouble = this.value.toString(); - } - return { $numberDouble: $numberDouble }; - }; - /** @internal */ - Double.fromExtendedJSON = function (doc, options) { - var doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - }; - /** @internal */ - Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Double.prototype.inspect = function () { - var eJSON = this.toExtendedJSON(); - return "new Double(" + eJSON.$numberDouble + ")"; - }; - return Double; -}()); -Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); - -/** - * A class representation of a BSON Int32 type. - * @public - */ -var Int32 = /** @class */ (function () { - /** - * Create an Int32 type - * - * @param value - the number we want to represent as an int32. - */ - function Int32(value) { - if (!(this instanceof Int32)) - return new Int32(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value | 0; - } - /** - * Access the number value. - * - * @returns returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - Int32.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - Int32.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - Int32.prototype.toExtendedJSON = function (options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; - }; - /** @internal */ - Int32.fromExtendedJSON = function (doc, options) { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - }; - /** @internal */ - Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Int32.prototype.inspect = function () { - return "new Int32(" + this.valueOf() + ")"; - }; - return Int32; -}()); -Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); - -/** - * A class representation of the BSON MaxKey type. - * @public - */ -var MaxKey = /** @class */ (function () { - function MaxKey() { - if (!(this instanceof MaxKey)) - return new MaxKey(); - } - /** @internal */ - MaxKey.prototype.toExtendedJSON = function () { - return { $maxKey: 1 }; - }; - /** @internal */ - MaxKey.fromExtendedJSON = function () { - return new MaxKey(); - }; - /** @internal */ - MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MaxKey.prototype.inspect = function () { - return 'new MaxKey()'; - }; - return MaxKey; -}()); -Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); - -/** - * A class representation of the BSON MinKey type. - * @public - */ -var MinKey = /** @class */ (function () { - function MinKey() { - if (!(this instanceof MinKey)) - return new MinKey(); - } - /** @internal */ - MinKey.prototype.toExtendedJSON = function () { - return { $minKey: 1 }; - }; - /** @internal */ - MinKey.fromExtendedJSON = function () { - return new MinKey(); - }; - /** @internal */ - MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MinKey.prototype.inspect = function () { - return 'new MinKey()'; - }; - return MinKey; -}()); -Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); -// Unique sequence for the current process (initialized on first use) -var PROCESS_UNIQUE = null; -var kId = Symbol('id'); -/** - * A class representation of the BSON ObjectId type. - * @public - */ -var ObjectId = /** @class */ (function () { - /** - * Create an ObjectId type - * - * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. - */ - function ObjectId(inputId) { - if (!(this instanceof ObjectId)) - return new ObjectId(inputId); - // workingId is set based on type of input and whether valid id exists for the input - var workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer'); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = buffer_1.from(inputId.toHexString(), 'hex'); - } - else { - workingId = inputId.id; - } - } - else { - workingId = inputId; - } - // the following cases use workingId to construct an ObjectId - if (workingId == null || typeof workingId === 'number') { - // The most common use case (blank id, new objectId instance) - // Generate a new id - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } - else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ensureBuffer(workingId); - } - else if (typeof workingId === 'string') { - if (workingId.length === 12) { - var bytes = buffer_1.from(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes'); - } - } - else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = buffer_1.from(workingId, 'hex'); - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters'); - } - } - else { - throw new BSONTypeError('Argument passed in does not match the accepted types'); - } - // If we are caching the hex string - if (ObjectId.cacheHexString) { - this.__id = this.id.toString('hex'); - } - } - Object.defineProperty(ObjectId.prototype, "id", { - /** - * The ObjectId bytes - * @readonly - */ - get: function () { - return this[kId]; - }, - set: function (value) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = value.toString('hex'); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectId.prototype, "generationTime", { - /** - * The generation time of this ObjectId instance - * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch - */ - get: function () { - return this.id.readInt32BE(0); - }, - set: function (value) { - // Encode time into first 4 bytes - this.id.writeUInt32BE(value, 0); - }, - enumerable: false, - configurable: true - }); - /** Returns the ObjectId id as a 24 character hex string representation */ - ObjectId.prototype.toHexString = function () { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - var hexString = this.id.toString('hex'); - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - return hexString; - }; - /** - * Update the ObjectId index - * @privateRemarks - * Used in generating new ObjectId's on the driver - * @internal - */ - ObjectId.getInc = function () { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - }; - /** - * Generate a 12 byte id buffer used in ObjectId's - * - * @param time - pass in a second based timestamp. - */ - ObjectId.generate = function (time) { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - var inc = ObjectId.getInc(); - var buffer = buffer_1.alloc(12); - // 4-byte timestamp - buffer.writeUInt32BE(time, 0); - // set PROCESS_UNIQUE if yet not initialized - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = randomBytes(5); - } - // 5-byte process unique - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - // 3-byte counter - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - return buffer; - }; - /** - * Converts the id into a 24 character hex string for printing - * - * @param format - The Buffer toString format parameter. - */ - ObjectId.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (format) - return this.id.toString(format); - return this.toHexString(); - }; - /** Converts to its JSON the 24 character hex string representation. */ - ObjectId.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this ObjectId with `otherID`. - * - * @param otherId - ObjectId instance to compare against. - */ - ObjectId.prototype.equals = function (otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (otherId instanceof ObjectId) { - return this.toString() === otherId.toString(); - } - if (typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - isUint8Array(this.id)) { - return otherId === buffer_1.prototype.toString.call(this.id, 'latin1'); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return buffer_1.from(otherId).equals(this.id); - } - if (typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function') { - return otherId.toHexString() === this.toHexString(); - } - return false; - }; - /** Returns the generation date (accurate up to the second) that this ID was generated. */ - ObjectId.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id.readUInt32BE(0); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - /** @internal */ - ObjectId.createPk = function () { - return new ObjectId(); - }; - /** - * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. - * - * @param time - an integer number representing a number of seconds. - */ - ObjectId.createFromTime = function (time) { - var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer.writeUInt32BE(time, 0); - // Return the new objectId - return new ObjectId(buffer); - }; - /** - * Creates an ObjectId from a hex string representation of an ObjectId. - * - * @param hexString - create a ObjectId from a passed in 24 character hexstring. - */ - ObjectId.createFromHexString = function (hexString) { - // Throw an error if it's not a valid setup - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - return new ObjectId(buffer_1.from(hexString, 'hex')); - }; - /** - * Checks if a value is a valid bson ObjectId - * - * @param id - ObjectId instance to validate. - */ - ObjectId.isValid = function (id) { - if (id == null) - return false; - if (typeof id === 'number') { - return true; - } - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - if (id instanceof ObjectId) { - return true; - } - if (isUint8Array(id) && id.length === 12) { - return true; - } - // Duck-Typing detection of ObjectId like objects - if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { - if (typeof id.id === 'string') { - return id.id.length === 12; - } - return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); - } - return false; - }; - /** @internal */ - ObjectId.prototype.toExtendedJSON = function () { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - }; - /** @internal */ - ObjectId.fromExtendedJSON = function (doc) { - return new ObjectId(doc.$oid); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 24 character hex string representation. - * @internal - */ - ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - ObjectId.prototype.inspect = function () { - return "new ObjectId(\"" + this.toHexString() + "\")"; - }; - /** @internal */ - ObjectId.index = Math.floor(Math.random() * 0xffffff); - return ObjectId; -}()); -// Deprecated methods -Object.defineProperty(ObjectId.prototype, 'generate', { - value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') -}); -Object.defineProperty(ObjectId.prototype, 'getInc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId.prototype, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); - -function alphabetize(str) { - return str.split('').sort().join(''); -} -/** - * A class representation of the BSON RegExp type. - * @public - */ -var BSONRegExp = /** @class */ (function () { - /** - * @param pattern - The regular expression pattern to match - * @param options - The regular expression options - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) - return new BSONRegExp(pattern, options); - this.pattern = pattern; - this.options = alphabetize(options !== null && options !== void 0 ? options : ''); - if (this.pattern.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); - } - if (this.options.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); - } - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u')) { - throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); - } - } - } - BSONRegExp.parseOptions = function (options) { - return options ? options.split('').sort().join('') : ''; - }; - /** @internal */ - BSONRegExp.prototype.toExtendedJSON = function (options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - }; - /** @internal */ - BSONRegExp.fromExtendedJSON = function (doc) { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - // This is for $regex query operators that have extended json values. - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc; - } - } - else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); - } - throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); - }; - return BSONRegExp; -}()); -Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); - -/** - * A class representation of the BSON Symbol type. - * @public - */ -var BSONSymbol = /** @class */ (function () { - /** - * @param value - the string representing the symbol. - */ - function BSONSymbol(value) { - if (!(this instanceof BSONSymbol)) - return new BSONSymbol(value); - this.value = value; - } - /** Access the wrapped string value. */ - BSONSymbol.prototype.valueOf = function () { - return this.value; - }; - BSONSymbol.prototype.toString = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.inspect = function () { - return "new BSONSymbol(\"" + this.value + "\")"; - }; - BSONSymbol.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.toExtendedJSON = function () { - return { $symbol: this.value }; - }; - /** @internal */ - BSONSymbol.fromExtendedJSON = function (doc) { - return new BSONSymbol(doc.$symbol); - }; - /** @internal */ - BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - return BSONSymbol; -}()); -Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); - -/** @public */ -var LongWithoutOverridesClass = Long; -/** @public */ -var Timestamp = /** @class */ (function (_super) { - __extends(Timestamp, _super); - function Timestamp(low, high) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - ///@ts-expect-error - if (!(_this instanceof Timestamp)) - return new Timestamp(low, high); - if (Long.isLong(low)) { - _this = _super.call(this, low.low, low.high, true) || this; - } - else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { - _this = _super.call(this, low.i, low.t, true) || this; - } - else { - _this = _super.call(this, low, high, true) || this; - } - Object.defineProperty(_this, '_bsontype', { - value: 'Timestamp', - writable: false, - configurable: false, - enumerable: false - }); - return _this; - } - Timestamp.prototype.toJSON = function () { - return { - $timestamp: this.toString() - }; - }; - /** Returns a Timestamp represented by the given (32-bit) integer value. */ - Timestamp.fromInt = function (value) { - return new Timestamp(Long.fromInt(value, true)); - }; - /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ - Timestamp.fromNumber = function (value) { - return new Timestamp(Long.fromNumber(value, true)); - }; - /** - * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. - * - * @param lowBits - the low 32-bits. - * @param highBits - the high 32-bits. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - /** - * Returns a Timestamp from the given string, optionally using the given radix. - * - * @param str - the textual representation of the Timestamp. - * @param optRadix - the radix in which the text is written. - */ - Timestamp.fromString = function (str, optRadix) { - return new Timestamp(Long.fromString(str, true, optRadix)); - }; - /** @internal */ - Timestamp.prototype.toExtendedJSON = function () { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - }; - /** @internal */ - Timestamp.fromExtendedJSON = function (doc) { - return new Timestamp(doc.$timestamp); - }; - /** @internal */ - Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Timestamp.prototype.inspect = function () { - return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; - }; - Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - return Timestamp; -}(LongWithoutOverridesClass)); - -function isBSONType(value) { - return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); -} -// INT32 boundaries -var BSON_INT32_MAX$1 = 0x7fffffff; -var BSON_INT32_MIN$1 = -0x80000000; -// INT64 boundaries -var BSON_INT64_MAX$1 = 0x7fffffffffffffff; -var BSON_INT64_MIN$1 = -0x8000000000000000; -// all the types where we don't need to do any special processing and can just pass the EJSON -//straight to type.fromExtendedJSON -var keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function deserializeValue(value, options) { - if (options === void 0) { options = {}; } - if (typeof value === 'number') { - if (options.relaxed || options.legacy) { - return value; - } - // if it's an integer, should interpret as smallest BSON integer - // that can represent it exactly. (if out of range, interpret as double.) - if (Math.floor(value) === value) { - if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) - return new Int32(value); - if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) - return Long.fromNumber(value); - } - // If the number is a non-integer or out of integer range, should interpret as BSON Double. - return new Double(value); - } - // from here on out we're looking for bson types, so bail if its not an object - if (value == null || typeof value !== 'object') - return value; - // upgrade deprecated undefined to null - if (value.$undefined) - return null; - var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); - for (var i = 0; i < keys.length; i++) { - var c = keysToCodecs[keys[i]]; - if (c) - return c.fromExtendedJSON(value, options); - } - if (value.$date != null) { - var d = value.$date; - var date = new Date(); - if (options.legacy) { - if (typeof d === 'number') - date.setTime(d); - else if (typeof d === 'string') - date.setTime(Date.parse(d)); - } - else { - if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (Long.isLong(d)) - date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) - date.setTime(d); - } - return date; - } - if (value.$code != null) { - var copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return Code.fromExtendedJSON(value); - } - if (isDBRefLike(value) || value.$dbPointer) { - var v = value.$ref ? value : value.$dbPointer; - // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) - // because of the order JSON.parse goes through the document - if (v instanceof DBRef) - return v; - var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); - var valid_1 = true; - dollarKeys.forEach(function (k) { - if (['$ref', '$id', '$db'].indexOf(k) === -1) - valid_1 = false; - }); - // only make DBRef if $ keys are all valid - if (valid_1) - return DBRef.fromExtendedJSON(v); - } - return value; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeArray(array, options) { - return array.map(function (v, index) { - options.seenObjects.push({ propertyName: "index " + index, obj: null }); - try { - return serializeValue(v, options); - } - finally { - options.seenObjects.pop(); - } - }); -} -function getISOString(date) { - var isoStr = date.toISOString(); - // we should only show milliseconds in timestamp if they're non-zero - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeValue(value, options) { - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); - if (index !== -1) { - var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); - var leadingPart = props - .slice(0, index) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var alreadySeen = props[index]; - var circularPart = ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var current = props[props.length - 1]; - var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new BSONTypeError('Converting circular structure to EJSON:\n' + - (" " + leadingPart + alreadySeen + circularPart + current + "\n") + - (" " + leadingSpace + "\\" + dashes + "/")); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || isDate(value)) { - var dateNum = value.getTime(), - // is it in year range 1970-9999? - inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - // it's an integer - if (Math.floor(value) === value) { - var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; - // interpret as being of the smallest BSON integer type that can represent the number exactly - if (int32Range) - return { $numberInt: value.toString() }; - if (int64Range) - return { $numberLong: value.toString() }; - } - return { $numberDouble: value.toString() }; - } - if (value instanceof RegExp || isRegExp(value)) { - var flags = value.flags; - if (flags === undefined) { - var match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - var rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - if (value != null && typeof value === 'object') - return serializeDocument(value, options); - return value; -} -var BSON_TYPE_MAPPINGS = { - Binary: function (o) { return new Binary(o.value(), o.sub_type); }, - Code: function (o) { return new Code(o.code, o.scope); }, - DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, - Decimal128: function (o) { return new Decimal128(o.bytes); }, - Double: function (o) { return new Double(o.value); }, - Int32: function (o) { return new Int32(o.value); }, - Long: function (o) { - return Long.fromBits( - // underscore variants for 1.x backwards compatibility - o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); - }, - MaxKey: function () { return new MaxKey(); }, - MinKey: function () { return new MinKey(); }, - ObjectID: function (o) { return new ObjectId(o); }, - ObjectId: function (o) { return new ObjectId(o); }, - BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, - Symbol: function (o) { return new BSONSymbol(o.value); }, - Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeDocument(doc, options) { - if (doc == null || typeof doc !== 'object') - throw new BSONError('not an object instance'); - var bsontype = doc._bsontype; - if (typeof bsontype === 'undefined') { - // It's a regular object. Recursively serialize its property values. - var _doc = {}; - for (var name in doc) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - _doc[name] = serializeValue(doc[name], options); - } - finally { - options.seenObjects.pop(); - } - } - return _doc; - } - else if (isBSONType(doc)) { - // the "document" is really just a BSON type object - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var outDoc = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - // There's no EJSON serialization function on the object. It's probably an - // object created by a previous version of this library (or another library) - // that's duck-typing objects to look like they were generated by this library). - // Copy the object into this library's version of that type. - var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - // Two BSON types may have nested objects that may need to be serialized too - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } - else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); - } - return outDoc.toExtendedJSON(options); - } - else { - throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } -} -/** - * EJSON parse / stringify API - * @public - */ -// the namespace here is used to emulate `export * as EJSON from '...'` -// which as of now (sept 2020) api-extractor does not support -// eslint-disable-next-line @typescript-eslint/no-namespace -var EJSON; -(function (EJSON) { - /** - * Parse an Extended JSON string, constructing the JavaScript value or object described by that - * string. - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const text = '{ "int32": { "$numberInt": "10" } }'; - * - * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } - * console.log(EJSON.parse(text, { relaxed: false })); - * - * // prints { int32: 10 } - * console.log(EJSON.parse(text)); - * ``` - */ - function parse(text, options) { - var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); - // relaxed implies not strict - if (typeof finalOptions.relaxed === 'boolean') - finalOptions.strict = !finalOptions.relaxed; - if (typeof finalOptions.strict === 'boolean') - finalOptions.relaxed = !finalOptions.strict; - return JSON.parse(text, function (key, value) { - if (key.indexOf('\x00') !== -1) { - throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); - } - return deserializeValue(value, finalOptions); - }); - } - EJSON.parse = parse; - /** - * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer - * function is specified or optionally including only the specified properties if a replacer array - * is specified. - * - * @param value - The value to convert to extended JSON - * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string - * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. - * @param options - Optional settings - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const Int32 = require('mongodb').Int32; - * const doc = { int32: new Int32(10) }; - * - * // prints '{"int32":{"$numberInt":"10"}}' - * console.log(EJSON.stringify(doc, { relaxed: false })); - * - * // prints '{"int32":10}' - * console.log(EJSON.stringify(doc)); - * ``` - */ - function stringify(value, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - replacer, space, options) { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - var doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer, space); - } - EJSON.stringify = stringify; - /** - * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - * - * @param value - The object to serialize - * @param options - Optional settings passed to the `stringify` function - */ - function serialize(value, options) { - options = options || {}; - return JSON.parse(stringify(value, options)); - } - EJSON.serialize = serialize; - /** - * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - * - * @param ejson - The Extended JSON object to deserialize - * @param options - Optional settings passed to the parse method - */ - function deserialize(ejson, options) { - options = options || {}; - return parse(JSON.stringify(ejson), options); - } - EJSON.deserialize = deserialize; -})(EJSON || (EJSON = {})); - -/* eslint-disable @typescript-eslint/no-explicit-any */ -/** @public */ -var bsonMap; -var bsonGlobal = getGlobal(); -if (bsonGlobal.Map) { - bsonMap = bsonGlobal.Map; -} -else { - // We will return a polyfill - bsonMap = /** @class */ (function () { - function Map(array) { - if (array === void 0) { array = []; } - this._keys = []; - this._values = {}; - for (var i = 0; i < array.length; i++) { - if (array[i] == null) - continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - } - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) - return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - Map.prototype.entries = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? [key, _this._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.forEach = function (callback, self) { - self = self || this; - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - Map.prototype.keys = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - Map.prototype.values = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? _this._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Object.defineProperty(Map.prototype, "size", { - get: function () { - return this._keys.length; - }, - enumerable: false, - configurable: true - }); - return Map; - }()); -} - -/** @internal */ -var BSON_INT32_MAX = 0x7fffffff; -/** @internal */ -var BSON_INT32_MIN = -0x80000000; -/** @internal */ -var BSON_INT64_MAX = Math.pow(2, 63) - 1; -/** @internal */ -var BSON_INT64_MIN = -Math.pow(2, 63); -/** - * Any integer up to 2^53 can be precisely represented by a double. - * @internal - */ -var JS_INT_MAX = Math.pow(2, 53); -/** - * Any integer down to -2^53 can be precisely represented by a double. - * @internal - */ -var JS_INT_MIN = -Math.pow(2, 53); -/** Number BSON Type @internal */ -var BSON_DATA_NUMBER = 1; -/** String BSON Type @internal */ -var BSON_DATA_STRING = 2; -/** Object BSON Type @internal */ -var BSON_DATA_OBJECT = 3; -/** Array BSON Type @internal */ -var BSON_DATA_ARRAY = 4; -/** Binary BSON Type @internal */ -var BSON_DATA_BINARY = 5; -/** Binary BSON Type @internal */ -var BSON_DATA_UNDEFINED = 6; -/** ObjectId BSON Type @internal */ -var BSON_DATA_OID = 7; -/** Boolean BSON Type @internal */ -var BSON_DATA_BOOLEAN = 8; -/** Date BSON Type @internal */ -var BSON_DATA_DATE = 9; -/** null BSON Type @internal */ -var BSON_DATA_NULL = 10; -/** RegExp BSON Type @internal */ -var BSON_DATA_REGEXP = 11; -/** Code BSON Type @internal */ -var BSON_DATA_DBPOINTER = 12; -/** Code BSON Type @internal */ -var BSON_DATA_CODE = 13; -/** Symbol BSON Type @internal */ -var BSON_DATA_SYMBOL = 14; -/** Code with Scope BSON Type @internal */ -var BSON_DATA_CODE_W_SCOPE = 15; -/** 32 bit Integer BSON Type @internal */ -var BSON_DATA_INT = 16; -/** Timestamp BSON Type @internal */ -var BSON_DATA_TIMESTAMP = 17; -/** Long BSON Type @internal */ -var BSON_DATA_LONG = 18; -/** Decimal128 BSON Type @internal */ -var BSON_DATA_DECIMAL128 = 19; -/** MinKey BSON Type @internal */ -var BSON_DATA_MIN_KEY = 0xff; -/** MaxKey BSON Type @internal */ -var BSON_DATA_MAX_KEY = 0x7f; -/** Binary Default Type @internal */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** Binary Function Type @internal */ -var BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** Binary Byte Array Type @internal */ -var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ -var BSON_BINARY_SUBTYPE_UUID = 3; -/** Binary UUID Type @internal */ -var BSON_BINARY_SUBTYPE_UUID_NEW = 4; -/** Binary MD5 Type @internal */ -var BSON_BINARY_SUBTYPE_MD5 = 5; -/** Encrypted BSON type @internal */ -var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; -/** Column BSON type @internal */ -var BSON_BINARY_SUBTYPE_COLUMN = 7; -/** Binary User Defined Type @internal */ -var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } - else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - return totalLength; -} -/** @internal */ -function calculateElement(name, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -value, serializeFunctions, isArray, ignoreUndefined) { - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (isArray === void 0) { isArray = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = false; } - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - switch (typeof value) { - case 'string': - return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && - value >= JS_INT_MIN && - value <= JS_INT_MAX) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - // 32 bit - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } - else { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } - else { - // 64 bit - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } - else if (value instanceof Date || isDate(value)) { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - isAnyArrayBuffer(value)) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); - } - else if (value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (value['_bsontype'] === 'Decimal128') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } - else if (value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.byteLength(value.code.toString(), 'utf8') + - 1); - } - } - else if (value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4)); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); - } - } - else if (value['_bsontype'] === 'Symbol') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - buffer_1.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1); - } - else if (value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - // Add db reference if it exists - if (value.db != null) { - ordered_values['$db'] = value.db; - } - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); - } - else if (value instanceof RegExp || isRegExp(value)) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else if (value['_bsontype'] === 'BSONRegExp') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.pattern, 'utf8') + - 1 + - buffer_1.byteLength(value.options, 'utf8') + - 1); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + - 1); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else if (serializeFunctions) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + - 1); - } - } - } - return 0; -} - -var FIRST_BIT = 0x80; -var FIRST_TWO_BITS = 0xc0; -var FIRST_THREE_BITS = 0xe0; -var FIRST_FOUR_BITS = 0xf0; -var FIRST_FIVE_BITS = 0xf8; -var TWO_BIT_CHAR = 0xc0; -var THREE_BIT_CHAR = 0xe0; -var FOUR_BIT_CHAR = 0xf0; -var CONTINUING_CHAR = 0x80; -/** - * Determines if the passed in bytes are valid utf8 - * @param bytes - An array of 8-bit bytes. Must be indexable and have length property - * @param start - The index to start validating - * @param end - The index to end validating - */ -function validateUtf8(bytes, start, end) { - var continuation = 0; - for (var i = start; i < end; i += 1) { - var byte = bytes[i]; - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } - else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } - else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } - else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } - else { - return false; - } - } - } - return !continuation; -} - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); -var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); -var functionCache = {}; -function deserialize$1(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (size < 5) { - throw new BSONError("bson size must be >= 5, is " + size); - } - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); - } - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); - } - if (size + index > buffer.byteLength) { - throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); - } - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -} -var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; -function deserializeObject(buffer, index, options, isArray) { - if (isArray === void 0) { isArray = false; } - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - // Ensures default validation option if none given - var validation = options.validation == null ? { utf8: true } : options.validation; - // Shows if global utf-8 validation is enabled or disabled - var globalUTFValidation = true; - // Reflects utf-8 validation setting regardless of global or specific key validation - var validationSetting; - // Set of keys either to enable or disable validation on - var utf8KeysSet = new Set(); - // Check for boolean uniformity and empty validation option - var utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } - else { - globalUTFValidation = false; - var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - // Ensures boolean uniformity in utf-8 validation (all true or all false) - if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) { - throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - // Add keys to set that will either be validated or not based on validationSetting - if (!globalUTFValidation) { - for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) { - var key = _a[_i]; - utf8KeysSet.add(key); - } - } - // Set the start index - var startIndex = index; - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) - throw new BSONError('corrupt bson message < 5 bytes long'); - // Read the document size - var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) - throw new BSONError('corrupt bson message'); - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - var done = false; - var isPossibleDBRef = isArray ? false : null; - // While we have more left data left keep parsing - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) - break; - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.byteLength) - throw new BSONError('Bad BSON Document: illegal CString'); - // Represents the key - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - // shouldValidateKey is true if the key should be validated, false otherwise - var shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } - else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - var value = void 0; - index = i + 1; - if (elementType === BSON_DATA_STRING) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } - else if (elementType === BSON_DATA_OID) { - var oid = buffer_1.alloc(12); - buffer.copy(oid, 0, index, index + 12); - value = new ObjectId(oid); - index = index + 12; - } - else if (elementType === BSON_DATA_INT && promoteValues === false) { - value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); - } - else if (elementType === BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } - else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { - value = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } - else if (elementType === BSON_DATA_NUMBER) { - value = buffer.readDoubleLE(index); - index = index + 8; - } - else if (elementType === BSON_DATA_DATE) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new Long(lowBits, highBits).toNumber()); - } - else if (elementType === BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } - else if (elementType === BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new BSONError('bad embedded document length in bson'); - // We have a raw value - if (raw) { - value = buffer.slice(index, index + objectSize); - } - else { - var objectOptions = options; - if (!globalUTFValidation) { - objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - index = index + objectSize; - } - else if (elementType === BSON_DATA_ARRAY) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - // Stop index - var stopIndex = index + objectSize; - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) { - arrayOptions[n] = options[n]; - } - arrayOptions['raw'] = true; - } - if (!globalUTFValidation) { - arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - if (buffer[index - 1] !== 0) - throw new BSONError('invalid array terminator byte'); - if (index !== stopIndex) - throw new BSONError('corrupted array bson'); - } - else if (elementType === BSON_DATA_UNDEFINED) { - value = undefined; - } - else if (elementType === BSON_DATA_NULL) { - value = null; - } - else if (elementType === BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } - else { - value = long; - } - } - else if (elementType === BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = buffer_1.alloc(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { - value = decimal128.toObject(); - } - else { - value = decimal128; - } - } - else if (elementType === BSON_DATA_BINARY) { - var binarySize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - // Did we have a negative binary size, throw - if (binarySize < 0) - throw new BSONError('Negative binary type element size found'); - // Is the length longer than the document - if (binarySize > buffer.byteLength) - throw new BSONError('Binary type size larger than document size'); - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - if (promoteBuffers && promoteValues) { - value = buffer.slice(index, index + binarySize); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - } - } - else { - var _buffer = buffer_1.alloc(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - if (promoteBuffers && promoteValues) { - value = _buffer; - } - else { - value = new Binary(_buffer, subType); - } - } - // Update the index - index = index + binarySize; - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - value = new RegExp(source, optionsArray.join('')); - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // Set the object - value = new BSONRegExp(source, regExpOptions); - } - else if (elementType === BSON_DATA_SYMBOL) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new BSONSymbol(symbol); - index = index + stringSize; - } - else if (elementType === BSON_DATA_TIMESTAMP) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Timestamp(lowBits, highBits); - } - else if (elementType === BSON_DATA_MIN_KEY) { - value = new MinKey(); - } - else if (elementType === BSON_DATA_MAX_KEY) { - value = new MaxKey(); - } - else if (elementType === BSON_DATA_CODE) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - } - else { - value = new Code(functionString); - } - // Update parse index position - index = index + stringSize; - } - else if (elementType === BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError('code_w_scope total size shorter minimum expected length'); - } - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - // Javascript function - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // Update parse index position - index = index + stringSize; - // Parse the element - var _index = index; - // Decode the size of the object document - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - // Check if field length is too short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too short, truncating scope'); - } - // Check if totalSize field is too long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too long, clips outer document'); - } - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - value.scope = scopeObject; - } - else { - value = new Code(functionString, scopeObject); - } - } - else if (elementType === BSON_DATA_DBPOINTER) { - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) - throw new BSONError('bad string length in bson'); - // Namespace - if (validation != null && validation.utf8) { - if (!validateUtf8(buffer, index, index + stringSize - 1)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - } - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Read the oid - var oidBuffer = buffer_1.alloc(12); - buffer.copy(oidBuffer, 0, index, index + 12); - var oid = new ObjectId(oidBuffer); - // Update the index - index = index + 12; - // Upgrade to DBRef type - value = new DBRef(namespace, oid); - } - else { - throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value: value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - object[name] = value; - } - } - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) - throw new BSONError('corrupt array bson'); - throw new BSONError('corrupt object bson'); - } - // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef - if (!isPossibleDBRef) - return object; - if (isDBRefLike(object)) { - var copy = Object.assign({}, object); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object.$ref, object.$id, object.$db, copy); - } - return object; -} -/** - * Ensure eval is isolated, store the result in functionCache. - * - * @internal - */ -function isolateEval(functionString, functionCache, object) { - if (!functionCache) - return new Function(functionString); - // Check for cache hit, eval if missing and return cached function - if (functionCache[functionString] == null) { - functionCache[functionString] = new Function(functionString); - } - // Set the object - return functionCache[functionString].bind(object); -} -function getValidatedString(buffer, start, end, shouldValidateUtf8) { - var value = buffer.toString('utf8', start, end); - // if utf8 validation is on, do the check - if (shouldValidateUtf8) { - for (var i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validateUtf8(buffer, start, end)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; -} - -// Copyright (c) 2008, Fair Oaks Labs, Inc. -function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { - var e; - var m; - var c; - var bBE = endian === 'big'; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = bBE ? nBytes - 1 : 0; - var d = bBE ? -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; - } - } - if (isNaN(value)) - m = 0; - while (mLen >= 8) { - buffer[offset + i] = m & 0xff; - i += d; - m /= 256; - mLen -= 8; - } - e = (e << mLen) | m; - if (isNaN(value)) - e += 8; - eLen += mLen; - while (eLen > 0) { - buffer[offset + i] = e & 0xff; - i += d; - e /= 256; - eLen -= 8; - } - buffer[offset + i - d] |= s * 128; -} - -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); -/* - * isArray indicates if we are writing to a BSON array (type 0x04) - * which forces the "key" which really an array index as a string to be written as ascii - * This will catch any errors in index as a string generation - */ -function serializeString(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, undefined, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -} -function serializeNumber(buffer, key, value, index, isArray) { - // We have an integer value - // TODO(NODE-2529): Add support for big int - if (Number.isInteger(value) && - value >= BSON_INT32_MIN && - value <= BSON_INT32_MAX) { - // If the value fits in 32 bits encode as int32 - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } - else { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - } - return index; -} -function serializeNull(buffer, key, _, index, isArray) { - // Set long type - buffer[index++] = BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeBoolean(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} -function serializeDate(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.ignoreCase) - buffer[index++] = 0x69; // i - if (value.global) - buffer[index++] = 0x73; // s - if (value.multiline) - buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -} -function serializeBSONRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.pattern, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; -} -function serializeMinMax(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON_DATA_NULL; - } - else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON_DATA_MIN_KEY; - } - else { - buffer[index++] = BSON_DATA_MAX_KEY; - } - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeObjectId(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, undefined, 'binary'); - } - else if (isUint8Array(value.id)) { - // Use the standard JS methods here because buffer.copy() is buggy with the - // browser polyfill - buffer.set(value.id.subarray(0, 12), index); - } - else { - throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - // Adjust index - return index + 12; -} -function serializeBuffer(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - buffer.set(ensureBuffer(value), index); - // Adjust the index - index = index + size; - return index; -} -function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (path === void 0) { path = []; } - for (var i = 0; i < path.length; i++) { - if (path[i] === value) - throw new BSONError('cyclic dependency detected'); - } - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - return endIndex; -} -function serializeDecimal128(buffer, key, value, index, isArray) { - buffer[index++] = BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - // Prefer the standard JS methods because their typechecking is not buggy, - // unlike the `buffer` polyfill's. - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; -} -function serializeLong(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = - value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeInt32(buffer, key, value, index, isArray) { - value = value.valueOf(); - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -} -function serializeDouble(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value.value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - return index; -} -function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} -function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Starting index - var startIndex = index; - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - // Writ the total - var totalSize = endIndex - startIndex; - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } - else { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - return index; -} -function serializeBinary(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - // Write the data to the object - buffer.set(data, index); - // Adjust the index - index = index + value.position; - return index; -} -function serializeSymbol(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} -function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var startIndex = index; - var output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; - } - output = Object.assign(output, value.fields); - var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} -function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (startingIndex === void 0) { startingIndex = 0; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (path === void 0) { path = []; } - startingIndex = startingIndex || 0; - path = path || []; - // Push the object to the path - path.push(object); - // Start place to serialize into - var index = startingIndex + 4; - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index, true); - } - else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } - else if (typeof value === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } - else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } - else if (typeof value === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } - else if (typeof value === 'object' && - isBSONType(value) && - value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else if (object instanceof bsonMap || isMap(object)) { - var iterator = object.entries(); - var done = false; - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = !!entry.done; - // Are we done, then skip and terminate - if (done) - continue; - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new BSONTypeError('toBSON function did not return an object'); - } - // Iterate over all the keys - for (var key in object) { - var value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - if (ignoreUndefined === false) - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - // Remove the path - path.pop(); - // Final padding byte for object - buffer[index++] = 0x00; - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -/** @internal */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; -// Current Internal Temporary Serialization Buffer -var buffer = buffer_1.alloc(MAXSIZE); -/** - * Sets the size of the internal serialization buffer. - * - * @param size - The desired size for the internal serialization buffer - * @public - */ -function setInternalBufferSize(size) { - // Resize the internal serialization buffer if needed - if (buffer.length < size) { - buffer = buffer_1.alloc(size); - } -} -/** - * Serialize a Javascript object. - * - * @param object - the Javascript object to serialize. - * @returns Buffer object containing the serialized object. - * @public - */ -function serialize(object, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = buffer_1.alloc(minInternalBufferSize); - } - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = buffer_1.alloc(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -} -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, - * useful when pre-allocating the space for serialization. - * - * @param object - the Javascript object to serialize. - * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. - * @returns the index pointing to the last written byte in the buffer. - * @public - */ -function serializeWithBufferAndIndex(object, finalBuffer, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - // Return the index - return startIndex + serializationIndex - 1; -} -/** - * Deserialize data as BSON. - * - * @param buffer - the buffer containing the serialized set of BSON documents. - * @returns returns the deserialized Javascript Object. - * @public - */ -function deserialize(buffer, options) { - if (options === void 0) { options = {}; } - return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options); -} -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param object - the Javascript object to calculate the BSON byte size for - * @returns size of BSON object in bytes - * @public - */ -function calculateObjectSize(object, options) { - if (options === void 0) { options = {}; } - options = options || {}; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); -} -/** - * Deserialize stream data as BSON documents. - * - * @param data - the buffer containing the serialized set of BSON documents. - * @param startIndex - the start index in the data Buffer where the deserialization is to start. - * @param numberOfDocuments - number of documents to deserialize. - * @param documents - an array where to store the deserialized documents. - * @param docStartIndex - the index in the documents array from where to start inserting documents. - * @param options - additional options used for the deserialization. - * @returns next index in the buffer after deserialization **x** numbers of documents. - * @public - */ -function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - var bufferData = ensureBuffer(data); - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - // Update options with index - internalOptions.index = index; - // Parse the document at this point - documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); - // Adjust index by the document size - index = index + size; - } - // Return object containing end index of parsing and list of documents - return index; -} -/** - * BSON default export - * @deprecated Please use named exports - * @privateRemarks - * We want to someday deprecate the default export, - * so none of the new TS types are being exported on the default - * @public - */ -var BSON = { - Binary: Binary, - Code: Code, - DBRef: DBRef, - Decimal128: Decimal128, - Double: Double, - Int32: Int32, - Long: Long, - UUID: UUID, - Map: bsonMap, - MaxKey: MaxKey, - MinKey: MinKey, - ObjectId: ObjectId, - ObjectID: ObjectId, - BSONRegExp: BSONRegExp, - BSONSymbol: BSONSymbol, - Timestamp: Timestamp, - EJSON: EJSON, - setInternalBufferSize: setInternalBufferSize, - serialize: serialize, - serializeWithBufferAndIndex: serializeWithBufferAndIndex, - deserialize: deserialize, - calculateObjectSize: calculateObjectSize, - deserializeStream: deserializeStream, - BSONError: BSONError, - BSONTypeError: BSONTypeError -}; - -export default BSON; -export { BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize }; -//# sourceMappingURL=bson.browser.esm.js.map diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.esm.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.esm.js.map deleted file mode 100644 index 719d85b..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.esm.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bson.browser.esm.js","sources":["../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/buffer/index.js","../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"sourcesContent":["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n var proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n var copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(buf).copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["byteLength","toByteArray","fromByteArray","lookup","revLookup","Arr","Uint8Array","Array","code","i","len","length","charCodeAt","getLens","b64","Error","validLen","indexOf","placeHoldersLen","lens","_byteLength","tmp","arr","curByte","tripletToBase64","num","encodeChunk","uint8","start","end","output","push","join","extraBytes","parts","maxChunkLength","len2","buffer","offset","isLE","mLen","nBytes","e","m","eLen","eMax","eBias","nBits","d","s","NaN","Infinity","Math","pow","value","c","rt","abs","isNaN","floor","log","LN2","customInspectSymbol","Symbol","exports","Buffer","SlowBuffer","K_MAX_LENGTH","TYPED_ARRAY_SUPPORT","typedArraySupport","console","error","proto","foo","Object","setPrototypeOf","prototype","defineProperty","enumerable","get","isBuffer","undefined","byteOffset","createBuffer","RangeError","buf","arg","encodingOrOffset","TypeError","allocUnsafe","from","poolSize","fromString","ArrayBuffer","isView","fromArrayView","isInstance","fromArrayBuffer","SharedArrayBuffer","valueOf","b","fromObject","toPrimitive","assertSize","size","alloc","fill","encoding","checked","allocUnsafeSlow","string","isEncoding","actual","write","slice","fromArrayLike","array","arrayView","copy","obj","numberIsNaN","type","isArray","data","toString","_isBuffer","compare","a","x","y","min","String","toLowerCase","concat","list","pos","set","call","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","swap16","swap32","swap64","apply","toLocaleString","equals","inspect","str","max","INSPECT_MAX_BYTES","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","includes","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","utf16leToBytes","isFinite","toJSON","_arr","base64","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","MAX_ARGUMENTS_LENGTH","codePoints","fromCharCode","ret","out","hexSliceLookupTable","bytes","newBuf","subarray","checkOffset","ext","readUintLE","readUIntLE","noAssert","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","ieee754","readFloatBE","readDoubleLE","readDoubleBE","checkInt","writeUintLE","writeUIntLE","maxBytes","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","checkIEEE754","writeFloat","littleEndian","writeFloatLE","writeFloatBE","writeDouble","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","base64clean","split","units","leadSurrogate","byteArray","hi","lo","src","dst","constructor","name","alphabet","table","i16","extendStatics","__proto__","p","hasOwnProperty","__extends","__","create","__assign","assign","t","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;;;AAEA,gBAAkB,GAAGA,UAArB;AACA,iBAAmB,GAAGC,WAAtB;AACA,mBAAqB,GAAGC,aAAxB;AAEA,IAAIC,MAAM,GAAG,EAAb;AACA,IAAIC,SAAS,GAAG,EAAhB;AACA,IAAIC,GAAG,GAAG,OAAOC,UAAP,KAAsB,WAAtB,GAAoCA,UAApC,GAAiDC,KAA3D;AAEA,IAAIC,IAAI,GAAG,kEAAX;;AACA,KAAK,IAAIC,CAAC,GAAG,CAAR,EAAWC,GAAG,GAAGF,IAAI,CAACG,MAA3B,EAAmCF,CAAC,GAAGC,GAAvC,EAA4C,EAAED,CAA9C,EAAiD;AAC/CN,EAAAA,MAAM,CAACM,CAAD,CAAN,GAAYD,IAAI,CAACC,CAAD,CAAhB;AACAL,EAAAA,SAAS,CAACI,IAAI,CAACI,UAAL,CAAgBH,CAAhB,CAAD,CAAT,GAAgCA,CAAhC;AACD;AAGD;;;AACAL,SAAS,CAAC,IAAIQ,UAAJ,CAAe,CAAf,CAAD,CAAT,GAA+B,EAA/B;AACAR,SAAS,CAAC,IAAIQ,UAAJ,CAAe,CAAf,CAAD,CAAT,GAA+B,EAA/B;;AAEA,SAASC,OAAT,CAAkBC,GAAlB,EAAuB;AACrB,MAAIJ,GAAG,GAAGI,GAAG,CAACH,MAAd;;AAEA,MAAID,GAAG,GAAG,CAAN,GAAU,CAAd,EAAiB;AACf,UAAM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E,EACpD,OAAO,CACR,CAAC;IACF,IAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IAEtC,IAAI,KAAK,GAAG,UAAU,CAAC;;IAEvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;;QAE1C,IAAM,IAAI,GACR,UAAU,CAAC,KAAK,CAAC;aAChB,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;aAC3B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;aAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;;QAEhC,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;;QAE9B,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAGD,aAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;;QAEhF,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;KACtB;;IAGD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;;;IAQM,IAAI,GAAG;IACX,MAAM,QAAA;IACN,IAAI,MAAA;IACJ,KAAK,OAAA;IACL,UAAU,YAAA;IACV,MAAM,QAAA;IACN,KAAK,OAAA;IACL,IAAI,MAAA;IACJ,IAAI,MAAA;IACJ,GAAG,SAAA;IACH,MAAM,QAAA;IACN,MAAM,QAAA;IACN,QAAQ,UAAA;IACR,QAAQ,EAAE,QAAQ;IAClB,UAAU,YAAA;IACV,UAAU,YAAA;IACV,SAAS,WAAA;IACT,KAAK,OAAA;IACL,qBAAqB,uBAAA;IACrB,SAAS,WAAA;IACT,2BAA2B,6BAAA;IAC3B,WAAW,aAAA;IACX,mBAAmB,qBAAA;IACnB,iBAAiB,mBAAA;IACjB,SAAS,WAAA;IACT,aAAa,eAAA;;;;;;"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.umd.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.umd.js deleted file mode 100644 index 0ffd1ff..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.umd.js +++ /dev/null @@ -1,7580 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BSON = {})); -}(this, (function (exports) { 'use strict'; - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var byteLength_1 = byteLength; - var toByteArray_1 = toByteArray; - var fromByteArray_1 = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } // Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - - function getLens(b64) { - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4'); - } // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - - - var validLen = b64.indexOf('='); - if (validLen === -1) validLen = len; - var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } // base64 is 4/3 + up to two characters of the original data - - - 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; // if there are placeholders, only get up to the last complete 4 chars - - var len = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i; - - for (i = 0; i < len; i += 4) { - tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; - arr[curByte++] = tmp >> 16 & 0xFF; - arr[curByte++] = tmp >> 8 & 0xFF; - arr[curByte++] = tmp & 0xFF; - } - - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; - arr[curByte++] = tmp & 0xFF; - } - - 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 & 0xFF; - arr[curByte++] = tmp & 0xFF; - } - - return arr; - } - - function tripletToBase64(num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - } - - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); - output.push(tripletToBase64(tmp)); - } - - return output.join(''); - } - - function fromByteArray(uint8) { - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); - } // pad the end with zeros, but make sure to not forget the extra bytes - - - if (extraBytes === 1) { - tmp = uint8[len - 1]; - parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); - } - - return parts.join(''); - } - - var base64Js = { - byteLength: byteLength_1, - toByteArray: toByteArray_1, - fromByteArray: fromByteArray_1 - }; - - /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - var read = function read(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 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); - }; - - var write = function write(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 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 & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = e << mLen | m; - eLen += mLen; - - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; - }; - - var ieee754 = { - read: read, - write: write - }; - - var buffer$1 = createCommonjsModule(function (module, exports) { - - var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation - Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation - : null; - exports.Buffer = Buffer; - exports.SlowBuffer = SlowBuffer; - exports.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 0x7fffffff; - exports.kMaxLength = K_MAX_LENGTH; - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ - - 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() { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1); - var proto = { - foo: function foo() { - return 42; - } - }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e) { - return false; - } - } - - Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function get() { - if (!Buffer.isBuffer(this)) return undefined; - return this.buffer; - } - }); - Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function get() { - 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"'); - } // Return an augmented `Uint8Array` instance - - - var buf = new Uint8Array(length); - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; - } - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - - function Buffer(arg, encodingOrOffset, length) { - // Common case. - 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); - } - - Buffer.poolSize = 8192; // not used by this implementation - - function from(value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset); - } - - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - - if (value == null) { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); - } - - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - - if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - 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 ' + babelHelpers["typeof"](value)); - } - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - - - Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length); - }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: - // https://github.com/feross/buffer/pull/148 - - - Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer, 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) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpreted as a start offset. - return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - - return createBuffer(size); - } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - - - Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding); - }; - - function allocUnsafe(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - - - Buffer.allocUnsafe = function (size) { - return allocUnsafe(size); - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - - - 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) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - 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 < length; i += 1) { - buf[i] = array[i] & 255; - } - - return buf; - } - - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - - return fromArrayLike(arrayView); - } - - function fromArrayBuffer(array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - - var buf; - - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array); - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length); - } // Return an augmented `Uint8Array` instance - - - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; - } - - function fromObject(obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); - - if (buf.length === 0) { - return buf; - } - - obj.copy(buf, 0, 0, len); - return buf; - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0); - } - - return fromArrayLike(obj); - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - - function checked(length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= 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) { - // eslint-disable-line eqeqeq - length = 0; - } - - return Buffer.alloc(+length); - } - - Buffer.isBuffer = function isBuffer(b) { - return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false - }; - - 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); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - - Buffer.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true; - - default: - return false; - } - }; - - Buffer.concat = function concat(list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - - if (list.length === 0) { - return Buffer.alloc(0); - } - - var i; - - if (length === undefined) { - length = 0; - - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer.from(buf).copy(buffer, pos); - } else { - Uint8Array.prototype.set.call(buffer, buf, pos); - } - } else if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - - pos += buf.length; - } - - return buffer; - }; - - function byteLength(string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length; - } - - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength; - } - - if (typeof string !== 'string') { - throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string)); - } - - var len = string.length; - var mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion - - 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; // assume utf8 - } - - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - - Buffer.byteLength = byteLength; - - function slowToString(encoding, start, end) { - var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - - if (start === undefined || start < 0) { - start = 0; - } // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - - - if (start > this.length) { - return ''; - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return ''; - } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. - - - 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; - } - } - } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) - // to detect a Buffer instance. It's not possible to use `instanceof Buffer` - // reliably in a browserify context because there could be multiple different - // copies of the 'buffer' package in use. This method works even for Buffer - // instances that were created from another copy of the `buffer` package. - // See: https://github.com/feross/buffer/issues/154 - - - 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; i < len; i += 2) { - swap(this, i, i + 1); - } - - return this; - }; - - Buffer.prototype.swap32 = function swap32() { - var len = this.length; - - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits'); - } - - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - - return this; - }; - - Buffer.prototype.swap64 = function swap64() { - var len = this.length; - - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits'); - } - - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - - return this; - }; - - Buffer.prototype.toString = function toString() { - var length = this.length; - if (length === 0) return ''; - if (arguments.length === 0) return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); - }; - - Buffer.prototype.toLocaleString = Buffer.prototype.toString; - - Buffer.prototype.equals = function equals(b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); - if (this === b) return true; - return Buffer.compare(this, b) === 0; - }; - - Buffer.prototype.inspect = function inspect() { - var str = ''; - var max = exports.INSPECT_MAX_BYTES; - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); - if (this.length > max) str += ' ... '; - return ''; - }; - - if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; - } - - 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 ' + babelHelpers["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; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - - - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1; // Normalize byteOffset - - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - - byteOffset = +byteOffset; // Coerce to Number. - - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : buffer.length - 1; - } // Normalize byteOffset: negative offsets start from the end of the buffer - - - 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; - } // Normalize val - - - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } // Finally, search either indexOf (if dir is true) or lastIndexOf - - - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1; - } - - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-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; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - - for (i = byteOffset; i >= 0; i--) { - var found = true; - - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - - if (found) return i; - } - } - - return -1; - } - - Buffer.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - - Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - - Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - - if (!length) { - length = remaining; - } else { - length = Number(length); - - if (length > remaining) { - length = remaining; - } - } - - var strLen = string.length; - - if (length > strLen / 2) { - length = strLen / 2; - } - - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i; - buf[offset + i] = parsed; - } - - return i; - } - - function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); - } - - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length); - } - - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); - } - - function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); - } - - Buffer.prototype.write = function write(string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 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': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length); - - case 'base64': - // Warning: maxLength not taken into account in base64Write - 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 base64Js.fromByteArray(buf); - } else { - return base64Js.fromByteArray(buf.slice(start, end)); - } - } - - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i = start; - - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - - break; - - case 2: - secondByte = buf[i + 1]; - - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; - - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - - break; - - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; - - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - - break; - - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; - - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray(res); - } // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - - - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); // avoid extra slice() - } // Decode in chunks to avoid "call stack size exceeded". - - - var res = ''; - var i = 0; - - while (i < len) { - res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); - } - - return res; - } - - function asciiSlice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - - return ret; - } - - function latin1Slice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - - return ret; - } - - function hexSlice(buf, start, end) { - var len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - var out = ''; - - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - - return out; - } - - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - - for (var i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - - return res; - } - - Buffer.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance - - Object.setPrototypeOf(newBuf, Buffer.prototype); - return newBuf; - }; - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - - - function checkOffset(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); - } - - Buffer.prototype.readUintLE = 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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val; - }; - - Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val; - }; - - Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset]; - }; - - Buffer.prototype.readUint16LE = 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 = 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 = 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] * 0x1000000; - }; - - Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] * 0x1000000 + (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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - mul *= 0x80; - if (val >= 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 *= 0x100)) { - val += this[offset + --i] * mul; - } - - mul *= 0x80; - 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] & 0x80)) return this[offset]; - return (0xff - 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 & 0x8000 ? val | 0xFFFF0000 : 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 & 0x8000 ? val | 0xFFFF0000 : 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 || value < min) throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) throw new RangeError('Index out of range'); - } - - Buffer.prototype.writeUintLE = 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 & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(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 i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - - Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 0xff; - return offset + 4; - }; - - Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - 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 & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - 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 & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (value < 0) value = 0xff + value + 1; - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - this[offset] = value & 0xff; - 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, 0x7fff, -0x8000); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - this[offset] = value & 0xff; - 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, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - 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); - } - - 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); - } - - 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); - }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - - - 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 < start) end = start; // Copy 0 bytes; we're done - - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions - - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds'); - } - - if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); - if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? - - if (end > this.length) end = this.length; - - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); - } - - return len; - }; // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - - - Buffer.prototype.fill = function fill(val, start, end, encoding) { - // Handle string cases: - 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') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code; - } - } - } else if (typeof val === 'number') { - val = val & 255; - } else if (typeof val === 'boolean') { - val = Number(val); - } // Invalid ranges are not set to a default, so can range check early. - - - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index'); - } - - if (end <= start) { - return this; - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - if (!val) val = 0; - var i; - - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); - var len = bytes.length; - - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this; - }; // HELPER FUNCTIONS - // ================ - - - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - - function base64clean(str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not - - str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' - - if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - - while (str.length % 4 !== 0) { - str = str + '='; - } - - return str; - } - - function utf8ToBytes(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); // is surrogate component - - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } // valid lead - - - leadSurrogate = codePoint; - continue; - } // 2 leads in a row - - - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue; - } // valid surrogate pair - - - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; // encode utf8 - - if (codePoint < 0x80) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break; - bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break; - bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break; - bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else { - throw new Error('Invalid code point'); - } - } - - return bytes; - } - - function asciiToBytes(str) { - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - - return byteArray; - } - - function utf16leToBytes(str, units) { - var c, hi, lo; - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray; - } - - function base64ToBytes(str) { - return base64Js.toByteArray(base64clean(str)); - } - - function blitBuffer(src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) break; - dst[i + offset] = src[i]; - } - - return i; - } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass - // the `instanceof` check but they should be treated as of that type. - // See: https://github.com/feross/buffer/issues/166 - - - 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) { - // For IE11 support - return obj !== obj; // eslint-disable-line no-self-compare - } // Create lookup table for `toString('hex')` - // See: https://github.com/feross/buffer/issues/219 - - - var hexSliceLookupTable = function () { - var alphabet = '0123456789abcdef'; - var table = new Array(256); - - for (var i = 0; i < 16; ++i) { - var i16 = i * 16; - - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; - } - } - - return table; - }(); - }); - var buffer_1 = buffer$1.Buffer; - buffer$1.SlowBuffer; - buffer$1.INSPECT_MAX_BYTES; - buffer$1.kMaxLength; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - - /* global Reflect, Promise */ - var _extendStatics = function extendStatics(d, b) { - _extendStatics = Object.setPrototypeOf || { - __proto__: [] - } instanceof Array && function (d, b) { - d.__proto__ = b; - } || function (d, b) { - for (var p in b) { - if (b.hasOwnProperty(p)) d[p] = b[p]; - } - }; - - return _extendStatics(d, b); - }; - - function __extends(d, b) { - _extendStatics(d, b); - - function __() { - this.constructor = d; - } - - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var _assign = function __assign() { - _assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - - for (var p in s) { - if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - } - - return t; - }; - - return _assign.apply(this, arguments); - }; - - /** @public */ - var BSONError = /** @class */ (function (_super) { - __extends(BSONError, _super); - function BSONError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONError.prototype); - return _this; - } - Object.defineProperty(BSONError.prototype, "name", { - get: function () { - return 'BSONError'; - }, - enumerable: false, - configurable: true - }); - return BSONError; - }(Error)); - /** @public */ - var BSONTypeError = /** @class */ (function (_super) { - __extends(BSONTypeError, _super); - function BSONTypeError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONTypeError.prototype); - return _this; - } - Object.defineProperty(BSONTypeError.prototype, "name", { - get: function () { - return 'BSONTypeError'; - }, - enumerable: false, - configurable: true - }); - return BSONTypeError; - }(TypeError)); - - function checkForMath(potentialGlobal) { - // eslint-disable-next-line eqeqeq - return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; - } - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - function getGlobal() { - // eslint-disable-next-line no-undef - return (checkForMath(typeof globalThis === 'object' && globalThis) || - checkForMath(typeof window === 'object' && window) || - checkForMath(typeof self === 'object' && self) || - checkForMath(typeof global === 'object' && global) || - Function('return this')()); - } - - /** - * Normalizes our expected stringified form of a function across versions of node - * @param fn - The function to stringify - */ - function normalizedFunctionString(fn) { - return fn.toString().replace('function(', 'function ('); - } - function isReactNative() { - var g = getGlobal(); - return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; - } - var insecureRandomBytes = function insecureRandomBytes(size) { - var insecureWarning = isReactNative() - ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' - : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; - console.warn(insecureWarning); - var result = buffer_1.alloc(size); - for (var i = 0; i < size; ++i) - result[i] = Math.floor(Math.random() * 256); - return result; - }; - var detectRandomBytes = function () { - if (typeof window !== 'undefined') { - // browser crypto implementation(s) - var target_1 = window.crypto || window.msCrypto; // allow for IE11 - if (target_1 && target_1.getRandomValues) { - return function (size) { return target_1.getRandomValues(buffer_1.alloc(size)); }; - } - } - if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { - // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global - return function (size) { return global.crypto.getRandomValues(buffer_1.alloc(size)); }; - } - var requiredRandomBytes; - try { - // eslint-disable-next-line @typescript-eslint/no-var-requires - requiredRandomBytes = require('crypto').randomBytes; - } - catch (e) { - // keep the fallback - } - // NOTE: in transpiled cases the above require might return null/undefined - return requiredRandomBytes || insecureRandomBytes; - }; - var randomBytes = detectRandomBytes(); - function isAnyArrayBuffer(value) { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); - } - function isUint8Array(value) { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; - } - function isBigInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigInt64Array]'; - } - function isBigUInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigUint64Array]'; - } - function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - } - function isMap(d) { - return Object.prototype.toString.call(d) === '[object Map]'; - } - // To ensure that 0.4 of node works correctly - function isDate(d) { - return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; - } - /** - * @internal - * this is to solve the `'someKey' in x` problem where x is unknown. - * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 - */ - function isObjectLike(candidate) { - return typeof candidate === 'object' && candidate !== null; - } - function deprecate(fn, message) { - var warned = false; - function deprecated() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!warned) { - console.warn(message); - warned = true; - } - return fn.apply(this, args); - } - return deprecated; - } - - /** - * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. - * - * @param potentialBuffer - The potential buffer - * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that - * wraps a passed in Uint8Array - * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in - */ - function ensureBuffer(potentialBuffer) { - if (ArrayBuffer.isView(potentialBuffer)) { - return buffer_1.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - if (isAnyArrayBuffer(potentialBuffer)) { - return buffer_1.from(potentialBuffer); - } - throw new BSONTypeError('Must use either Buffer or TypedArray'); - } - - // Validation regex for v4 uuid (validates with or without dashes) - var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; - var uuidValidateString = function (str) { - return typeof str === 'string' && VALIDATION_REGEX.test(str); - }; - var uuidHexStringToBuffer = function (hexString) { - if (!uuidValidateString(hexString)) { - throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); - } - var sanitizedHexString = hexString.replace(/-/g, ''); - return buffer_1.from(sanitizedHexString, 'hex'); - }; - var bufferToUuidHexString = function (buffer, includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - return includeDashes - ? buffer.toString('hex', 0, 4) + - '-' + - buffer.toString('hex', 4, 6) + - '-' + - buffer.toString('hex', 6, 8) + - '-' + - buffer.toString('hex', 8, 10) + - '-' + - buffer.toString('hex', 10, 16) - : buffer.toString('hex'); - }; - - var BYTE_LENGTH = 16; - var kId$1 = Symbol('id'); - /** - * A class representation of the BSON UUID type. - * @public - */ - var UUID = /** @class */ (function () { - /** - * Create an UUID type - * - * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. - */ - function UUID(input) { - if (typeof input === 'undefined') { - // The most common use case (blank id, new UUID() instance) - this.id = UUID.generate(); - } - else if (input instanceof UUID) { - this[kId$1] = buffer_1.from(input.id); - this.__id = input.__id; - } - else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { - this.id = ensureBuffer(input); - } - else if (typeof input === 'string') { - this.id = uuidHexStringToBuffer(input); - } - else { - throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); - } - } - Object.defineProperty(UUID.prototype, "id", { - /** - * The UUID bytes - * @readonly - */ - get: function () { - return this[kId$1]; - }, - set: function (value) { - this[kId$1] = value; - if (UUID.cacheHexString) { - this.__id = bufferToUuidHexString(value); - } - }, - enumerable: false, - configurable: true - }); - /** - * Generate a 16 byte uuid v4 buffer used in UUIDs - */ - /** - * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) - * @param includeDashes - should the string exclude dash-separators. - * */ - UUID.prototype.toHexString = function (includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - var uuidHexString = bufferToUuidHexString(this.id, includeDashes); - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - return uuidHexString; - }; - /** - * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. - */ - UUID.prototype.toString = function (encoding) { - return encoding ? this.id.toString(encoding) : this.toHexString(); - }; - /** - * Converts the id into its JSON string representation. - * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - */ - UUID.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this UUID with `otherID`. - * - * @param otherId - UUID instance to compare against. - */ - UUID.prototype.equals = function (otherId) { - if (!otherId) { - return false; - } - if (otherId instanceof UUID) { - return otherId.id.equals(this.id); - } - try { - return new UUID(otherId).id.equals(this.id); - } - catch (_a) { - return false; - } - }; - /** - * Creates a Binary instance from the current UUID. - */ - UUID.prototype.toBinary = function () { - return new Binary(this.id, Binary.SUBTYPE_UUID); - }; - /** - * Generates a populated buffer containing a v4 uuid - */ - UUID.generate = function () { - var bytes = randomBytes(BYTE_LENGTH); - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - return buffer_1.from(bytes); - }; - /** - * Checks if a value is a valid bson UUID - * @param input - UUID, string or Buffer to validate. - */ - UUID.isValid = function (input) { - if (!input) { - return false; - } - if (input instanceof UUID) { - return true; - } - if (typeof input === 'string') { - return uuidValidateString(input); - } - if (isUint8Array(input)) { - // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) - if (input.length !== BYTE_LENGTH) { - return false; - } - try { - // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx - // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx - return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; - } - catch (_a) { - return false; - } - } - return false; - }; - /** - * Creates an UUID from a hex string representation of an UUID. - * @param hexString - 32 or 36 character hex string (dashes excluded/included). - */ - UUID.createFromHexString = function (hexString) { - var buffer = uuidHexStringToBuffer(hexString); - return new UUID(buffer); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 36 character hex string representation. - * @internal - */ - UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - UUID.prototype.inspect = function () { - return "new UUID(\"" + this.toHexString() + "\")"; - }; - return UUID; - }()); - Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); - - /** - * A class representation of the BSON Binary type. - * @public - */ - var Binary = /** @class */ (function () { - /** - * @param buffer - a buffer object containing the binary data. - * @param subType - the option binary type. - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) - return new Binary(buffer, subType); - if (!(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer)) { - throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); - } - this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer == null) { - // create an empty binary buffer - this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE); - this.position = 0; - } - else { - if (typeof buffer === 'string') { - // string - this.buffer = buffer_1.from(buffer, 'binary'); - } - else if (Array.isArray(buffer)) { - // number[] - this.buffer = buffer_1.from(buffer); - } - else { - // Buffer | TypedArray | ArrayBuffer - this.buffer = ensureBuffer(buffer); - } - this.position = this.buffer.byteLength; - } - } - /** - * Updates this binary with byte_value. - * - * @param byteValue - a single byte we wish to write. - */ - Binary.prototype.put = function (byteValue) { - // If it's a string and a has more than one character throw an error - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new BSONTypeError('only accepts single character String'); - } - else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new BSONTypeError('only accepts single character Uint8Array or Array'); - // Decode the byte value once - var decodedByte; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } - else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } - else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); - } - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decodedByte; - } - else { - var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decodedByte; - } - }; - /** - * Writes a buffer or string to the binary. - * - * @param sequence - a string or buffer to be written to the Binary BSON object. - * @param offset - specify the binary of where to write the content. - */ - Binary.prototype.write = function (sequence, offset) { - offset = typeof offset === 'number' ? offset : this.position; - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + sequence.length) { - var buffer = buffer_1.alloc(this.buffer.length + sequence.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - // Assign the new buffer - this.buffer = buffer; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ensureBuffer(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } - else if (typeof sequence === 'string') { - this.buffer.write(sequence, offset, sequence.length, 'binary'); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - }; - /** - * Reads **length** bytes starting at **position**. - * - * @param position - read from the given position in the Binary. - * @param length - the number of bytes to read. - */ - Binary.prototype.read = function (position, length) { - length = length && length > 0 ? length : this.position; - // Let's return the data based on the type we have - return this.buffer.slice(position, position + length); - }; - /** - * Returns the value of this binary as a string. - * @param asRaw - Will skip converting to a string - * @remarks - * This is handy when calling this function conditionally for some key value pairs and not others - */ - Binary.prototype.value = function (asRaw) { - asRaw = !!asRaw; - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - // If it's a node.js buffer object - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return this.buffer.toString('binary', 0, this.position); - }; - /** the length of the binary sequence */ - Binary.prototype.length = function () { - return this.position; - }; - Binary.prototype.toJSON = function () { - return this.buffer.toString('base64'); - }; - Binary.prototype.toString = function (format) { - return this.buffer.toString(format); - }; - /** @internal */ - Binary.prototype.toExtendedJSON = function (options) { - options = options || {}; - var base64String = this.buffer.toString('base64'); - var subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - }; - Binary.prototype.toUUID = function () { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID(this.buffer.slice(0, this.position)); - } - throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); - }; - /** @internal */ - Binary.fromExtendedJSON = function (doc, options) { - options = options || {}; - var data; - var type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = buffer_1.from(doc.$binary, 'base64'); - } - else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = buffer_1.from(doc.$binary.base64, 'base64'); - } - } - } - else if ('$uuid' in doc) { - type = 4; - data = uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); - } - return new Binary(data, type); - }; - /** @internal */ - Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Binary.prototype.inspect = function () { - var asBuffer = this.value(true); - return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; - }; - /** - * Binary default subtype - * @internal - */ - Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** Initial buffer default size */ - Binary.BUFFER_SIZE = 256; - /** Default BSON type */ - Binary.SUBTYPE_DEFAULT = 0; - /** Function BSON type */ - Binary.SUBTYPE_FUNCTION = 1; - /** Byte Array BSON type */ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ - Binary.SUBTYPE_UUID_OLD = 3; - /** UUID BSON type */ - Binary.SUBTYPE_UUID = 4; - /** MD5 BSON type */ - Binary.SUBTYPE_MD5 = 5; - /** Encrypted BSON type */ - Binary.SUBTYPE_ENCRYPTED = 6; - /** Column BSON type */ - Binary.SUBTYPE_COLUMN = 7; - /** User BSON type */ - Binary.SUBTYPE_USER_DEFINED = 128; - return Binary; - }()); - Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); - - /** - * A class representation of the BSON Code type. - * @public - */ - var Code = /** @class */ (function () { - /** - * @param code - a string or function. - * @param scope - an optional scope for the function. - */ - function Code(code, scope) { - if (!(this instanceof Code)) - return new Code(code, scope); - this.code = code; - this.scope = scope; - } - Code.prototype.toJSON = function () { - return { code: this.code, scope: this.scope }; - }; - /** @internal */ - Code.prototype.toExtendedJSON = function () { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - }; - /** @internal */ - Code.fromExtendedJSON = function (doc) { - return new Code(doc.$code, doc.$scope); - }; - /** @internal */ - Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Code.prototype.inspect = function () { - var codeJson = this.toJSON(); - return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; - }; - return Code; - }()); - Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); - - /** @internal */ - function isDBRefLike(value) { - return (isObjectLike(value) && - value.$id != null && - typeof value.$ref === 'string' && - (value.$db == null || typeof value.$db === 'string')); - } - /** - * A class representation of the BSON DBRef type. - * @public - */ - var DBRef = /** @class */ (function () { - /** - * @param collection - the collection name. - * @param oid - the reference ObjectId. - * @param db - optional db name, if omitted the reference is local to the current db. - */ - function DBRef(collection, oid, db, fields) { - if (!(this instanceof DBRef)) - return new DBRef(collection, oid, db, fields); - // check if namespace has been provided - var parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - Object.defineProperty(DBRef.prototype, "namespace", { - // Property provided for compatibility with the 1.x parser - // the 1.x parser used a "namespace" property, while 4.x uses "collection" - /** @internal */ - get: function () { - return this.collection; - }, - set: function (value) { - this.collection = value; - }, - enumerable: false, - configurable: true - }); - DBRef.prototype.toJSON = function () { - var o = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o.$db = this.db; - return o; - }; - /** @internal */ - DBRef.prototype.toExtendedJSON = function (options) { - options = options || {}; - var o = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o; - } - if (this.db) - o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - }; - /** @internal */ - DBRef.fromExtendedJSON = function (doc) { - var copy = Object.assign({}, doc); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - }; - /** @internal */ - DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - DBRef.prototype.inspect = function () { - // NOTE: if OID is an ObjectId class it will just print the oid string. - var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; - }; - return DBRef; - }()); - Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); - - /** - * wasm optimizations, to do native i64 multiplication and divide - */ - var wasm = undefined; - try { - wasm = new WebAssembly.Instance(new WebAssembly.Module( - // prettier-ignore - new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; - } - catch (_a) { - // no wasm support - } - var TWO_PWR_16_DBL = 1 << 16; - var TWO_PWR_24_DBL = 1 << 24; - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - /** A cache of the Long representations of small integer values. */ - var INT_CACHE = {}; - /** A cache of the Long representations of small unsigned integer values. */ - var UINT_CACHE = {}; - /** - * A class representing a 64-bit integer - * @public - * @remarks - * The internal representation of a long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16 bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. - */ - var Long = /** @class */ (function () { - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * - * Acceptable signatures are: - * - Long(low, high, unsigned?) - * - Long(bigint, unsigned?) - * - Long(string, unsigned?) - * - * @param low - The low (signed) 32 bits of the long - * @param high - The high (signed) 32 bits of the long - * @param unsigned - Whether unsigned or not, defaults to signed - */ - function Long(low, high, unsigned) { - if (low === void 0) { low = 0; } - if (!(this instanceof Long)) - return new Long(low, high, unsigned); - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } - else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } - else { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - Object.defineProperty(this, '__isLong__', { - value: true, - configurable: false, - writable: false, - enumerable: false - }); - } - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. - * Each is assumed to use 32 bits. - * @param lowBits - The low 32 bits - * @param highBits - The high 32 bits - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBits = function (lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - }; - /** - * Returns a Long representing the given 32 bit integer value. - * @param value - The 32 bit integer in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromInt = function (value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } - else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromNumber = function (value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } - else { - if (value <= -TWO_PWR_63_DBL) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; - } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBigInt = function (value, unsigned) { - return Long.fromString(value.toString(), unsigned); - }; - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param str - The textual representation of the Long - * @param unsigned - Whether unsigned or not, defaults to signed - * @param radix - The radix in which the text is written (2-36), defaults to 10 - * @returns The corresponding Long value - */ - Long.fromString = function (str, unsigned, radix) { - if (str.length === 0) - throw Error('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - (radix = unsigned), (unsigned = false); - } - else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - var p; - if ((p = str.indexOf('-')) > 0) - throw Error('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } - else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - }; - /** - * Creates a Long from its byte representation. - * @param bytes - Byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @param le - Whether little or big endian, defaults to big endian - * @returns The corresponding Long value - */ - Long.fromBytes = function (bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - }; - /** - * Creates a Long from its little endian byte representation. - * @param bytes - Little endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesLE = function (bytes, unsigned) { - return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); - }; - /** - * Creates a Long from its big endian byte representation. - * @param bytes - Big endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesBE = function (bytes, unsigned) { - return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); - }; - /** - * Tests if the specified object is a Long. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Long.isLong = function (value) { - return isObjectLike(value) && value['__isLong__'] === true; - }; - /** - * Converts the specified value to a Long. - * @param unsigned - Whether unsigned or not, defaults to signed - */ - Long.fromValue = function (val, unsigned) { - if (typeof val === 'number') - return Long.fromNumber(val, unsigned); - if (typeof val === 'string') - return Long.fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); - }; - /** Returns the sum of this and the specified Long. */ - Long.prototype.add = function (addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** - * Returns the sum of this and the specified Long. - * @returns Sum - */ - Long.prototype.and = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - /** - * Compares this Long's value with the specified's. - * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater - */ - Long.prototype.compare = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - // At this point the sign bits are the same - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; - /** This is an alias of {@link Long.compare} */ - Long.prototype.comp = function (other) { - return this.compare(other); - }; - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. - * @returns Quotient - */ - Long.prototype.divide = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw Error('division by zero'); - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if (!this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } - else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } - else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } - else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } - else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return Long.UONE; - res = Long.UZERO; - } - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - /**This is an alias of {@link Long.divide} */ - Long.prototype.div = function (divisor) { - return this.divide(divisor); - }; - /** - * Tests if this Long's value equals the specified's. - * @param other - Other value - */ - Long.prototype.equals = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - /** This is an alias of {@link Long.equals} */ - Long.prototype.eq = function (other) { - return this.equals(other); - }; - /** Gets the high 32 bits as a signed integer. */ - Long.prototype.getHighBits = function () { - return this.high; - }; - /** Gets the high 32 bits as an unsigned integer. */ - Long.prototype.getHighBitsUnsigned = function () { - return this.high >>> 0; - }; - /** Gets the low 32 bits as a signed integer. */ - Long.prototype.getLowBits = function () { - return this.low; - }; - /** Gets the low 32 bits as an unsigned integer. */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low >>> 0; - }; - /** Gets the number of bits needed to represent the absolute value of this Long. */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - // Unsigned Longs are never negative - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - var val = this.high !== 0 ? this.high : this.low; - var bit; - for (bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - }; - /** Tests if this Long's value is greater than the specified's. */ - Long.prototype.greaterThan = function (other) { - return this.comp(other) > 0; - }; - /** This is an alias of {@link Long.greaterThan} */ - Long.prototype.gt = function (other) { - return this.greaterThan(other); - }; - /** Tests if this Long's value is greater than or equal the specified's. */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.comp(other) >= 0; - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.gte = function (other) { - return this.greaterThanOrEqual(other); - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.ge = function (other) { - return this.greaterThanOrEqual(other); - }; - /** Tests if this Long's value is even. */ - Long.prototype.isEven = function () { - return (this.low & 1) === 0; - }; - /** Tests if this Long's value is negative. */ - Long.prototype.isNegative = function () { - return !this.unsigned && this.high < 0; - }; - /** Tests if this Long's value is odd. */ - Long.prototype.isOdd = function () { - return (this.low & 1) === 1; - }; - /** Tests if this Long's value is positive. */ - Long.prototype.isPositive = function () { - return this.unsigned || this.high >= 0; - }; - /** Tests if this Long's value equals zero. */ - Long.prototype.isZero = function () { - return this.high === 0 && this.low === 0; - }; - /** Tests if this Long's value is less than the specified's. */ - Long.prototype.lessThan = function (other) { - return this.comp(other) < 0; - }; - /** This is an alias of {@link Long#lessThan}. */ - Long.prototype.lt = function (other) { - return this.lessThan(other); - }; - /** Tests if this Long's value is less than or equal the specified's. */ - Long.prototype.lessThanOrEqual = function (other) { - return this.comp(other) <= 0; - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.lte = function (other) { - return this.lessThanOrEqual(other); - }; - /** Returns this Long modulo the specified. */ - Long.prototype.modulo = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.mod = function (divisor) { - return this.modulo(divisor); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.rem = function (divisor) { - return this.modulo(divisor); - }; - /** - * Returns the product of this and the specified Long. - * @param multiplier - Multiplier - * @returns Product - */ - Long.prototype.multiply = function (multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - // use wasm support if present - if (wasm) { - var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } - else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - // If both longs are small, use float multiplication - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** This is an alias of {@link Long.multiply} */ - Long.prototype.mul = function (multiplier) { - return this.multiply(multiplier); - }; - /** Returns the Negation of this Long's value. */ - Long.prototype.negate = function () { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); - }; - /** This is an alias of {@link Long.negate} */ - Long.prototype.neg = function () { - return this.negate(); - }; - /** Returns the bitwise NOT of this Long. */ - Long.prototype.not = function () { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - }; - /** Tests if this Long's value differs from the specified's. */ - Long.prototype.notEquals = function (other) { - return !this.equals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.neq = function (other) { - return this.notEquals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.ne = function (other) { - return this.notEquals(other); - }; - /** - * Returns the bitwise OR of this Long and the specified. - */ - Long.prototype.or = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftLeft = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - }; - /** This is an alias of {@link Long.shiftLeft} */ - Long.prototype.shl = function (numBits) { - return this.shiftLeft(numBits); - }; - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRight = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - }; - /** This is an alias of {@link Long.shiftRight} */ - Long.prototype.shr = function (numBits) { - return this.shiftRight(numBits); - }; - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } - else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shr_u = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shru = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** - * Returns the difference of this and the specified Long. - * @param subtrahend - Subtrahend - * @returns Difference - */ - Long.prototype.subtract = function (subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - /** This is an alias of {@link Long.subtract} */ - Long.prototype.sub = function (subtrahend) { - return this.subtract(subtrahend); - }; - /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ - Long.prototype.toInt = function () { - return this.unsigned ? this.low >>> 0 : this.low; - }; - /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ - Long.prototype.toNumber = function () { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - /** Converts the Long to a BigInt (arbitrary precision). */ - Long.prototype.toBigInt = function () { - return BigInt(this.toString()); - }; - /** - * Converts this Long to its byte representation. - * @param le - Whether little or big endian, defaults to big endian - * @returns Byte representation - */ - Long.prototype.toBytes = function (le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - /** - * Converts this Long to its little endian byte representation. - * @returns Little endian byte representation - */ - Long.prototype.toBytesLE = function () { - var hi = this.high, lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - }; - /** - * Converts this Long to its big endian byte representation. - * @returns Big endian byte representation - */ - Long.prototype.toBytesBE = function () { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - }; - /** - * Converts this Long to signed. - */ - Long.prototype.toSigned = function () { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); - }; - /** - * Converts the Long to a string written in the specified radix. - * @param radix - Radix (2-36), defaults to 10 - * @throws RangeError If `radix` is out of range - */ - Long.prototype.toString = function (radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } - else - return '-' + this.neg().toString(radix); - } - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - // eslint-disable-next-line @typescript-eslint/no-this-alias - var rem = this; - var result = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - var digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - }; - /** Converts this Long to unsigned. */ - Long.prototype.toUnsigned = function () { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - }; - /** Returns the bitwise XOR of this Long and the given one. */ - Long.prototype.xor = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - /** This is an alias of {@link Long.isZero} */ - Long.prototype.eqz = function () { - return this.isZero(); - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.le = function (other) { - return this.lessThanOrEqual(other); - }; - /* - **************************************************************** - * BSON SPECIFIC ADDITIONS * - **************************************************************** - */ - Long.prototype.toExtendedJSON = function (options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; - }; - Long.fromExtendedJSON = function (doc, options) { - var result = Long.fromString(doc.$numberLong); - return options && options.relaxed ? result.toNumber() : result; - }; - /** @internal */ - Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Long.prototype.inspect = function () { - return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; - }; - Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); - /** Maximum unsigned value. */ - Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); - /** Signed zero */ - Long.ZERO = Long.fromInt(0); - /** Unsigned zero. */ - Long.UZERO = Long.fromInt(0, true); - /** Signed one. */ - Long.ONE = Long.fromInt(1); - /** Unsigned one. */ - Long.UONE = Long.fromInt(1, true); - /** Signed negative one. */ - Long.NEG_ONE = Long.fromInt(-1); - /** Maximum signed value. */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - /** Minimum signed value. */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - return Long; - }()); - Object.defineProperty(Long.prototype, '__isLong__', { value: true }); - Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); - - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - ].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - ].reverse(); - var INF_POSITIVE_BUFFER = [ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - ].reverse(); - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Detect if the value is a digit - function isDigit(value) { - return !isNaN(parseInt(value, 10)); - } - // Divide two uint128 values - function divideu128(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (var i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - return { quotient: value, rem: _rem }; - } - // Multiply two Long values and return the 128 bit value - function multiply64x2(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - // Return the 128 bit result - return { high: productHigh, low: productLow }; - } - function lessThan(left, right) { - // Make values unsigned - var uhleft = left.high >>> 0; - var uhright = right.high >>> 0; - // Compare high bits first - if (uhleft < uhright) { - return true; - } - else if (uhleft === uhright) { - var ulleft = left.low >>> 0; - var ulright = right.low >>> 0; - if (ulleft < ulright) - return true; - } - return false; - } - function invalidErr(string, message) { - throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); - } - /** - * A class representation of the BSON Decimal128 type. - * @public - */ - var Decimal128 = /** @class */ (function () { - /** - * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, - * or a string representation as returned by .toString() - */ - function Decimal128(bytes) { - if (!(this instanceof Decimal128)) - return new Decimal128(bytes); - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } - else { - this.bytes = bytes; - } - } - /** - * Create a Decimal128 instance from a string representation - * - * @param representation - a numeric string representation. - */ - Decimal128.fromString = function (representation) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = new Long(0, 0); - // The low 17 digits of the significand - var significandLow = new Long(0, 0); - // The biased exponent - var biasedExponent = 0; - // Read index - var index = 0; - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (representation.length >= 7000) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - // Results - var stringMatch = representation.match(PARSE_STRING_REGEXP); - var infMatch = representation.match(PARSE_INF_REGEXP); - var nanMatch = representation.match(PARSE_NAN_REGEXP); - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - if (stringMatch) { - // full_match = stringMatch[0] - // sign = stringMatch[1] - var unsignedNumber = stringMatch[2]; - // stringMatch[3] is undefined if a whole number (ex "1", 12") - // but defined if a number w/ decimal in it (ex "1.0, 12.2") - var e = stringMatch[4]; - var expSign = stringMatch[5]; - var expNumber = stringMatch[6]; - // they provided e, but didn't give an exponent number. for ex "1e" - if (e && expNumber === undefined) - invalidErr(representation, 'missing exponent power'); - // they provided e, but didn't give a number before it. for ex "e1" - if (e && unsignedNumber === undefined) - invalidErr(representation, 'missing exponent base'); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - // Get the negative or positive sign - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - // Check if user passed Infinity or NaN - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - else if (representation[index] === 'N') { - return new Decimal128(buffer_1.from(NAN_BUFFER)); - } - } - // Read all the digits - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) - invalidErr(representation, 'contains multiple periods'); - sawRadix = true; - index = index + 1; - continue; - } - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - // Only store 34 digits - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - if (sawRadix && !nDigitsRead) - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - // Read exponent if exists - if (representation[index] === 'e' || representation[index] === 'E') { - // Read exponent digits - var match = representation.substr(++index).match(EXPONENT_REGEX); - // No digits read - if (!match || !match[2]) - return new Decimal128(buffer_1.from(NAN_BUFFER)); - // Get exponent - exponent = parseInt(match[0], 10); - // Adjust the index - index = index + match[0].length; - } - // Return not a number - if (representation[index]) - return new Decimal128(buffer_1.from(NAN_BUFFER)); - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } - else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } - else { - exponent = exponent - radixPosition; - } - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit. can only do this if < significant digits than # stored. - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } - else { - // adjust to round - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } - else { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits) { - var endOfString = nDigitsRead; - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - // if negative, we need to increment again to account for - sign at start. - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - var dIdx = lastDigit; - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } - else { - return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - } - } - } - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } - else if (lastDigit - firstDigit < 17) { - var dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - else { - var dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - significandLow = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } - else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - dec.low = significand.low; - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - // Encode into a buffer - var buffer = buffer_1.alloc(16); - index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - // Return the new Decimal128 - return new Decimal128(buffer); - }; - /** Create a string representation of the raw Decimal128 value */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) - significand[i] = 0; - // read pointer into significand - var index = 0; - // true if the number is zero - var is_zero = false; - // the most significant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: [0, 0, 0, 0] }; - // indexing variables - var j, k; - // Output string - var string = []; - // Unpack index - index = 0; - // Buffer reference - var buffer = this.bytes; - // Unpack the low 64bits into a long - // bits 96 - 127 - var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 64 - 95 - var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack the high 64bits into a long - // bits 32 - 63 - var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 0 - 31 - var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack index - index = 0; - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - // Decode combination field and exponent - // bits 1 - 5 - var combination = (high >> 26) & COMBINATION_MASK; - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } - else if (combination === COMBINATION_NAN) { - return 'NaN'; - } - else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } - else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - // unbiased exponent - var exponent = biased_exponent - EXPONENT_BIAS; - // Create string of significand digits - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0) { - is_zero = true; - } - else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Perform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) - continue; - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } - else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - // the exponent if scientific notation is used - var scientific_exponent = significand_digits - 1 + exponent; - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - // if there are too many significant digits, we should just be treating numbers - // as + or - 0 and using the non-scientific exponent (this is for the "invalid - // representation should be treated as 0/-0" spec cases in decimal128-1.json) - if (significand_digits > 34) { - string.push("" + 0); - if (exponent > 0) - string.push('E+' + exponent); - else if (exponent < 0) - string.push('E' + exponent); - return string.join(''); - } - string.push("" + significand[index++]); - significand_digits = significand_digits - 1; - if (significand_digits) { - string.push('.'); - } - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } - else { - string.push("" + scientific_exponent); - } - } - else { - // Regular format with no decimal place - if (exponent >= 0) { - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - } - else { - var radix_position = significand_digits + exponent; - // non-zero digits before radix - if (radix_position > 0) { - for (var i = 0; i < radix_position; i++) { - string.push("" + significand[index++]); - } - } - else { - string.push('0'); - } - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push("" + significand[index++]); - } - } - } - return string.join(''); - }; - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.prototype.toExtendedJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.fromExtendedJSON = function (doc) { - return Decimal128.fromString(doc.$numberDecimal); - }; - /** @internal */ - Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Decimal128.prototype.inspect = function () { - return "new Decimal128(\"" + this.toString() + "\")"; - }; - return Decimal128; - }()); - Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); - - /** - * A class representation of the BSON Double type. - * @public - */ - var Double = /** @class */ (function () { - /** - * Create a Double type - * - * @param value - the number we want to represent as a double. - */ - function Double(value) { - if (!(this instanceof Double)) - return new Double(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; - } - /** - * Access the number value. - * - * @returns returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - Double.prototype.toJSON = function () { - return this.value; - }; - Double.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - /** @internal */ - Double.prototype.toExtendedJSON = function (options) { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user - // explicitly provided `-0` then we need to ensure the sign makes it into the output - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: "-" + this.value.toFixed(1) }; - } - var $numberDouble; - if (Number.isInteger(this.value)) { - $numberDouble = this.value.toFixed(1); - if ($numberDouble.length >= 13) { - $numberDouble = this.value.toExponential(13).toUpperCase(); - } - } - else { - $numberDouble = this.value.toString(); - } - return { $numberDouble: $numberDouble }; - }; - /** @internal */ - Double.fromExtendedJSON = function (doc, options) { - var doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - }; - /** @internal */ - Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Double.prototype.inspect = function () { - var eJSON = this.toExtendedJSON(); - return "new Double(" + eJSON.$numberDouble + ")"; - }; - return Double; - }()); - Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); - - /** - * A class representation of a BSON Int32 type. - * @public - */ - var Int32 = /** @class */ (function () { - /** - * Create an Int32 type - * - * @param value - the number we want to represent as an int32. - */ - function Int32(value) { - if (!(this instanceof Int32)) - return new Int32(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value | 0; - } - /** - * Access the number value. - * - * @returns returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - Int32.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - Int32.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - Int32.prototype.toExtendedJSON = function (options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; - }; - /** @internal */ - Int32.fromExtendedJSON = function (doc, options) { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - }; - /** @internal */ - Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Int32.prototype.inspect = function () { - return "new Int32(" + this.valueOf() + ")"; - }; - return Int32; - }()); - Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); - - /** - * A class representation of the BSON MaxKey type. - * @public - */ - var MaxKey = /** @class */ (function () { - function MaxKey() { - if (!(this instanceof MaxKey)) - return new MaxKey(); - } - /** @internal */ - MaxKey.prototype.toExtendedJSON = function () { - return { $maxKey: 1 }; - }; - /** @internal */ - MaxKey.fromExtendedJSON = function () { - return new MaxKey(); - }; - /** @internal */ - MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MaxKey.prototype.inspect = function () { - return 'new MaxKey()'; - }; - return MaxKey; - }()); - Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); - - /** - * A class representation of the BSON MinKey type. - * @public - */ - var MinKey = /** @class */ (function () { - function MinKey() { - if (!(this instanceof MinKey)) - return new MinKey(); - } - /** @internal */ - MinKey.prototype.toExtendedJSON = function () { - return { $minKey: 1 }; - }; - /** @internal */ - MinKey.fromExtendedJSON = function () { - return new MinKey(); - }; - /** @internal */ - MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MinKey.prototype.inspect = function () { - return 'new MinKey()'; - }; - return MinKey; - }()); - Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); - - // Regular expression that checks for hex value - var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - // Unique sequence for the current process (initialized on first use) - var PROCESS_UNIQUE = null; - var kId = Symbol('id'); - /** - * A class representation of the BSON ObjectId type. - * @public - */ - var ObjectId = /** @class */ (function () { - /** - * Create an ObjectId type - * - * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. - */ - function ObjectId(inputId) { - if (!(this instanceof ObjectId)) - return new ObjectId(inputId); - // workingId is set based on type of input and whether valid id exists for the input - var workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer'); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = buffer_1.from(inputId.toHexString(), 'hex'); - } - else { - workingId = inputId.id; - } - } - else { - workingId = inputId; - } - // the following cases use workingId to construct an ObjectId - if (workingId == null || typeof workingId === 'number') { - // The most common use case (blank id, new objectId instance) - // Generate a new id - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } - else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ensureBuffer(workingId); - } - else if (typeof workingId === 'string') { - if (workingId.length === 12) { - var bytes = buffer_1.from(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes'); - } - } - else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = buffer_1.from(workingId, 'hex'); - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters'); - } - } - else { - throw new BSONTypeError('Argument passed in does not match the accepted types'); - } - // If we are caching the hex string - if (ObjectId.cacheHexString) { - this.__id = this.id.toString('hex'); - } - } - Object.defineProperty(ObjectId.prototype, "id", { - /** - * The ObjectId bytes - * @readonly - */ - get: function () { - return this[kId]; - }, - set: function (value) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = value.toString('hex'); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectId.prototype, "generationTime", { - /** - * The generation time of this ObjectId instance - * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch - */ - get: function () { - return this.id.readInt32BE(0); - }, - set: function (value) { - // Encode time into first 4 bytes - this.id.writeUInt32BE(value, 0); - }, - enumerable: false, - configurable: true - }); - /** Returns the ObjectId id as a 24 character hex string representation */ - ObjectId.prototype.toHexString = function () { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - var hexString = this.id.toString('hex'); - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - return hexString; - }; - /** - * Update the ObjectId index - * @privateRemarks - * Used in generating new ObjectId's on the driver - * @internal - */ - ObjectId.getInc = function () { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - }; - /** - * Generate a 12 byte id buffer used in ObjectId's - * - * @param time - pass in a second based timestamp. - */ - ObjectId.generate = function (time) { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - var inc = ObjectId.getInc(); - var buffer = buffer_1.alloc(12); - // 4-byte timestamp - buffer.writeUInt32BE(time, 0); - // set PROCESS_UNIQUE if yet not initialized - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = randomBytes(5); - } - // 5-byte process unique - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - // 3-byte counter - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - return buffer; - }; - /** - * Converts the id into a 24 character hex string for printing - * - * @param format - The Buffer toString format parameter. - */ - ObjectId.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (format) - return this.id.toString(format); - return this.toHexString(); - }; - /** Converts to its JSON the 24 character hex string representation. */ - ObjectId.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this ObjectId with `otherID`. - * - * @param otherId - ObjectId instance to compare against. - */ - ObjectId.prototype.equals = function (otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (otherId instanceof ObjectId) { - return this.toString() === otherId.toString(); - } - if (typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - isUint8Array(this.id)) { - return otherId === buffer_1.prototype.toString.call(this.id, 'latin1'); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return buffer_1.from(otherId).equals(this.id); - } - if (typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function') { - return otherId.toHexString() === this.toHexString(); - } - return false; - }; - /** Returns the generation date (accurate up to the second) that this ID was generated. */ - ObjectId.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id.readUInt32BE(0); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - /** @internal */ - ObjectId.createPk = function () { - return new ObjectId(); - }; - /** - * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. - * - * @param time - an integer number representing a number of seconds. - */ - ObjectId.createFromTime = function (time) { - var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer.writeUInt32BE(time, 0); - // Return the new objectId - return new ObjectId(buffer); - }; - /** - * Creates an ObjectId from a hex string representation of an ObjectId. - * - * @param hexString - create a ObjectId from a passed in 24 character hexstring. - */ - ObjectId.createFromHexString = function (hexString) { - // Throw an error if it's not a valid setup - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - return new ObjectId(buffer_1.from(hexString, 'hex')); - }; - /** - * Checks if a value is a valid bson ObjectId - * - * @param id - ObjectId instance to validate. - */ - ObjectId.isValid = function (id) { - if (id == null) - return false; - if (typeof id === 'number') { - return true; - } - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - if (id instanceof ObjectId) { - return true; - } - if (isUint8Array(id) && id.length === 12) { - return true; - } - // Duck-Typing detection of ObjectId like objects - if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { - if (typeof id.id === 'string') { - return id.id.length === 12; - } - return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); - } - return false; - }; - /** @internal */ - ObjectId.prototype.toExtendedJSON = function () { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - }; - /** @internal */ - ObjectId.fromExtendedJSON = function (doc) { - return new ObjectId(doc.$oid); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 24 character hex string representation. - * @internal - */ - ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - ObjectId.prototype.inspect = function () { - return "new ObjectId(\"" + this.toHexString() + "\")"; - }; - /** @internal */ - ObjectId.index = Math.floor(Math.random() * 0xffffff); - return ObjectId; - }()); - // Deprecated methods - Object.defineProperty(ObjectId.prototype, 'generate', { - value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') - }); - Object.defineProperty(ObjectId.prototype, 'getInc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') - }); - Object.defineProperty(ObjectId.prototype, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') - }); - Object.defineProperty(ObjectId, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') - }); - Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); - - function alphabetize(str) { - return str.split('').sort().join(''); - } - /** - * A class representation of the BSON RegExp type. - * @public - */ - var BSONRegExp = /** @class */ (function () { - /** - * @param pattern - The regular expression pattern to match - * @param options - The regular expression options - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) - return new BSONRegExp(pattern, options); - this.pattern = pattern; - this.options = alphabetize(options !== null && options !== void 0 ? options : ''); - if (this.pattern.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); - } - if (this.options.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); - } - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u')) { - throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); - } - } - } - BSONRegExp.parseOptions = function (options) { - return options ? options.split('').sort().join('') : ''; - }; - /** @internal */ - BSONRegExp.prototype.toExtendedJSON = function (options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - }; - /** @internal */ - BSONRegExp.fromExtendedJSON = function (doc) { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - // This is for $regex query operators that have extended json values. - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc; - } - } - else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); - } - throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); - }; - return BSONRegExp; - }()); - Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); - - /** - * A class representation of the BSON Symbol type. - * @public - */ - var BSONSymbol = /** @class */ (function () { - /** - * @param value - the string representing the symbol. - */ - function BSONSymbol(value) { - if (!(this instanceof BSONSymbol)) - return new BSONSymbol(value); - this.value = value; - } - /** Access the wrapped string value. */ - BSONSymbol.prototype.valueOf = function () { - return this.value; - }; - BSONSymbol.prototype.toString = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.inspect = function () { - return "new BSONSymbol(\"" + this.value + "\")"; - }; - BSONSymbol.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.toExtendedJSON = function () { - return { $symbol: this.value }; - }; - /** @internal */ - BSONSymbol.fromExtendedJSON = function (doc) { - return new BSONSymbol(doc.$symbol); - }; - /** @internal */ - BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - return BSONSymbol; - }()); - Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); - - /** @public */ - var LongWithoutOverridesClass = Long; - /** @public */ - var Timestamp = /** @class */ (function (_super) { - __extends(Timestamp, _super); - function Timestamp(low, high) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - ///@ts-expect-error - if (!(_this instanceof Timestamp)) - return new Timestamp(low, high); - if (Long.isLong(low)) { - _this = _super.call(this, low.low, low.high, true) || this; - } - else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { - _this = _super.call(this, low.i, low.t, true) || this; - } - else { - _this = _super.call(this, low, high, true) || this; - } - Object.defineProperty(_this, '_bsontype', { - value: 'Timestamp', - writable: false, - configurable: false, - enumerable: false - }); - return _this; - } - Timestamp.prototype.toJSON = function () { - return { - $timestamp: this.toString() - }; - }; - /** Returns a Timestamp represented by the given (32-bit) integer value. */ - Timestamp.fromInt = function (value) { - return new Timestamp(Long.fromInt(value, true)); - }; - /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ - Timestamp.fromNumber = function (value) { - return new Timestamp(Long.fromNumber(value, true)); - }; - /** - * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. - * - * @param lowBits - the low 32-bits. - * @param highBits - the high 32-bits. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - /** - * Returns a Timestamp from the given string, optionally using the given radix. - * - * @param str - the textual representation of the Timestamp. - * @param optRadix - the radix in which the text is written. - */ - Timestamp.fromString = function (str, optRadix) { - return new Timestamp(Long.fromString(str, true, optRadix)); - }; - /** @internal */ - Timestamp.prototype.toExtendedJSON = function () { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - }; - /** @internal */ - Timestamp.fromExtendedJSON = function (doc) { - return new Timestamp(doc.$timestamp); - }; - /** @internal */ - Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Timestamp.prototype.inspect = function () { - return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; - }; - Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - return Timestamp; - }(LongWithoutOverridesClass)); - - function isBSONType(value) { - return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); - } - // INT32 boundaries - var BSON_INT32_MAX$1 = 0x7fffffff; - var BSON_INT32_MIN$1 = -0x80000000; - // INT64 boundaries - var BSON_INT64_MAX$1 = 0x7fffffffffffffff; - var BSON_INT64_MIN$1 = -0x8000000000000000; - // all the types where we don't need to do any special processing and can just pass the EJSON - //straight to type.fromExtendedJSON - var keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp - }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function deserializeValue(value, options) { - if (options === void 0) { options = {}; } - if (typeof value === 'number') { - if (options.relaxed || options.legacy) { - return value; - } - // if it's an integer, should interpret as smallest BSON integer - // that can represent it exactly. (if out of range, interpret as double.) - if (Math.floor(value) === value) { - if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) - return new Int32(value); - if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) - return Long.fromNumber(value); - } - // If the number is a non-integer or out of integer range, should interpret as BSON Double. - return new Double(value); - } - // from here on out we're looking for bson types, so bail if its not an object - if (value == null || typeof value !== 'object') - return value; - // upgrade deprecated undefined to null - if (value.$undefined) - return null; - var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); - for (var i = 0; i < keys.length; i++) { - var c = keysToCodecs[keys[i]]; - if (c) - return c.fromExtendedJSON(value, options); - } - if (value.$date != null) { - var d = value.$date; - var date = new Date(); - if (options.legacy) { - if (typeof d === 'number') - date.setTime(d); - else if (typeof d === 'string') - date.setTime(Date.parse(d)); - } - else { - if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (Long.isLong(d)) - date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) - date.setTime(d); - } - return date; - } - if (value.$code != null) { - var copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return Code.fromExtendedJSON(value); - } - if (isDBRefLike(value) || value.$dbPointer) { - var v = value.$ref ? value : value.$dbPointer; - // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) - // because of the order JSON.parse goes through the document - if (v instanceof DBRef) - return v; - var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); - var valid_1 = true; - dollarKeys.forEach(function (k) { - if (['$ref', '$id', '$db'].indexOf(k) === -1) - valid_1 = false; - }); - // only make DBRef if $ keys are all valid - if (valid_1) - return DBRef.fromExtendedJSON(v); - } - return value; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function serializeArray(array, options) { - return array.map(function (v, index) { - options.seenObjects.push({ propertyName: "index " + index, obj: null }); - try { - return serializeValue(v, options); - } - finally { - options.seenObjects.pop(); - } - }); - } - function getISOString(date) { - var isoStr = date.toISOString(); - // we should only show milliseconds in timestamp if they're non-zero - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function serializeValue(value, options) { - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); - if (index !== -1) { - var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); - var leadingPart = props - .slice(0, index) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var alreadySeen = props[index]; - var circularPart = ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var current = props[props.length - 1]; - var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new BSONTypeError('Converting circular structure to EJSON:\n' + - (" " + leadingPart + alreadySeen + circularPart + current + "\n") + - (" " + leadingSpace + "\\" + dashes + "/")); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || isDate(value)) { - var dateNum = value.getTime(), - // is it in year range 1970-9999? - inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - // it's an integer - if (Math.floor(value) === value) { - var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; - // interpret as being of the smallest BSON integer type that can represent the number exactly - if (int32Range) - return { $numberInt: value.toString() }; - if (int64Range) - return { $numberLong: value.toString() }; - } - return { $numberDouble: value.toString() }; - } - if (value instanceof RegExp || isRegExp(value)) { - var flags = value.flags; - if (flags === undefined) { - var match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - var rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - if (value != null && typeof value === 'object') - return serializeDocument(value, options); - return value; - } - var BSON_TYPE_MAPPINGS = { - Binary: function (o) { return new Binary(o.value(), o.sub_type); }, - Code: function (o) { return new Code(o.code, o.scope); }, - DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, - Decimal128: function (o) { return new Decimal128(o.bytes); }, - Double: function (o) { return new Double(o.value); }, - Int32: function (o) { return new Int32(o.value); }, - Long: function (o) { - return Long.fromBits( - // underscore variants for 1.x backwards compatibility - o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); - }, - MaxKey: function () { return new MaxKey(); }, - MinKey: function () { return new MinKey(); }, - ObjectID: function (o) { return new ObjectId(o); }, - ObjectId: function (o) { return new ObjectId(o); }, - BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, - Symbol: function (o) { return new BSONSymbol(o.value); }, - Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } - }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function serializeDocument(doc, options) { - if (doc == null || typeof doc !== 'object') - throw new BSONError('not an object instance'); - var bsontype = doc._bsontype; - if (typeof bsontype === 'undefined') { - // It's a regular object. Recursively serialize its property values. - var _doc = {}; - for (var name in doc) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - _doc[name] = serializeValue(doc[name], options); - } - finally { - options.seenObjects.pop(); - } - } - return _doc; - } - else if (isBSONType(doc)) { - // the "document" is really just a BSON type object - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var outDoc = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - // There's no EJSON serialization function on the object. It's probably an - // object created by a previous version of this library (or another library) - // that's duck-typing objects to look like they were generated by this library). - // Copy the object into this library's version of that type. - var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - // Two BSON types may have nested objects that may need to be serialized too - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } - else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); - } - return outDoc.toExtendedJSON(options); - } - else { - throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } - } - /** - * EJSON parse / stringify API - * @public - */ - // the namespace here is used to emulate `export * as EJSON from '...'` - // which as of now (sept 2020) api-extractor does not support - // eslint-disable-next-line @typescript-eslint/no-namespace - exports.EJSON = void 0; - (function (EJSON) { - /** - * Parse an Extended JSON string, constructing the JavaScript value or object described by that - * string. - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const text = '{ "int32": { "$numberInt": "10" } }'; - * - * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } - * console.log(EJSON.parse(text, { relaxed: false })); - * - * // prints { int32: 10 } - * console.log(EJSON.parse(text)); - * ``` - */ - function parse(text, options) { - var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); - // relaxed implies not strict - if (typeof finalOptions.relaxed === 'boolean') - finalOptions.strict = !finalOptions.relaxed; - if (typeof finalOptions.strict === 'boolean') - finalOptions.relaxed = !finalOptions.strict; - return JSON.parse(text, function (key, value) { - if (key.indexOf('\x00') !== -1) { - throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); - } - return deserializeValue(value, finalOptions); - }); - } - EJSON.parse = parse; - /** - * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer - * function is specified or optionally including only the specified properties if a replacer array - * is specified. - * - * @param value - The value to convert to extended JSON - * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string - * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. - * @param options - Optional settings - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const Int32 = require('mongodb').Int32; - * const doc = { int32: new Int32(10) }; - * - * // prints '{"int32":{"$numberInt":"10"}}' - * console.log(EJSON.stringify(doc, { relaxed: false })); - * - * // prints '{"int32":10}' - * console.log(EJSON.stringify(doc)); - * ``` - */ - function stringify(value, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - replacer, space, options) { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - var doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer, space); - } - EJSON.stringify = stringify; - /** - * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - * - * @param value - The object to serialize - * @param options - Optional settings passed to the `stringify` function - */ - function serialize(value, options) { - options = options || {}; - return JSON.parse(stringify(value, options)); - } - EJSON.serialize = serialize; - /** - * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - * - * @param ejson - The Extended JSON object to deserialize - * @param options - Optional settings passed to the parse method - */ - function deserialize(ejson, options) { - options = options || {}; - return parse(JSON.stringify(ejson), options); - } - EJSON.deserialize = deserialize; - })(exports.EJSON || (exports.EJSON = {})); - - /* eslint-disable @typescript-eslint/no-explicit-any */ - /** @public */ - exports.Map = void 0; - var bsonGlobal = getGlobal(); - if (bsonGlobal.Map) { - exports.Map = bsonGlobal.Map; - } - else { - // We will return a polyfill - exports.Map = /** @class */ (function () { - function Map(array) { - if (array === void 0) { array = []; } - this._keys = []; - this._values = {}; - for (var i = 0; i < array.length; i++) { - if (array[i] == null) - continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - } - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) - return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - Map.prototype.entries = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? [key, _this._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.forEach = function (callback, self) { - self = self || this; - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - Map.prototype.keys = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - Map.prototype.values = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? _this._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Object.defineProperty(Map.prototype, "size", { - get: function () { - return this._keys.length; - }, - enumerable: false, - configurable: true - }); - return Map; - }()); - } - - /** @internal */ - var BSON_INT32_MAX = 0x7fffffff; - /** @internal */ - var BSON_INT32_MIN = -0x80000000; - /** @internal */ - var BSON_INT64_MAX = Math.pow(2, 63) - 1; - /** @internal */ - var BSON_INT64_MIN = -Math.pow(2, 63); - /** - * Any integer up to 2^53 can be precisely represented by a double. - * @internal - */ - var JS_INT_MAX = Math.pow(2, 53); - /** - * Any integer down to -2^53 can be precisely represented by a double. - * @internal - */ - var JS_INT_MIN = -Math.pow(2, 53); - /** Number BSON Type @internal */ - var BSON_DATA_NUMBER = 1; - /** String BSON Type @internal */ - var BSON_DATA_STRING = 2; - /** Object BSON Type @internal */ - var BSON_DATA_OBJECT = 3; - /** Array BSON Type @internal */ - var BSON_DATA_ARRAY = 4; - /** Binary BSON Type @internal */ - var BSON_DATA_BINARY = 5; - /** Binary BSON Type @internal */ - var BSON_DATA_UNDEFINED = 6; - /** ObjectId BSON Type @internal */ - var BSON_DATA_OID = 7; - /** Boolean BSON Type @internal */ - var BSON_DATA_BOOLEAN = 8; - /** Date BSON Type @internal */ - var BSON_DATA_DATE = 9; - /** null BSON Type @internal */ - var BSON_DATA_NULL = 10; - /** RegExp BSON Type @internal */ - var BSON_DATA_REGEXP = 11; - /** Code BSON Type @internal */ - var BSON_DATA_DBPOINTER = 12; - /** Code BSON Type @internal */ - var BSON_DATA_CODE = 13; - /** Symbol BSON Type @internal */ - var BSON_DATA_SYMBOL = 14; - /** Code with Scope BSON Type @internal */ - var BSON_DATA_CODE_W_SCOPE = 15; - /** 32 bit Integer BSON Type @internal */ - var BSON_DATA_INT = 16; - /** Timestamp BSON Type @internal */ - var BSON_DATA_TIMESTAMP = 17; - /** Long BSON Type @internal */ - var BSON_DATA_LONG = 18; - /** Decimal128 BSON Type @internal */ - var BSON_DATA_DECIMAL128 = 19; - /** MinKey BSON Type @internal */ - var BSON_DATA_MIN_KEY = 0xff; - /** MaxKey BSON Type @internal */ - var BSON_DATA_MAX_KEY = 0x7f; - /** Binary Default Type @internal */ - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** Binary Function Type @internal */ - var BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** Binary Byte Array Type @internal */ - var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ - var BSON_BINARY_SUBTYPE_UUID = 3; - /** Binary UUID Type @internal */ - var BSON_BINARY_SUBTYPE_UUID_NEW = 4; - /** Binary MD5 Type @internal */ - var BSON_BINARY_SUBTYPE_MD5 = 5; - /** Encrypted BSON type @internal */ - var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; - /** Column BSON type @internal */ - var BSON_BINARY_SUBTYPE_COLUMN = 7; - /** Binary User Defined Type @internal */ - var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } - else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - return totalLength; - } - /** @internal */ - function calculateElement(name, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - value, serializeFunctions, isArray, ignoreUndefined) { - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (isArray === void 0) { isArray = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = false; } - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - switch (typeof value) { - case 'string': - return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && - value >= JS_INT_MIN && - value <= JS_INT_MAX) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - // 32 bit - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } - else { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } - else { - // 64 bit - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } - else if (value instanceof Date || isDate(value)) { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - isAnyArrayBuffer(value)) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); - } - else if (value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (value['_bsontype'] === 'Decimal128') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } - else if (value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.byteLength(value.code.toString(), 'utf8') + - 1); - } - } - else if (value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4)); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); - } - } - else if (value['_bsontype'] === 'Symbol') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - buffer_1.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1); - } - else if (value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - // Add db reference if it exists - if (value.db != null) { - ordered_values['$db'] = value.db; - } - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); - } - else if (value instanceof RegExp || isRegExp(value)) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else if (value['_bsontype'] === 'BSONRegExp') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.pattern, 'utf8') + - 1 + - buffer_1.byteLength(value.options, 'utf8') + - 1); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + - 1); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else if (serializeFunctions) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + - 1); - } - } - } - return 0; - } - - var FIRST_BIT = 0x80; - var FIRST_TWO_BITS = 0xc0; - var FIRST_THREE_BITS = 0xe0; - var FIRST_FOUR_BITS = 0xf0; - var FIRST_FIVE_BITS = 0xf8; - var TWO_BIT_CHAR = 0xc0; - var THREE_BIT_CHAR = 0xe0; - var FOUR_BIT_CHAR = 0xf0; - var CONTINUING_CHAR = 0x80; - /** - * Determines if the passed in bytes are valid utf8 - * @param bytes - An array of 8-bit bytes. Must be indexable and have length property - * @param start - The index to start validating - * @param end - The index to end validating - */ - function validateUtf8(bytes, start, end) { - var continuation = 0; - for (var i = start; i < end; i += 1) { - var byte = bytes[i]; - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } - else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } - else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } - else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } - else { - return false; - } - } - } - return !continuation; - } - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); - var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); - var functionCache = {}; - function deserialize$1(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (size < 5) { - throw new BSONError("bson size must be >= 5, is " + size); - } - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); - } - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); - } - if (size + index > buffer.byteLength) { - throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); - } - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - } - var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; - function deserializeObject(buffer, index, options, isArray) { - if (isArray === void 0) { isArray = false; } - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - // Ensures default validation option if none given - var validation = options.validation == null ? { utf8: true } : options.validation; - // Shows if global utf-8 validation is enabled or disabled - var globalUTFValidation = true; - // Reflects utf-8 validation setting regardless of global or specific key validation - var validationSetting; - // Set of keys either to enable or disable validation on - var utf8KeysSet = new Set(); - // Check for boolean uniformity and empty validation option - var utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } - else { - globalUTFValidation = false; - var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - // Ensures boolean uniformity in utf-8 validation (all true or all false) - if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) { - throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - // Add keys to set that will either be validated or not based on validationSetting - if (!globalUTFValidation) { - for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) { - var key = _a[_i]; - utf8KeysSet.add(key); - } - } - // Set the start index - var startIndex = index; - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) - throw new BSONError('corrupt bson message < 5 bytes long'); - // Read the document size - var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) - throw new BSONError('corrupt bson message'); - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - var done = false; - var isPossibleDBRef = isArray ? false : null; - // While we have more left data left keep parsing - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) - break; - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.byteLength) - throw new BSONError('Bad BSON Document: illegal CString'); - // Represents the key - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - // shouldValidateKey is true if the key should be validated, false otherwise - var shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } - else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - var value = void 0; - index = i + 1; - if (elementType === BSON_DATA_STRING) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } - else if (elementType === BSON_DATA_OID) { - var oid = buffer_1.alloc(12); - buffer.copy(oid, 0, index, index + 12); - value = new ObjectId(oid); - index = index + 12; - } - else if (elementType === BSON_DATA_INT && promoteValues === false) { - value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); - } - else if (elementType === BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } - else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { - value = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } - else if (elementType === BSON_DATA_NUMBER) { - value = buffer.readDoubleLE(index); - index = index + 8; - } - else if (elementType === BSON_DATA_DATE) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new Long(lowBits, highBits).toNumber()); - } - else if (elementType === BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } - else if (elementType === BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new BSONError('bad embedded document length in bson'); - // We have a raw value - if (raw) { - value = buffer.slice(index, index + objectSize); - } - else { - var objectOptions = options; - if (!globalUTFValidation) { - objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - index = index + objectSize; - } - else if (elementType === BSON_DATA_ARRAY) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - // Stop index - var stopIndex = index + objectSize; - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) { - arrayOptions[n] = options[n]; - } - arrayOptions['raw'] = true; - } - if (!globalUTFValidation) { - arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - if (buffer[index - 1] !== 0) - throw new BSONError('invalid array terminator byte'); - if (index !== stopIndex) - throw new BSONError('corrupted array bson'); - } - else if (elementType === BSON_DATA_UNDEFINED) { - value = undefined; - } - else if (elementType === BSON_DATA_NULL) { - value = null; - } - else if (elementType === BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } - else { - value = long; - } - } - else if (elementType === BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = buffer_1.alloc(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { - value = decimal128.toObject(); - } - else { - value = decimal128; - } - } - else if (elementType === BSON_DATA_BINARY) { - var binarySize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - // Did we have a negative binary size, throw - if (binarySize < 0) - throw new BSONError('Negative binary type element size found'); - // Is the length longer than the document - if (binarySize > buffer.byteLength) - throw new BSONError('Binary type size larger than document size'); - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - if (promoteBuffers && promoteValues) { - value = buffer.slice(index, index + binarySize); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - } - } - else { - var _buffer = buffer_1.alloc(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - if (promoteBuffers && promoteValues) { - value = _buffer; - } - else { - value = new Binary(_buffer, subType); - } - } - // Update the index - index = index + binarySize; - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - value = new RegExp(source, optionsArray.join('')); - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // Set the object - value = new BSONRegExp(source, regExpOptions); - } - else if (elementType === BSON_DATA_SYMBOL) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new BSONSymbol(symbol); - index = index + stringSize; - } - else if (elementType === BSON_DATA_TIMESTAMP) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Timestamp(lowBits, highBits); - } - else if (elementType === BSON_DATA_MIN_KEY) { - value = new MinKey(); - } - else if (elementType === BSON_DATA_MAX_KEY) { - value = new MaxKey(); - } - else if (elementType === BSON_DATA_CODE) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - } - else { - value = new Code(functionString); - } - // Update parse index position - index = index + stringSize; - } - else if (elementType === BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError('code_w_scope total size shorter minimum expected length'); - } - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - // Javascript function - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // Update parse index position - index = index + stringSize; - // Parse the element - var _index = index; - // Decode the size of the object document - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - // Check if field length is too short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too short, truncating scope'); - } - // Check if totalSize field is too long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too long, clips outer document'); - } - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - value.scope = scopeObject; - } - else { - value = new Code(functionString, scopeObject); - } - } - else if (elementType === BSON_DATA_DBPOINTER) { - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) - throw new BSONError('bad string length in bson'); - // Namespace - if (validation != null && validation.utf8) { - if (!validateUtf8(buffer, index, index + stringSize - 1)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - } - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Read the oid - var oidBuffer = buffer_1.alloc(12); - buffer.copy(oidBuffer, 0, index, index + 12); - var oid = new ObjectId(oidBuffer); - // Update the index - index = index + 12; - // Upgrade to DBRef type - value = new DBRef(namespace, oid); - } - else { - throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value: value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - object[name] = value; - } - } - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) - throw new BSONError('corrupt array bson'); - throw new BSONError('corrupt object bson'); - } - // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef - if (!isPossibleDBRef) - return object; - if (isDBRefLike(object)) { - var copy = Object.assign({}, object); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object.$ref, object.$id, object.$db, copy); - } - return object; - } - /** - * Ensure eval is isolated, store the result in functionCache. - * - * @internal - */ - function isolateEval(functionString, functionCache, object) { - if (!functionCache) - return new Function(functionString); - // Check for cache hit, eval if missing and return cached function - if (functionCache[functionString] == null) { - functionCache[functionString] = new Function(functionString); - } - // Set the object - return functionCache[functionString].bind(object); - } - function getValidatedString(buffer, start, end, shouldValidateUtf8) { - var value = buffer.toString('utf8', start, end); - // if utf8 validation is on, do the check - if (shouldValidateUtf8) { - for (var i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validateUtf8(buffer, start, end)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; - } - - // Copyright (c) 2008, Fair Oaks Labs, Inc. - function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { - var e; - var m; - var c; - var bBE = endian === 'big'; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = bBE ? nBytes - 1 : 0; - var d = bBE ? -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; - } - } - if (isNaN(value)) - m = 0; - while (mLen >= 8) { - buffer[offset + i] = m & 0xff; - i += d; - m /= 256; - mLen -= 8; - } - e = (e << mLen) | m; - if (isNaN(value)) - e += 8; - eLen += mLen; - while (eLen > 0) { - buffer[offset + i] = e & 0xff; - i += d; - e /= 256; - eLen -= 8; - } - buffer[offset + i - d] |= s * 128; - } - - var regexp = /\x00/; // eslint-disable-line no-control-regex - var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); - /* - * isArray indicates if we are writing to a BSON array (type 0x04) - * which forces the "key" which really an array index as a string to be written as ascii - * This will catch any errors in index as a string generation - */ - function serializeString(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, undefined, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - } - function serializeNumber(buffer, key, value, index, isArray) { - // We have an integer value - // TODO(NODE-2529): Add support for big int - if (Number.isInteger(value) && - value >= BSON_INT32_MIN && - value <= BSON_INT32_MAX) { - // If the value fits in 32 bits encode as int32 - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } - else { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - } - return index; - } - function serializeNull(buffer, key, _, index, isArray) { - // Set long type - buffer[index++] = BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - } - function serializeBoolean(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - } - function serializeDate(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } - function serializeRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.ignoreCase) - buffer[index++] = 0x69; // i - if (value.global) - buffer[index++] = 0x73; // s - if (value.multiline) - buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } - function serializeBSONRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.pattern, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - } - function serializeMinMax(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON_DATA_NULL; - } - else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON_DATA_MIN_KEY; - } - else { - buffer[index++] = BSON_DATA_MAX_KEY; - } - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - } - function serializeObjectId(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, undefined, 'binary'); - } - else if (isUint8Array(value.id)) { - // Use the standard JS methods here because buffer.copy() is buggy with the - // browser polyfill - buffer.set(value.id.subarray(0, 12), index); - } - else { - throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - // Adjust index - return index + 12; - } - function serializeBuffer(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - buffer.set(ensureBuffer(value), index); - // Adjust the index - index = index + size; - return index; - } - function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (path === void 0) { path = []; } - for (var i = 0; i < path.length; i++) { - if (path[i] === value) - throw new BSONError('cyclic dependency detected'); - } - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - return endIndex; - } - function serializeDecimal128(buffer, key, value, index, isArray) { - buffer[index++] = BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - // Prefer the standard JS methods because their typechecking is not buggy, - // unlike the `buffer` polyfill's. - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; - } - function serializeLong(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = - value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } - function serializeInt32(buffer, key, value, index, isArray) { - value = value.valueOf(); - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; - } - function serializeDouble(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value.value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - return index; - } - function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Starting index - var startIndex = index; - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - // Writ the total - var totalSize = endIndex - startIndex; - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } - else { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - return index; - } - function serializeBinary(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - // Write the data to the object - buffer.set(data, index); - // Adjust the index - index = index + value.position; - return index; - } - function serializeSymbol(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } - function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var startIndex = index; - var output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; - } - output = Object.assign(output, value.fields); - var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; - } - function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (startingIndex === void 0) { startingIndex = 0; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (path === void 0) { path = []; } - startingIndex = startingIndex || 0; - path = path || []; - // Push the object to the path - path.push(object); - // Start place to serialize into - var index = startingIndex + 4; - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index, true); - } - else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } - else if (typeof value === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } - else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } - else if (typeof value === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } - else if (typeof value === 'object' && - isBSONType(value) && - value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else if (object instanceof exports.Map || isMap(object)) { - var iterator = object.entries(); - var done = false; - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = !!entry.done; - // Are we done, then skip and terminate - if (done) - continue; - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new BSONTypeError('toBSON function did not return an object'); - } - // Iterate over all the keys - for (var key in object) { - var value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - if (ignoreUndefined === false) - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - // Remove the path - path.pop(); - // Final padding byte for object - buffer[index++] = 0x00; - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; - } - - /** @internal */ - // Default Max Size - var MAXSIZE = 1024 * 1024 * 17; - // Current Internal Temporary Serialization Buffer - var buffer = buffer_1.alloc(MAXSIZE); - /** - * Sets the size of the internal serialization buffer. - * - * @param size - The desired size for the internal serialization buffer - * @public - */ - function setInternalBufferSize(size) { - // Resize the internal serialization buffer if needed - if (buffer.length < size) { - buffer = buffer_1.alloc(size); - } - } - /** - * Serialize a Javascript object. - * - * @param object - the Javascript object to serialize. - * @returns Buffer object containing the serialized object. - * @public - */ - function serialize(object, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = buffer_1.alloc(minInternalBufferSize); - } - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = buffer_1.alloc(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - } - /** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, - * useful when pre-allocating the space for serialization. - * - * @param object - the Javascript object to serialize. - * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. - * @returns the index pointing to the last written byte in the buffer. - * @public - */ - function serializeWithBufferAndIndex(object, finalBuffer, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - // Return the index - return startIndex + serializationIndex - 1; - } - /** - * Deserialize data as BSON. - * - * @param buffer - the buffer containing the serialized set of BSON documents. - * @returns returns the deserialized Javascript Object. - * @public - */ - function deserialize(buffer, options) { - if (options === void 0) { options = {}; } - return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options); - } - /** - * Calculate the bson size for a passed in Javascript object. - * - * @param object - the Javascript object to calculate the BSON byte size for - * @returns size of BSON object in bytes - * @public - */ - function calculateObjectSize(object, options) { - if (options === void 0) { options = {}; } - options = options || {}; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); - } - /** - * Deserialize stream data as BSON documents. - * - * @param data - the buffer containing the serialized set of BSON documents. - * @param startIndex - the start index in the data Buffer where the deserialization is to start. - * @param numberOfDocuments - number of documents to deserialize. - * @param documents - an array where to store the deserialized documents. - * @param docStartIndex - the index in the documents array from where to start inserting documents. - * @param options - additional options used for the deserialization. - * @returns next index in the buffer after deserialization **x** numbers of documents. - * @public - */ - function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - var bufferData = ensureBuffer(data); - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - // Update options with index - internalOptions.index = index; - // Parse the document at this point - documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); - // Adjust index by the document size - index = index + size; - } - // Return object containing end index of parsing and list of documents - return index; - } - /** - * BSON default export - * @deprecated Please use named exports - * @privateRemarks - * We want to someday deprecate the default export, - * so none of the new TS types are being exported on the default - * @public - */ - var BSON = { - Binary: Binary, - Code: Code, - DBRef: DBRef, - Decimal128: Decimal128, - Double: Double, - Int32: Int32, - Long: Long, - UUID: UUID, - Map: exports.Map, - MaxKey: MaxKey, - MinKey: MinKey, - ObjectId: ObjectId, - ObjectID: ObjectId, - BSONRegExp: BSONRegExp, - BSONSymbol: BSONSymbol, - Timestamp: Timestamp, - EJSON: exports.EJSON, - setInternalBufferSize: setInternalBufferSize, - serialize: serialize, - serializeWithBufferAndIndex: serializeWithBufferAndIndex, - deserialize: deserialize, - calculateObjectSize: calculateObjectSize, - deserializeStream: deserializeStream, - BSONError: BSONError, - BSONTypeError: BSONTypeError - }; - - exports.BSONError = BSONError; - exports.BSONRegExp = BSONRegExp; - exports.BSONSymbol = BSONSymbol; - exports.BSONTypeError = BSONTypeError; - exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = BSON_BINARY_SUBTYPE_BYTE_ARRAY; - exports.BSON_BINARY_SUBTYPE_COLUMN = BSON_BINARY_SUBTYPE_COLUMN; - exports.BSON_BINARY_SUBTYPE_DEFAULT = BSON_BINARY_SUBTYPE_DEFAULT; - exports.BSON_BINARY_SUBTYPE_ENCRYPTED = BSON_BINARY_SUBTYPE_ENCRYPTED; - exports.BSON_BINARY_SUBTYPE_FUNCTION = BSON_BINARY_SUBTYPE_FUNCTION; - exports.BSON_BINARY_SUBTYPE_MD5 = BSON_BINARY_SUBTYPE_MD5; - exports.BSON_BINARY_SUBTYPE_USER_DEFINED = BSON_BINARY_SUBTYPE_USER_DEFINED; - exports.BSON_BINARY_SUBTYPE_UUID = BSON_BINARY_SUBTYPE_UUID; - exports.BSON_BINARY_SUBTYPE_UUID_NEW = BSON_BINARY_SUBTYPE_UUID_NEW; - exports.BSON_DATA_ARRAY = BSON_DATA_ARRAY; - exports.BSON_DATA_BINARY = BSON_DATA_BINARY; - exports.BSON_DATA_BOOLEAN = BSON_DATA_BOOLEAN; - exports.BSON_DATA_CODE = BSON_DATA_CODE; - exports.BSON_DATA_CODE_W_SCOPE = BSON_DATA_CODE_W_SCOPE; - exports.BSON_DATA_DATE = BSON_DATA_DATE; - exports.BSON_DATA_DBPOINTER = BSON_DATA_DBPOINTER; - exports.BSON_DATA_DECIMAL128 = BSON_DATA_DECIMAL128; - exports.BSON_DATA_INT = BSON_DATA_INT; - exports.BSON_DATA_LONG = BSON_DATA_LONG; - exports.BSON_DATA_MAX_KEY = BSON_DATA_MAX_KEY; - exports.BSON_DATA_MIN_KEY = BSON_DATA_MIN_KEY; - exports.BSON_DATA_NULL = BSON_DATA_NULL; - exports.BSON_DATA_NUMBER = BSON_DATA_NUMBER; - exports.BSON_DATA_OBJECT = BSON_DATA_OBJECT; - exports.BSON_DATA_OID = BSON_DATA_OID; - exports.BSON_DATA_REGEXP = BSON_DATA_REGEXP; - exports.BSON_DATA_STRING = BSON_DATA_STRING; - exports.BSON_DATA_SYMBOL = BSON_DATA_SYMBOL; - exports.BSON_DATA_TIMESTAMP = BSON_DATA_TIMESTAMP; - exports.BSON_DATA_UNDEFINED = BSON_DATA_UNDEFINED; - exports.BSON_INT32_MAX = BSON_INT32_MAX; - exports.BSON_INT32_MIN = BSON_INT32_MIN; - exports.BSON_INT64_MAX = BSON_INT64_MAX; - exports.BSON_INT64_MIN = BSON_INT64_MIN; - exports.Binary = Binary; - exports.Code = Code; - exports.DBRef = DBRef; - exports.Decimal128 = Decimal128; - exports.Double = Double; - exports.Int32 = Int32; - exports.Long = Long; - exports.LongWithoutOverridesClass = LongWithoutOverridesClass; - exports.MaxKey = MaxKey; - exports.MinKey = MinKey; - exports.ObjectID = ObjectId; - exports.ObjectId = ObjectId; - exports.Timestamp = Timestamp; - exports.UUID = UUID; - exports.calculateObjectSize = calculateObjectSize; - exports.default = BSON; - exports.deserialize = deserialize; - exports.deserializeStream = deserializeStream; - exports.serialize = serialize; - exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; - exports.setInternalBufferSize = setInternalBufferSize; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); -//# sourceMappingURL=bson.browser.umd.js.map diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.umd.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.umd.js.map deleted file mode 100644 index ddee79c..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.browser.umd.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bson.browser.umd.js","sources":["../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/buffer/index.js","../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"sourcesContent":["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n var proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n var copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(buf).copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["byteLength","toByteArray","fromByteArray","lookup","revLookup","Arr","Uint8Array","Array","code","i","len","length","charCodeAt","getLens","b64","Error","validLen","indexOf","placeHoldersLen","lens","_byteLength","tmp","arr","curByte","tripletToBase64","num","encodeChunk","uint8","start","end","output","push","join","extraBytes","parts","maxChunkLength","len2","buffer","offset","isLE","mLen","nBytes","e","m","eLen","eMax","eBias","nBits","d","s","NaN","Infinity","Math","pow","value","c","rt","abs","isNaN","floor","log","LN2","customInspectSymbol","Symbol","exports","Buffer","SlowBuffer","K_MAX_LENGTH","TYPED_ARRAY_SUPPORT","typedArraySupport","console","error","proto","foo","Object","setPrototypeOf","prototype","defineProperty","enumerable","get","isBuffer","undefined","byteOffset","createBuffer","RangeError","buf","arg","encodingOrOffset","TypeError","allocUnsafe","from","poolSize","fromString","ArrayBuffer","isView","fromArrayView","isInstance","fromArrayBuffer","SharedArrayBuffer","valueOf","b","fromObject","toPrimitive","assertSize","size","alloc","fill","encoding","checked","allocUnsafeSlow","string","isEncoding","actual","write","slice","fromArrayLike","array","arrayView","copy","obj","numberIsNaN","type","isArray","data","toString","_isBuffer","compare","a","x","y","min","String","toLowerCase","concat","list","pos","set","call","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","swap16","swap32","swap64","apply","toLocaleString","equals","inspect","str","max","INSPECT_MAX_BYTES","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","includes","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","utf16leToBytes","isFinite","toJSON","_arr","base64","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","MAX_ARGUMENTS_LENGTH","codePoints","fromCharCode","ret","out","hexSliceLookupTable","bytes","newBuf","subarray","checkOffset","ext","readUintLE","readUIntLE","noAssert","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","ieee754","readFloatBE","readDoubleLE","readDoubleBE","checkInt","writeUintLE","writeUIntLE","maxBytes","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","checkIEEE754","writeFloat","littleEndian","writeFloatLE","writeFloatBE","writeDouble","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","base64clean","split","units","leadSurrogate","byteArray","hi","lo","src","dst","constructor","name","alphabet","table","i16","extendStatics","__proto__","p","hasOwnProperty","__extends","__","create","__assign","assign","t","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","EJSON","bsonMap","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;;;;;;;;;CAEA,gBAAkB,GAAGA,UAArB;CACA,iBAAmB,GAAGC,WAAtB;CACA,mBAAqB,GAAGC,aAAxB;CAEA,IAAIC,MAAM,GAAG,EAAb;CACA,IAAIC,SAAS,GAAG,EAAhB;CACA,IAAIC,GAAG,GAAG,OAAOC,UAAP,KAAsB,WAAtB,GAAoCA,UAApC,GAAiDC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SAEhF,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;MACtB;;KAGD,OAAO,KAAK,CAAC;CACf,CAAC;CAED;;;;;;;;KAQM,IAAI,GAAG;KACX,MAAM,QAAA;KACN,IAAI,MAAA;KACJ,KAAK,OAAA;KACL,UAAU,YAAA;KACV,MAAM,QAAA;KACN,KAAK,OAAA;KACL,IAAI,MAAA;KACJ,IAAI,MAAA;KACJ,GAAG,aAAA;KACH,MAAM,QAAA;KACN,MAAM,QAAA;KACN,QAAQ,UAAA;KACR,QAAQ,EAAE,QAAQ;KAClB,UAAU,YAAA;KACV,UAAU,YAAA;KACV,SAAS,WAAA;KACT,KAAK,eAAA;KACL,qBAAqB,uBAAA;KACrB,SAAS,WAAA;KACT,2BAA2B,6BAAA;KAC3B,WAAW,aAAA;KACX,mBAAmB,qBAAA;KACnB,iBAAiB,mBAAA;KACjB,SAAS,WAAA;KACT,aAAa,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.bundle.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.bundle.js deleted file mode 100644 index 833ea99..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.bundle.js +++ /dev/null @@ -1,7579 +0,0 @@ -var BSON = (function (exports) { - 'use strict'; - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var byteLength_1 = byteLength; - var toByteArray_1 = toByteArray; - var fromByteArray_1 = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } // Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - - function getLens(b64) { - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4'); - } // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - - - var validLen = b64.indexOf('='); - if (validLen === -1) validLen = len; - var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } // base64 is 4/3 + up to two characters of the original data - - - 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; // if there are placeholders, only get up to the last complete 4 chars - - var len = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i; - - for (i = 0; i < len; i += 4) { - tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; - arr[curByte++] = tmp >> 16 & 0xFF; - arr[curByte++] = tmp >> 8 & 0xFF; - arr[curByte++] = tmp & 0xFF; - } - - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; - arr[curByte++] = tmp & 0xFF; - } - - 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 & 0xFF; - arr[curByte++] = tmp & 0xFF; - } - - return arr; - } - - function tripletToBase64(num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - } - - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); - output.push(tripletToBase64(tmp)); - } - - return output.join(''); - } - - function fromByteArray(uint8) { - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); - } // pad the end with zeros, but make sure to not forget the extra bytes - - - if (extraBytes === 1) { - tmp = uint8[len - 1]; - parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); - } - - return parts.join(''); - } - - var base64Js = { - byteLength: byteLength_1, - toByteArray: toByteArray_1, - fromByteArray: fromByteArray_1 - }; - - /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - var read = function read(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 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); - }; - - var write = function write(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 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 & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = e << mLen | m; - eLen += mLen; - - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; - }; - - var ieee754 = { - read: read, - write: write - }; - - var buffer$1 = createCommonjsModule(function (module, exports) { - - var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation - Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation - : null; - exports.Buffer = Buffer; - exports.SlowBuffer = SlowBuffer; - exports.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 0x7fffffff; - exports.kMaxLength = K_MAX_LENGTH; - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ - - 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() { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1); - var proto = { - foo: function foo() { - return 42; - } - }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e) { - return false; - } - } - - Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function get() { - if (!Buffer.isBuffer(this)) return undefined; - return this.buffer; - } - }); - Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function get() { - 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"'); - } // Return an augmented `Uint8Array` instance - - - var buf = new Uint8Array(length); - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; - } - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - - function Buffer(arg, encodingOrOffset, length) { - // Common case. - 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); - } - - Buffer.poolSize = 8192; // not used by this implementation - - function from(value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset); - } - - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - - if (value == null) { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); - } - - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - - if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - 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 ' + babelHelpers["typeof"](value)); - } - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - - - Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length); - }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: - // https://github.com/feross/buffer/pull/148 - - - Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer, 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) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpreted as a start offset. - return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - - return createBuffer(size); - } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - - - Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding); - }; - - function allocUnsafe(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - - - Buffer.allocUnsafe = function (size) { - return allocUnsafe(size); - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - - - 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) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - 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 < length; i += 1) { - buf[i] = array[i] & 255; - } - - return buf; - } - - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - - return fromArrayLike(arrayView); - } - - function fromArrayBuffer(array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - - var buf; - - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array); - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length); - } // Return an augmented `Uint8Array` instance - - - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; - } - - function fromObject(obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); - - if (buf.length === 0) { - return buf; - } - - obj.copy(buf, 0, 0, len); - return buf; - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0); - } - - return fromArrayLike(obj); - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - - function checked(length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= 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) { - // eslint-disable-line eqeqeq - length = 0; - } - - return Buffer.alloc(+length); - } - - Buffer.isBuffer = function isBuffer(b) { - return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false - }; - - 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); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - - Buffer.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true; - - default: - return false; - } - }; - - Buffer.concat = function concat(list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - - if (list.length === 0) { - return Buffer.alloc(0); - } - - var i; - - if (length === undefined) { - length = 0; - - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer.from(buf).copy(buffer, pos); - } else { - Uint8Array.prototype.set.call(buffer, buf, pos); - } - } else if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - - pos += buf.length; - } - - return buffer; - }; - - function byteLength(string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length; - } - - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength; - } - - if (typeof string !== 'string') { - throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string)); - } - - var len = string.length; - var mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion - - 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; // assume utf8 - } - - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - - Buffer.byteLength = byteLength; - - function slowToString(encoding, start, end) { - var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - - if (start === undefined || start < 0) { - start = 0; - } // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - - - if (start > this.length) { - return ''; - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return ''; - } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. - - - 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; - } - } - } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) - // to detect a Buffer instance. It's not possible to use `instanceof Buffer` - // reliably in a browserify context because there could be multiple different - // copies of the 'buffer' package in use. This method works even for Buffer - // instances that were created from another copy of the `buffer` package. - // See: https://github.com/feross/buffer/issues/154 - - - 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; i < len; i += 2) { - swap(this, i, i + 1); - } - - return this; - }; - - Buffer.prototype.swap32 = function swap32() { - var len = this.length; - - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits'); - } - - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - - return this; - }; - - Buffer.prototype.swap64 = function swap64() { - var len = this.length; - - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits'); - } - - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - - return this; - }; - - Buffer.prototype.toString = function toString() { - var length = this.length; - if (length === 0) return ''; - if (arguments.length === 0) return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); - }; - - Buffer.prototype.toLocaleString = Buffer.prototype.toString; - - Buffer.prototype.equals = function equals(b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); - if (this === b) return true; - return Buffer.compare(this, b) === 0; - }; - - Buffer.prototype.inspect = function inspect() { - var str = ''; - var max = exports.INSPECT_MAX_BYTES; - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); - if (this.length > max) str += ' ... '; - return ''; - }; - - if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; - } - - 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 ' + babelHelpers["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; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - - - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1; // Normalize byteOffset - - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - - byteOffset = +byteOffset; // Coerce to Number. - - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : buffer.length - 1; - } // Normalize byteOffset: negative offsets start from the end of the buffer - - - 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; - } // Normalize val - - - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } // Finally, search either indexOf (if dir is true) or lastIndexOf - - - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1; - } - - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-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; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - - for (i = byteOffset; i >= 0; i--) { - var found = true; - - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - - if (found) return i; - } - } - - return -1; - } - - Buffer.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - - Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - - Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - - if (!length) { - length = remaining; - } else { - length = Number(length); - - if (length > remaining) { - length = remaining; - } - } - - var strLen = string.length; - - if (length > strLen / 2) { - length = strLen / 2; - } - - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i; - buf[offset + i] = parsed; - } - - return i; - } - - function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); - } - - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length); - } - - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); - } - - function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); - } - - Buffer.prototype.write = function write(string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 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': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length); - - case 'base64': - // Warning: maxLength not taken into account in base64Write - 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 base64Js.fromByteArray(buf); - } else { - return base64Js.fromByteArray(buf.slice(start, end)); - } - } - - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i = start; - - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - - break; - - case 2: - secondByte = buf[i + 1]; - - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; - - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - - break; - - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; - - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - - break; - - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; - - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray(res); - } // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - - - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); // avoid extra slice() - } // Decode in chunks to avoid "call stack size exceeded". - - - var res = ''; - var i = 0; - - while (i < len) { - res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); - } - - return res; - } - - function asciiSlice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - - return ret; - } - - function latin1Slice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - - return ret; - } - - function hexSlice(buf, start, end) { - var len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - var out = ''; - - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - - return out; - } - - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - - for (var i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - - return res; - } - - Buffer.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance - - Object.setPrototypeOf(newBuf, Buffer.prototype); - return newBuf; - }; - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - - - function checkOffset(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); - } - - Buffer.prototype.readUintLE = 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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val; - }; - - Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val; - }; - - Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset]; - }; - - Buffer.prototype.readUint16LE = 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 = 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 = 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] * 0x1000000; - }; - - Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] * 0x1000000 + (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 < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - mul *= 0x80; - if (val >= 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 *= 0x100)) { - val += this[offset + --i] * mul; - } - - mul *= 0x80; - 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] & 0x80)) return this[offset]; - return (0xff - 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 & 0x8000 ? val | 0xFFFF0000 : 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 & 0x8000 ? val | 0xFFFF0000 : 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 || value < min) throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) throw new RangeError('Index out of range'); - } - - Buffer.prototype.writeUintLE = 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 & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(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 i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - - Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 0xff; - return offset + 4; - }; - - Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - 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 & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - 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 & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (value < 0) value = 0xff + value + 1; - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - this[offset] = value & 0xff; - 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, 0x7fff, -0x8000); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - this[offset] = value & 0xff; - 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, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - 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); - } - - 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); - } - - 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); - }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - - - 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 < start) end = start; // Copy 0 bytes; we're done - - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions - - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds'); - } - - if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); - if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? - - if (end > this.length) end = this.length; - - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); - } - - return len; - }; // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - - - Buffer.prototype.fill = function fill(val, start, end, encoding) { - // Handle string cases: - 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') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code; - } - } - } else if (typeof val === 'number') { - val = val & 255; - } else if (typeof val === 'boolean') { - val = Number(val); - } // Invalid ranges are not set to a default, so can range check early. - - - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index'); - } - - if (end <= start) { - return this; - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - if (!val) val = 0; - var i; - - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); - var len = bytes.length; - - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this; - }; // HELPER FUNCTIONS - // ================ - - - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - - function base64clean(str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not - - str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' - - if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - - while (str.length % 4 !== 0) { - str = str + '='; - } - - return str; - } - - function utf8ToBytes(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); // is surrogate component - - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } // valid lead - - - leadSurrogate = codePoint; - continue; - } // 2 leads in a row - - - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue; - } // valid surrogate pair - - - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; // encode utf8 - - if (codePoint < 0x80) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break; - bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break; - bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break; - bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else { - throw new Error('Invalid code point'); - } - } - - return bytes; - } - - function asciiToBytes(str) { - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - - return byteArray; - } - - function utf16leToBytes(str, units) { - var c, hi, lo; - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray; - } - - function base64ToBytes(str) { - return base64Js.toByteArray(base64clean(str)); - } - - function blitBuffer(src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) break; - dst[i + offset] = src[i]; - } - - return i; - } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass - // the `instanceof` check but they should be treated as of that type. - // See: https://github.com/feross/buffer/issues/166 - - - 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) { - // For IE11 support - return obj !== obj; // eslint-disable-line no-self-compare - } // Create lookup table for `toString('hex')` - // See: https://github.com/feross/buffer/issues/219 - - - var hexSliceLookupTable = function () { - var alphabet = '0123456789abcdef'; - var table = new Array(256); - - for (var i = 0; i < 16; ++i) { - var i16 = i * 16; - - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; - } - } - - return table; - }(); - }); - var buffer_1 = buffer$1.Buffer; - buffer$1.SlowBuffer; - buffer$1.INSPECT_MAX_BYTES; - buffer$1.kMaxLength; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - - /* global Reflect, Promise */ - var _extendStatics = function extendStatics(d, b) { - _extendStatics = Object.setPrototypeOf || { - __proto__: [] - } instanceof Array && function (d, b) { - d.__proto__ = b; - } || function (d, b) { - for (var p in b) { - if (b.hasOwnProperty(p)) d[p] = b[p]; - } - }; - - return _extendStatics(d, b); - }; - - function __extends(d, b) { - _extendStatics(d, b); - - function __() { - this.constructor = d; - } - - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var _assign = function __assign() { - _assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - - for (var p in s) { - if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - } - - return t; - }; - - return _assign.apply(this, arguments); - }; - - /** @public */ - var BSONError = /** @class */ (function (_super) { - __extends(BSONError, _super); - function BSONError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONError.prototype); - return _this; - } - Object.defineProperty(BSONError.prototype, "name", { - get: function () { - return 'BSONError'; - }, - enumerable: false, - configurable: true - }); - return BSONError; - }(Error)); - /** @public */ - var BSONTypeError = /** @class */ (function (_super) { - __extends(BSONTypeError, _super); - function BSONTypeError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONTypeError.prototype); - return _this; - } - Object.defineProperty(BSONTypeError.prototype, "name", { - get: function () { - return 'BSONTypeError'; - }, - enumerable: false, - configurable: true - }); - return BSONTypeError; - }(TypeError)); - - function checkForMath(potentialGlobal) { - // eslint-disable-next-line eqeqeq - return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; - } - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - function getGlobal() { - // eslint-disable-next-line no-undef - return (checkForMath(typeof globalThis === 'object' && globalThis) || - checkForMath(typeof window === 'object' && window) || - checkForMath(typeof self === 'object' && self) || - checkForMath(typeof global === 'object' && global) || - Function('return this')()); - } - - /** - * Normalizes our expected stringified form of a function across versions of node - * @param fn - The function to stringify - */ - function normalizedFunctionString(fn) { - return fn.toString().replace('function(', 'function ('); - } - function isReactNative() { - var g = getGlobal(); - return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; - } - var insecureRandomBytes = function insecureRandomBytes(size) { - var insecureWarning = isReactNative() - ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' - : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; - console.warn(insecureWarning); - var result = buffer_1.alloc(size); - for (var i = 0; i < size; ++i) - result[i] = Math.floor(Math.random() * 256); - return result; - }; - var detectRandomBytes = function () { - if (typeof window !== 'undefined') { - // browser crypto implementation(s) - var target_1 = window.crypto || window.msCrypto; // allow for IE11 - if (target_1 && target_1.getRandomValues) { - return function (size) { return target_1.getRandomValues(buffer_1.alloc(size)); }; - } - } - if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { - // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global - return function (size) { return global.crypto.getRandomValues(buffer_1.alloc(size)); }; - } - var requiredRandomBytes; - try { - // eslint-disable-next-line @typescript-eslint/no-var-requires - requiredRandomBytes = require('crypto').randomBytes; - } - catch (e) { - // keep the fallback - } - // NOTE: in transpiled cases the above require might return null/undefined - return requiredRandomBytes || insecureRandomBytes; - }; - var randomBytes = detectRandomBytes(); - function isAnyArrayBuffer(value) { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); - } - function isUint8Array(value) { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; - } - function isBigInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigInt64Array]'; - } - function isBigUInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigUint64Array]'; - } - function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - } - function isMap(d) { - return Object.prototype.toString.call(d) === '[object Map]'; - } - // To ensure that 0.4 of node works correctly - function isDate(d) { - return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; - } - /** - * @internal - * this is to solve the `'someKey' in x` problem where x is unknown. - * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 - */ - function isObjectLike(candidate) { - return typeof candidate === 'object' && candidate !== null; - } - function deprecate(fn, message) { - var warned = false; - function deprecated() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!warned) { - console.warn(message); - warned = true; - } - return fn.apply(this, args); - } - return deprecated; - } - - /** - * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. - * - * @param potentialBuffer - The potential buffer - * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that - * wraps a passed in Uint8Array - * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in - */ - function ensureBuffer(potentialBuffer) { - if (ArrayBuffer.isView(potentialBuffer)) { - return buffer_1.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - if (isAnyArrayBuffer(potentialBuffer)) { - return buffer_1.from(potentialBuffer); - } - throw new BSONTypeError('Must use either Buffer or TypedArray'); - } - - // Validation regex for v4 uuid (validates with or without dashes) - var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; - var uuidValidateString = function (str) { - return typeof str === 'string' && VALIDATION_REGEX.test(str); - }; - var uuidHexStringToBuffer = function (hexString) { - if (!uuidValidateString(hexString)) { - throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); - } - var sanitizedHexString = hexString.replace(/-/g, ''); - return buffer_1.from(sanitizedHexString, 'hex'); - }; - var bufferToUuidHexString = function (buffer, includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - return includeDashes - ? buffer.toString('hex', 0, 4) + - '-' + - buffer.toString('hex', 4, 6) + - '-' + - buffer.toString('hex', 6, 8) + - '-' + - buffer.toString('hex', 8, 10) + - '-' + - buffer.toString('hex', 10, 16) - : buffer.toString('hex'); - }; - - var BYTE_LENGTH = 16; - var kId$1 = Symbol('id'); - /** - * A class representation of the BSON UUID type. - * @public - */ - var UUID = /** @class */ (function () { - /** - * Create an UUID type - * - * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. - */ - function UUID(input) { - if (typeof input === 'undefined') { - // The most common use case (blank id, new UUID() instance) - this.id = UUID.generate(); - } - else if (input instanceof UUID) { - this[kId$1] = buffer_1.from(input.id); - this.__id = input.__id; - } - else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { - this.id = ensureBuffer(input); - } - else if (typeof input === 'string') { - this.id = uuidHexStringToBuffer(input); - } - else { - throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); - } - } - Object.defineProperty(UUID.prototype, "id", { - /** - * The UUID bytes - * @readonly - */ - get: function () { - return this[kId$1]; - }, - set: function (value) { - this[kId$1] = value; - if (UUID.cacheHexString) { - this.__id = bufferToUuidHexString(value); - } - }, - enumerable: false, - configurable: true - }); - /** - * Generate a 16 byte uuid v4 buffer used in UUIDs - */ - /** - * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) - * @param includeDashes - should the string exclude dash-separators. - * */ - UUID.prototype.toHexString = function (includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - var uuidHexString = bufferToUuidHexString(this.id, includeDashes); - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - return uuidHexString; - }; - /** - * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. - */ - UUID.prototype.toString = function (encoding) { - return encoding ? this.id.toString(encoding) : this.toHexString(); - }; - /** - * Converts the id into its JSON string representation. - * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - */ - UUID.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this UUID with `otherID`. - * - * @param otherId - UUID instance to compare against. - */ - UUID.prototype.equals = function (otherId) { - if (!otherId) { - return false; - } - if (otherId instanceof UUID) { - return otherId.id.equals(this.id); - } - try { - return new UUID(otherId).id.equals(this.id); - } - catch (_a) { - return false; - } - }; - /** - * Creates a Binary instance from the current UUID. - */ - UUID.prototype.toBinary = function () { - return new Binary(this.id, Binary.SUBTYPE_UUID); - }; - /** - * Generates a populated buffer containing a v4 uuid - */ - UUID.generate = function () { - var bytes = randomBytes(BYTE_LENGTH); - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - return buffer_1.from(bytes); - }; - /** - * Checks if a value is a valid bson UUID - * @param input - UUID, string or Buffer to validate. - */ - UUID.isValid = function (input) { - if (!input) { - return false; - } - if (input instanceof UUID) { - return true; - } - if (typeof input === 'string') { - return uuidValidateString(input); - } - if (isUint8Array(input)) { - // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) - if (input.length !== BYTE_LENGTH) { - return false; - } - try { - // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx - // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx - return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; - } - catch (_a) { - return false; - } - } - return false; - }; - /** - * Creates an UUID from a hex string representation of an UUID. - * @param hexString - 32 or 36 character hex string (dashes excluded/included). - */ - UUID.createFromHexString = function (hexString) { - var buffer = uuidHexStringToBuffer(hexString); - return new UUID(buffer); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 36 character hex string representation. - * @internal - */ - UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - UUID.prototype.inspect = function () { - return "new UUID(\"" + this.toHexString() + "\")"; - }; - return UUID; - }()); - Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); - - /** - * A class representation of the BSON Binary type. - * @public - */ - var Binary = /** @class */ (function () { - /** - * @param buffer - a buffer object containing the binary data. - * @param subType - the option binary type. - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) - return new Binary(buffer, subType); - if (!(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer)) { - throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); - } - this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer == null) { - // create an empty binary buffer - this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE); - this.position = 0; - } - else { - if (typeof buffer === 'string') { - // string - this.buffer = buffer_1.from(buffer, 'binary'); - } - else if (Array.isArray(buffer)) { - // number[] - this.buffer = buffer_1.from(buffer); - } - else { - // Buffer | TypedArray | ArrayBuffer - this.buffer = ensureBuffer(buffer); - } - this.position = this.buffer.byteLength; - } - } - /** - * Updates this binary with byte_value. - * - * @param byteValue - a single byte we wish to write. - */ - Binary.prototype.put = function (byteValue) { - // If it's a string and a has more than one character throw an error - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new BSONTypeError('only accepts single character String'); - } - else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new BSONTypeError('only accepts single character Uint8Array or Array'); - // Decode the byte value once - var decodedByte; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } - else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } - else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); - } - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decodedByte; - } - else { - var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decodedByte; - } - }; - /** - * Writes a buffer or string to the binary. - * - * @param sequence - a string or buffer to be written to the Binary BSON object. - * @param offset - specify the binary of where to write the content. - */ - Binary.prototype.write = function (sequence, offset) { - offset = typeof offset === 'number' ? offset : this.position; - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + sequence.length) { - var buffer = buffer_1.alloc(this.buffer.length + sequence.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - // Assign the new buffer - this.buffer = buffer; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ensureBuffer(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } - else if (typeof sequence === 'string') { - this.buffer.write(sequence, offset, sequence.length, 'binary'); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - }; - /** - * Reads **length** bytes starting at **position**. - * - * @param position - read from the given position in the Binary. - * @param length - the number of bytes to read. - */ - Binary.prototype.read = function (position, length) { - length = length && length > 0 ? length : this.position; - // Let's return the data based on the type we have - return this.buffer.slice(position, position + length); - }; - /** - * Returns the value of this binary as a string. - * @param asRaw - Will skip converting to a string - * @remarks - * This is handy when calling this function conditionally for some key value pairs and not others - */ - Binary.prototype.value = function (asRaw) { - asRaw = !!asRaw; - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - // If it's a node.js buffer object - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return this.buffer.toString('binary', 0, this.position); - }; - /** the length of the binary sequence */ - Binary.prototype.length = function () { - return this.position; - }; - Binary.prototype.toJSON = function () { - return this.buffer.toString('base64'); - }; - Binary.prototype.toString = function (format) { - return this.buffer.toString(format); - }; - /** @internal */ - Binary.prototype.toExtendedJSON = function (options) { - options = options || {}; - var base64String = this.buffer.toString('base64'); - var subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - }; - Binary.prototype.toUUID = function () { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID(this.buffer.slice(0, this.position)); - } - throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); - }; - /** @internal */ - Binary.fromExtendedJSON = function (doc, options) { - options = options || {}; - var data; - var type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = buffer_1.from(doc.$binary, 'base64'); - } - else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = buffer_1.from(doc.$binary.base64, 'base64'); - } - } - } - else if ('$uuid' in doc) { - type = 4; - data = uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); - } - return new Binary(data, type); - }; - /** @internal */ - Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Binary.prototype.inspect = function () { - var asBuffer = this.value(true); - return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; - }; - /** - * Binary default subtype - * @internal - */ - Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** Initial buffer default size */ - Binary.BUFFER_SIZE = 256; - /** Default BSON type */ - Binary.SUBTYPE_DEFAULT = 0; - /** Function BSON type */ - Binary.SUBTYPE_FUNCTION = 1; - /** Byte Array BSON type */ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ - Binary.SUBTYPE_UUID_OLD = 3; - /** UUID BSON type */ - Binary.SUBTYPE_UUID = 4; - /** MD5 BSON type */ - Binary.SUBTYPE_MD5 = 5; - /** Encrypted BSON type */ - Binary.SUBTYPE_ENCRYPTED = 6; - /** Column BSON type */ - Binary.SUBTYPE_COLUMN = 7; - /** User BSON type */ - Binary.SUBTYPE_USER_DEFINED = 128; - return Binary; - }()); - Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); - - /** - * A class representation of the BSON Code type. - * @public - */ - var Code = /** @class */ (function () { - /** - * @param code - a string or function. - * @param scope - an optional scope for the function. - */ - function Code(code, scope) { - if (!(this instanceof Code)) - return new Code(code, scope); - this.code = code; - this.scope = scope; - } - Code.prototype.toJSON = function () { - return { code: this.code, scope: this.scope }; - }; - /** @internal */ - Code.prototype.toExtendedJSON = function () { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - }; - /** @internal */ - Code.fromExtendedJSON = function (doc) { - return new Code(doc.$code, doc.$scope); - }; - /** @internal */ - Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Code.prototype.inspect = function () { - var codeJson = this.toJSON(); - return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; - }; - return Code; - }()); - Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); - - /** @internal */ - function isDBRefLike(value) { - return (isObjectLike(value) && - value.$id != null && - typeof value.$ref === 'string' && - (value.$db == null || typeof value.$db === 'string')); - } - /** - * A class representation of the BSON DBRef type. - * @public - */ - var DBRef = /** @class */ (function () { - /** - * @param collection - the collection name. - * @param oid - the reference ObjectId. - * @param db - optional db name, if omitted the reference is local to the current db. - */ - function DBRef(collection, oid, db, fields) { - if (!(this instanceof DBRef)) - return new DBRef(collection, oid, db, fields); - // check if namespace has been provided - var parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - Object.defineProperty(DBRef.prototype, "namespace", { - // Property provided for compatibility with the 1.x parser - // the 1.x parser used a "namespace" property, while 4.x uses "collection" - /** @internal */ - get: function () { - return this.collection; - }, - set: function (value) { - this.collection = value; - }, - enumerable: false, - configurable: true - }); - DBRef.prototype.toJSON = function () { - var o = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o.$db = this.db; - return o; - }; - /** @internal */ - DBRef.prototype.toExtendedJSON = function (options) { - options = options || {}; - var o = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o; - } - if (this.db) - o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - }; - /** @internal */ - DBRef.fromExtendedJSON = function (doc) { - var copy = Object.assign({}, doc); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - }; - /** @internal */ - DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - DBRef.prototype.inspect = function () { - // NOTE: if OID is an ObjectId class it will just print the oid string. - var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; - }; - return DBRef; - }()); - Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); - - /** - * wasm optimizations, to do native i64 multiplication and divide - */ - var wasm = undefined; - try { - wasm = new WebAssembly.Instance(new WebAssembly.Module( - // prettier-ignore - new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; - } - catch (_a) { - // no wasm support - } - var TWO_PWR_16_DBL = 1 << 16; - var TWO_PWR_24_DBL = 1 << 24; - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - /** A cache of the Long representations of small integer values. */ - var INT_CACHE = {}; - /** A cache of the Long representations of small unsigned integer values. */ - var UINT_CACHE = {}; - /** - * A class representing a 64-bit integer - * @public - * @remarks - * The internal representation of a long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16 bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. - */ - var Long = /** @class */ (function () { - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * - * Acceptable signatures are: - * - Long(low, high, unsigned?) - * - Long(bigint, unsigned?) - * - Long(string, unsigned?) - * - * @param low - The low (signed) 32 bits of the long - * @param high - The high (signed) 32 bits of the long - * @param unsigned - Whether unsigned or not, defaults to signed - */ - function Long(low, high, unsigned) { - if (low === void 0) { low = 0; } - if (!(this instanceof Long)) - return new Long(low, high, unsigned); - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } - else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } - else { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - Object.defineProperty(this, '__isLong__', { - value: true, - configurable: false, - writable: false, - enumerable: false - }); - } - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. - * Each is assumed to use 32 bits. - * @param lowBits - The low 32 bits - * @param highBits - The high 32 bits - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBits = function (lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - }; - /** - * Returns a Long representing the given 32 bit integer value. - * @param value - The 32 bit integer in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromInt = function (value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } - else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromNumber = function (value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } - else { - if (value <= -TWO_PWR_63_DBL) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; - } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBigInt = function (value, unsigned) { - return Long.fromString(value.toString(), unsigned); - }; - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param str - The textual representation of the Long - * @param unsigned - Whether unsigned or not, defaults to signed - * @param radix - The radix in which the text is written (2-36), defaults to 10 - * @returns The corresponding Long value - */ - Long.fromString = function (str, unsigned, radix) { - if (str.length === 0) - throw Error('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - (radix = unsigned), (unsigned = false); - } - else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - var p; - if ((p = str.indexOf('-')) > 0) - throw Error('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } - else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - }; - /** - * Creates a Long from its byte representation. - * @param bytes - Byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @param le - Whether little or big endian, defaults to big endian - * @returns The corresponding Long value - */ - Long.fromBytes = function (bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - }; - /** - * Creates a Long from its little endian byte representation. - * @param bytes - Little endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesLE = function (bytes, unsigned) { - return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); - }; - /** - * Creates a Long from its big endian byte representation. - * @param bytes - Big endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesBE = function (bytes, unsigned) { - return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); - }; - /** - * Tests if the specified object is a Long. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Long.isLong = function (value) { - return isObjectLike(value) && value['__isLong__'] === true; - }; - /** - * Converts the specified value to a Long. - * @param unsigned - Whether unsigned or not, defaults to signed - */ - Long.fromValue = function (val, unsigned) { - if (typeof val === 'number') - return Long.fromNumber(val, unsigned); - if (typeof val === 'string') - return Long.fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); - }; - /** Returns the sum of this and the specified Long. */ - Long.prototype.add = function (addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** - * Returns the sum of this and the specified Long. - * @returns Sum - */ - Long.prototype.and = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - /** - * Compares this Long's value with the specified's. - * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater - */ - Long.prototype.compare = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - // At this point the sign bits are the same - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; - /** This is an alias of {@link Long.compare} */ - Long.prototype.comp = function (other) { - return this.compare(other); - }; - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. - * @returns Quotient - */ - Long.prototype.divide = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw Error('division by zero'); - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if (!this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } - else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } - else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } - else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } - else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return Long.UONE; - res = Long.UZERO; - } - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - /**This is an alias of {@link Long.divide} */ - Long.prototype.div = function (divisor) { - return this.divide(divisor); - }; - /** - * Tests if this Long's value equals the specified's. - * @param other - Other value - */ - Long.prototype.equals = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - /** This is an alias of {@link Long.equals} */ - Long.prototype.eq = function (other) { - return this.equals(other); - }; - /** Gets the high 32 bits as a signed integer. */ - Long.prototype.getHighBits = function () { - return this.high; - }; - /** Gets the high 32 bits as an unsigned integer. */ - Long.prototype.getHighBitsUnsigned = function () { - return this.high >>> 0; - }; - /** Gets the low 32 bits as a signed integer. */ - Long.prototype.getLowBits = function () { - return this.low; - }; - /** Gets the low 32 bits as an unsigned integer. */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low >>> 0; - }; - /** Gets the number of bits needed to represent the absolute value of this Long. */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - // Unsigned Longs are never negative - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - var val = this.high !== 0 ? this.high : this.low; - var bit; - for (bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - }; - /** Tests if this Long's value is greater than the specified's. */ - Long.prototype.greaterThan = function (other) { - return this.comp(other) > 0; - }; - /** This is an alias of {@link Long.greaterThan} */ - Long.prototype.gt = function (other) { - return this.greaterThan(other); - }; - /** Tests if this Long's value is greater than or equal the specified's. */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.comp(other) >= 0; - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.gte = function (other) { - return this.greaterThanOrEqual(other); - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.ge = function (other) { - return this.greaterThanOrEqual(other); - }; - /** Tests if this Long's value is even. */ - Long.prototype.isEven = function () { - return (this.low & 1) === 0; - }; - /** Tests if this Long's value is negative. */ - Long.prototype.isNegative = function () { - return !this.unsigned && this.high < 0; - }; - /** Tests if this Long's value is odd. */ - Long.prototype.isOdd = function () { - return (this.low & 1) === 1; - }; - /** Tests if this Long's value is positive. */ - Long.prototype.isPositive = function () { - return this.unsigned || this.high >= 0; - }; - /** Tests if this Long's value equals zero. */ - Long.prototype.isZero = function () { - return this.high === 0 && this.low === 0; - }; - /** Tests if this Long's value is less than the specified's. */ - Long.prototype.lessThan = function (other) { - return this.comp(other) < 0; - }; - /** This is an alias of {@link Long#lessThan}. */ - Long.prototype.lt = function (other) { - return this.lessThan(other); - }; - /** Tests if this Long's value is less than or equal the specified's. */ - Long.prototype.lessThanOrEqual = function (other) { - return this.comp(other) <= 0; - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.lte = function (other) { - return this.lessThanOrEqual(other); - }; - /** Returns this Long modulo the specified. */ - Long.prototype.modulo = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.mod = function (divisor) { - return this.modulo(divisor); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.rem = function (divisor) { - return this.modulo(divisor); - }; - /** - * Returns the product of this and the specified Long. - * @param multiplier - Multiplier - * @returns Product - */ - Long.prototype.multiply = function (multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - // use wasm support if present - if (wasm) { - var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } - else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - // If both longs are small, use float multiplication - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** This is an alias of {@link Long.multiply} */ - Long.prototype.mul = function (multiplier) { - return this.multiply(multiplier); - }; - /** Returns the Negation of this Long's value. */ - Long.prototype.negate = function () { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); - }; - /** This is an alias of {@link Long.negate} */ - Long.prototype.neg = function () { - return this.negate(); - }; - /** Returns the bitwise NOT of this Long. */ - Long.prototype.not = function () { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - }; - /** Tests if this Long's value differs from the specified's. */ - Long.prototype.notEquals = function (other) { - return !this.equals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.neq = function (other) { - return this.notEquals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.ne = function (other) { - return this.notEquals(other); - }; - /** - * Returns the bitwise OR of this Long and the specified. - */ - Long.prototype.or = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftLeft = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - }; - /** This is an alias of {@link Long.shiftLeft} */ - Long.prototype.shl = function (numBits) { - return this.shiftLeft(numBits); - }; - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRight = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - }; - /** This is an alias of {@link Long.shiftRight} */ - Long.prototype.shr = function (numBits) { - return this.shiftRight(numBits); - }; - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } - else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shr_u = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shru = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** - * Returns the difference of this and the specified Long. - * @param subtrahend - Subtrahend - * @returns Difference - */ - Long.prototype.subtract = function (subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - /** This is an alias of {@link Long.subtract} */ - Long.prototype.sub = function (subtrahend) { - return this.subtract(subtrahend); - }; - /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ - Long.prototype.toInt = function () { - return this.unsigned ? this.low >>> 0 : this.low; - }; - /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ - Long.prototype.toNumber = function () { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - /** Converts the Long to a BigInt (arbitrary precision). */ - Long.prototype.toBigInt = function () { - return BigInt(this.toString()); - }; - /** - * Converts this Long to its byte representation. - * @param le - Whether little or big endian, defaults to big endian - * @returns Byte representation - */ - Long.prototype.toBytes = function (le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - /** - * Converts this Long to its little endian byte representation. - * @returns Little endian byte representation - */ - Long.prototype.toBytesLE = function () { - var hi = this.high, lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - }; - /** - * Converts this Long to its big endian byte representation. - * @returns Big endian byte representation - */ - Long.prototype.toBytesBE = function () { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - }; - /** - * Converts this Long to signed. - */ - Long.prototype.toSigned = function () { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); - }; - /** - * Converts the Long to a string written in the specified radix. - * @param radix - Radix (2-36), defaults to 10 - * @throws RangeError If `radix` is out of range - */ - Long.prototype.toString = function (radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } - else - return '-' + this.neg().toString(radix); - } - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - // eslint-disable-next-line @typescript-eslint/no-this-alias - var rem = this; - var result = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - var digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - }; - /** Converts this Long to unsigned. */ - Long.prototype.toUnsigned = function () { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - }; - /** Returns the bitwise XOR of this Long and the given one. */ - Long.prototype.xor = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - /** This is an alias of {@link Long.isZero} */ - Long.prototype.eqz = function () { - return this.isZero(); - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.le = function (other) { - return this.lessThanOrEqual(other); - }; - /* - **************************************************************** - * BSON SPECIFIC ADDITIONS * - **************************************************************** - */ - Long.prototype.toExtendedJSON = function (options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; - }; - Long.fromExtendedJSON = function (doc, options) { - var result = Long.fromString(doc.$numberLong); - return options && options.relaxed ? result.toNumber() : result; - }; - /** @internal */ - Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Long.prototype.inspect = function () { - return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; - }; - Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); - /** Maximum unsigned value. */ - Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); - /** Signed zero */ - Long.ZERO = Long.fromInt(0); - /** Unsigned zero. */ - Long.UZERO = Long.fromInt(0, true); - /** Signed one. */ - Long.ONE = Long.fromInt(1); - /** Unsigned one. */ - Long.UONE = Long.fromInt(1, true); - /** Signed negative one. */ - Long.NEG_ONE = Long.fromInt(-1); - /** Maximum signed value. */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - /** Minimum signed value. */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - return Long; - }()); - Object.defineProperty(Long.prototype, '__isLong__', { value: true }); - Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); - - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - ].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - ].reverse(); - var INF_POSITIVE_BUFFER = [ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - ].reverse(); - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Detect if the value is a digit - function isDigit(value) { - return !isNaN(parseInt(value, 10)); - } - // Divide two uint128 values - function divideu128(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (var i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - return { quotient: value, rem: _rem }; - } - // Multiply two Long values and return the 128 bit value - function multiply64x2(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - // Return the 128 bit result - return { high: productHigh, low: productLow }; - } - function lessThan(left, right) { - // Make values unsigned - var uhleft = left.high >>> 0; - var uhright = right.high >>> 0; - // Compare high bits first - if (uhleft < uhright) { - return true; - } - else if (uhleft === uhright) { - var ulleft = left.low >>> 0; - var ulright = right.low >>> 0; - if (ulleft < ulright) - return true; - } - return false; - } - function invalidErr(string, message) { - throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); - } - /** - * A class representation of the BSON Decimal128 type. - * @public - */ - var Decimal128 = /** @class */ (function () { - /** - * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, - * or a string representation as returned by .toString() - */ - function Decimal128(bytes) { - if (!(this instanceof Decimal128)) - return new Decimal128(bytes); - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } - else { - this.bytes = bytes; - } - } - /** - * Create a Decimal128 instance from a string representation - * - * @param representation - a numeric string representation. - */ - Decimal128.fromString = function (representation) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = new Long(0, 0); - // The low 17 digits of the significand - var significandLow = new Long(0, 0); - // The biased exponent - var biasedExponent = 0; - // Read index - var index = 0; - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (representation.length >= 7000) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - // Results - var stringMatch = representation.match(PARSE_STRING_REGEXP); - var infMatch = representation.match(PARSE_INF_REGEXP); - var nanMatch = representation.match(PARSE_NAN_REGEXP); - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - if (stringMatch) { - // full_match = stringMatch[0] - // sign = stringMatch[1] - var unsignedNumber = stringMatch[2]; - // stringMatch[3] is undefined if a whole number (ex "1", 12") - // but defined if a number w/ decimal in it (ex "1.0, 12.2") - var e = stringMatch[4]; - var expSign = stringMatch[5]; - var expNumber = stringMatch[6]; - // they provided e, but didn't give an exponent number. for ex "1e" - if (e && expNumber === undefined) - invalidErr(representation, 'missing exponent power'); - // they provided e, but didn't give a number before it. for ex "e1" - if (e && unsignedNumber === undefined) - invalidErr(representation, 'missing exponent base'); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - // Get the negative or positive sign - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - // Check if user passed Infinity or NaN - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - else if (representation[index] === 'N') { - return new Decimal128(buffer_1.from(NAN_BUFFER)); - } - } - // Read all the digits - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) - invalidErr(representation, 'contains multiple periods'); - sawRadix = true; - index = index + 1; - continue; - } - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - // Only store 34 digits - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - if (sawRadix && !nDigitsRead) - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - // Read exponent if exists - if (representation[index] === 'e' || representation[index] === 'E') { - // Read exponent digits - var match = representation.substr(++index).match(EXPONENT_REGEX); - // No digits read - if (!match || !match[2]) - return new Decimal128(buffer_1.from(NAN_BUFFER)); - // Get exponent - exponent = parseInt(match[0], 10); - // Adjust the index - index = index + match[0].length; - } - // Return not a number - if (representation[index]) - return new Decimal128(buffer_1.from(NAN_BUFFER)); - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } - else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } - else { - exponent = exponent - radixPosition; - } - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit. can only do this if < significant digits than # stored. - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } - else { - // adjust to round - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } - else { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits) { - var endOfString = nDigitsRead; - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - // if negative, we need to increment again to account for - sign at start. - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - var dIdx = lastDigit; - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } - else { - return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - } - } - } - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } - else if (lastDigit - firstDigit < 17) { - var dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - else { - var dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - significandLow = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } - else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - dec.low = significand.low; - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - // Encode into a buffer - var buffer = buffer_1.alloc(16); - index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - // Return the new Decimal128 - return new Decimal128(buffer); - }; - /** Create a string representation of the raw Decimal128 value */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) - significand[i] = 0; - // read pointer into significand - var index = 0; - // true if the number is zero - var is_zero = false; - // the most significant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: [0, 0, 0, 0] }; - // indexing variables - var j, k; - // Output string - var string = []; - // Unpack index - index = 0; - // Buffer reference - var buffer = this.bytes; - // Unpack the low 64bits into a long - // bits 96 - 127 - var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 64 - 95 - var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack the high 64bits into a long - // bits 32 - 63 - var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 0 - 31 - var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack index - index = 0; - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - // Decode combination field and exponent - // bits 1 - 5 - var combination = (high >> 26) & COMBINATION_MASK; - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } - else if (combination === COMBINATION_NAN) { - return 'NaN'; - } - else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } - else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - // unbiased exponent - var exponent = biased_exponent - EXPONENT_BIAS; - // Create string of significand digits - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0) { - is_zero = true; - } - else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Perform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) - continue; - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } - else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - // the exponent if scientific notation is used - var scientific_exponent = significand_digits - 1 + exponent; - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - // if there are too many significant digits, we should just be treating numbers - // as + or - 0 and using the non-scientific exponent (this is for the "invalid - // representation should be treated as 0/-0" spec cases in decimal128-1.json) - if (significand_digits > 34) { - string.push("" + 0); - if (exponent > 0) - string.push('E+' + exponent); - else if (exponent < 0) - string.push('E' + exponent); - return string.join(''); - } - string.push("" + significand[index++]); - significand_digits = significand_digits - 1; - if (significand_digits) { - string.push('.'); - } - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } - else { - string.push("" + scientific_exponent); - } - } - else { - // Regular format with no decimal place - if (exponent >= 0) { - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - } - else { - var radix_position = significand_digits + exponent; - // non-zero digits before radix - if (radix_position > 0) { - for (var i = 0; i < radix_position; i++) { - string.push("" + significand[index++]); - } - } - else { - string.push('0'); - } - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push("" + significand[index++]); - } - } - } - return string.join(''); - }; - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.prototype.toExtendedJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.fromExtendedJSON = function (doc) { - return Decimal128.fromString(doc.$numberDecimal); - }; - /** @internal */ - Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Decimal128.prototype.inspect = function () { - return "new Decimal128(\"" + this.toString() + "\")"; - }; - return Decimal128; - }()); - Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); - - /** - * A class representation of the BSON Double type. - * @public - */ - var Double = /** @class */ (function () { - /** - * Create a Double type - * - * @param value - the number we want to represent as a double. - */ - function Double(value) { - if (!(this instanceof Double)) - return new Double(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; - } - /** - * Access the number value. - * - * @returns returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - Double.prototype.toJSON = function () { - return this.value; - }; - Double.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - /** @internal */ - Double.prototype.toExtendedJSON = function (options) { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user - // explicitly provided `-0` then we need to ensure the sign makes it into the output - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: "-" + this.value.toFixed(1) }; - } - var $numberDouble; - if (Number.isInteger(this.value)) { - $numberDouble = this.value.toFixed(1); - if ($numberDouble.length >= 13) { - $numberDouble = this.value.toExponential(13).toUpperCase(); - } - } - else { - $numberDouble = this.value.toString(); - } - return { $numberDouble: $numberDouble }; - }; - /** @internal */ - Double.fromExtendedJSON = function (doc, options) { - var doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - }; - /** @internal */ - Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Double.prototype.inspect = function () { - var eJSON = this.toExtendedJSON(); - return "new Double(" + eJSON.$numberDouble + ")"; - }; - return Double; - }()); - Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); - - /** - * A class representation of a BSON Int32 type. - * @public - */ - var Int32 = /** @class */ (function () { - /** - * Create an Int32 type - * - * @param value - the number we want to represent as an int32. - */ - function Int32(value) { - if (!(this instanceof Int32)) - return new Int32(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value | 0; - } - /** - * Access the number value. - * - * @returns returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - Int32.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - Int32.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - Int32.prototype.toExtendedJSON = function (options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; - }; - /** @internal */ - Int32.fromExtendedJSON = function (doc, options) { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - }; - /** @internal */ - Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Int32.prototype.inspect = function () { - return "new Int32(" + this.valueOf() + ")"; - }; - return Int32; - }()); - Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); - - /** - * A class representation of the BSON MaxKey type. - * @public - */ - var MaxKey = /** @class */ (function () { - function MaxKey() { - if (!(this instanceof MaxKey)) - return new MaxKey(); - } - /** @internal */ - MaxKey.prototype.toExtendedJSON = function () { - return { $maxKey: 1 }; - }; - /** @internal */ - MaxKey.fromExtendedJSON = function () { - return new MaxKey(); - }; - /** @internal */ - MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MaxKey.prototype.inspect = function () { - return 'new MaxKey()'; - }; - return MaxKey; - }()); - Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); - - /** - * A class representation of the BSON MinKey type. - * @public - */ - var MinKey = /** @class */ (function () { - function MinKey() { - if (!(this instanceof MinKey)) - return new MinKey(); - } - /** @internal */ - MinKey.prototype.toExtendedJSON = function () { - return { $minKey: 1 }; - }; - /** @internal */ - MinKey.fromExtendedJSON = function () { - return new MinKey(); - }; - /** @internal */ - MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MinKey.prototype.inspect = function () { - return 'new MinKey()'; - }; - return MinKey; - }()); - Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); - - // Regular expression that checks for hex value - var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - // Unique sequence for the current process (initialized on first use) - var PROCESS_UNIQUE = null; - var kId = Symbol('id'); - /** - * A class representation of the BSON ObjectId type. - * @public - */ - var ObjectId = /** @class */ (function () { - /** - * Create an ObjectId type - * - * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. - */ - function ObjectId(inputId) { - if (!(this instanceof ObjectId)) - return new ObjectId(inputId); - // workingId is set based on type of input and whether valid id exists for the input - var workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer'); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = buffer_1.from(inputId.toHexString(), 'hex'); - } - else { - workingId = inputId.id; - } - } - else { - workingId = inputId; - } - // the following cases use workingId to construct an ObjectId - if (workingId == null || typeof workingId === 'number') { - // The most common use case (blank id, new objectId instance) - // Generate a new id - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } - else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ensureBuffer(workingId); - } - else if (typeof workingId === 'string') { - if (workingId.length === 12) { - var bytes = buffer_1.from(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes'); - } - } - else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = buffer_1.from(workingId, 'hex'); - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters'); - } - } - else { - throw new BSONTypeError('Argument passed in does not match the accepted types'); - } - // If we are caching the hex string - if (ObjectId.cacheHexString) { - this.__id = this.id.toString('hex'); - } - } - Object.defineProperty(ObjectId.prototype, "id", { - /** - * The ObjectId bytes - * @readonly - */ - get: function () { - return this[kId]; - }, - set: function (value) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = value.toString('hex'); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectId.prototype, "generationTime", { - /** - * The generation time of this ObjectId instance - * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch - */ - get: function () { - return this.id.readInt32BE(0); - }, - set: function (value) { - // Encode time into first 4 bytes - this.id.writeUInt32BE(value, 0); - }, - enumerable: false, - configurable: true - }); - /** Returns the ObjectId id as a 24 character hex string representation */ - ObjectId.prototype.toHexString = function () { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - var hexString = this.id.toString('hex'); - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - return hexString; - }; - /** - * Update the ObjectId index - * @privateRemarks - * Used in generating new ObjectId's on the driver - * @internal - */ - ObjectId.getInc = function () { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - }; - /** - * Generate a 12 byte id buffer used in ObjectId's - * - * @param time - pass in a second based timestamp. - */ - ObjectId.generate = function (time) { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - var inc = ObjectId.getInc(); - var buffer = buffer_1.alloc(12); - // 4-byte timestamp - buffer.writeUInt32BE(time, 0); - // set PROCESS_UNIQUE if yet not initialized - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = randomBytes(5); - } - // 5-byte process unique - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - // 3-byte counter - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - return buffer; - }; - /** - * Converts the id into a 24 character hex string for printing - * - * @param format - The Buffer toString format parameter. - */ - ObjectId.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (format) - return this.id.toString(format); - return this.toHexString(); - }; - /** Converts to its JSON the 24 character hex string representation. */ - ObjectId.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this ObjectId with `otherID`. - * - * @param otherId - ObjectId instance to compare against. - */ - ObjectId.prototype.equals = function (otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (otherId instanceof ObjectId) { - return this.toString() === otherId.toString(); - } - if (typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - isUint8Array(this.id)) { - return otherId === buffer_1.prototype.toString.call(this.id, 'latin1'); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return buffer_1.from(otherId).equals(this.id); - } - if (typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function') { - return otherId.toHexString() === this.toHexString(); - } - return false; - }; - /** Returns the generation date (accurate up to the second) that this ID was generated. */ - ObjectId.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id.readUInt32BE(0); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - /** @internal */ - ObjectId.createPk = function () { - return new ObjectId(); - }; - /** - * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. - * - * @param time - an integer number representing a number of seconds. - */ - ObjectId.createFromTime = function (time) { - var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer.writeUInt32BE(time, 0); - // Return the new objectId - return new ObjectId(buffer); - }; - /** - * Creates an ObjectId from a hex string representation of an ObjectId. - * - * @param hexString - create a ObjectId from a passed in 24 character hexstring. - */ - ObjectId.createFromHexString = function (hexString) { - // Throw an error if it's not a valid setup - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - return new ObjectId(buffer_1.from(hexString, 'hex')); - }; - /** - * Checks if a value is a valid bson ObjectId - * - * @param id - ObjectId instance to validate. - */ - ObjectId.isValid = function (id) { - if (id == null) - return false; - if (typeof id === 'number') { - return true; - } - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - if (id instanceof ObjectId) { - return true; - } - if (isUint8Array(id) && id.length === 12) { - return true; - } - // Duck-Typing detection of ObjectId like objects - if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { - if (typeof id.id === 'string') { - return id.id.length === 12; - } - return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); - } - return false; - }; - /** @internal */ - ObjectId.prototype.toExtendedJSON = function () { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - }; - /** @internal */ - ObjectId.fromExtendedJSON = function (doc) { - return new ObjectId(doc.$oid); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 24 character hex string representation. - * @internal - */ - ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - ObjectId.prototype.inspect = function () { - return "new ObjectId(\"" + this.toHexString() + "\")"; - }; - /** @internal */ - ObjectId.index = Math.floor(Math.random() * 0xffffff); - return ObjectId; - }()); - // Deprecated methods - Object.defineProperty(ObjectId.prototype, 'generate', { - value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') - }); - Object.defineProperty(ObjectId.prototype, 'getInc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') - }); - Object.defineProperty(ObjectId.prototype, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') - }); - Object.defineProperty(ObjectId, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') - }); - Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); - - function alphabetize(str) { - return str.split('').sort().join(''); - } - /** - * A class representation of the BSON RegExp type. - * @public - */ - var BSONRegExp = /** @class */ (function () { - /** - * @param pattern - The regular expression pattern to match - * @param options - The regular expression options - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) - return new BSONRegExp(pattern, options); - this.pattern = pattern; - this.options = alphabetize(options !== null && options !== void 0 ? options : ''); - if (this.pattern.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); - } - if (this.options.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); - } - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u')) { - throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); - } - } - } - BSONRegExp.parseOptions = function (options) { - return options ? options.split('').sort().join('') : ''; - }; - /** @internal */ - BSONRegExp.prototype.toExtendedJSON = function (options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - }; - /** @internal */ - BSONRegExp.fromExtendedJSON = function (doc) { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - // This is for $regex query operators that have extended json values. - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc; - } - } - else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); - } - throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); - }; - return BSONRegExp; - }()); - Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); - - /** - * A class representation of the BSON Symbol type. - * @public - */ - var BSONSymbol = /** @class */ (function () { - /** - * @param value - the string representing the symbol. - */ - function BSONSymbol(value) { - if (!(this instanceof BSONSymbol)) - return new BSONSymbol(value); - this.value = value; - } - /** Access the wrapped string value. */ - BSONSymbol.prototype.valueOf = function () { - return this.value; - }; - BSONSymbol.prototype.toString = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.inspect = function () { - return "new BSONSymbol(\"" + this.value + "\")"; - }; - BSONSymbol.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.toExtendedJSON = function () { - return { $symbol: this.value }; - }; - /** @internal */ - BSONSymbol.fromExtendedJSON = function (doc) { - return new BSONSymbol(doc.$symbol); - }; - /** @internal */ - BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - return BSONSymbol; - }()); - Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); - - /** @public */ - var LongWithoutOverridesClass = Long; - /** @public */ - var Timestamp = /** @class */ (function (_super) { - __extends(Timestamp, _super); - function Timestamp(low, high) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - ///@ts-expect-error - if (!(_this instanceof Timestamp)) - return new Timestamp(low, high); - if (Long.isLong(low)) { - _this = _super.call(this, low.low, low.high, true) || this; - } - else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { - _this = _super.call(this, low.i, low.t, true) || this; - } - else { - _this = _super.call(this, low, high, true) || this; - } - Object.defineProperty(_this, '_bsontype', { - value: 'Timestamp', - writable: false, - configurable: false, - enumerable: false - }); - return _this; - } - Timestamp.prototype.toJSON = function () { - return { - $timestamp: this.toString() - }; - }; - /** Returns a Timestamp represented by the given (32-bit) integer value. */ - Timestamp.fromInt = function (value) { - return new Timestamp(Long.fromInt(value, true)); - }; - /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ - Timestamp.fromNumber = function (value) { - return new Timestamp(Long.fromNumber(value, true)); - }; - /** - * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. - * - * @param lowBits - the low 32-bits. - * @param highBits - the high 32-bits. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - /** - * Returns a Timestamp from the given string, optionally using the given radix. - * - * @param str - the textual representation of the Timestamp. - * @param optRadix - the radix in which the text is written. - */ - Timestamp.fromString = function (str, optRadix) { - return new Timestamp(Long.fromString(str, true, optRadix)); - }; - /** @internal */ - Timestamp.prototype.toExtendedJSON = function () { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - }; - /** @internal */ - Timestamp.fromExtendedJSON = function (doc) { - return new Timestamp(doc.$timestamp); - }; - /** @internal */ - Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Timestamp.prototype.inspect = function () { - return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; - }; - Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - return Timestamp; - }(LongWithoutOverridesClass)); - - function isBSONType(value) { - return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); - } - // INT32 boundaries - var BSON_INT32_MAX$1 = 0x7fffffff; - var BSON_INT32_MIN$1 = -0x80000000; - // INT64 boundaries - var BSON_INT64_MAX$1 = 0x7fffffffffffffff; - var BSON_INT64_MIN$1 = -0x8000000000000000; - // all the types where we don't need to do any special processing and can just pass the EJSON - //straight to type.fromExtendedJSON - var keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp - }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function deserializeValue(value, options) { - if (options === void 0) { options = {}; } - if (typeof value === 'number') { - if (options.relaxed || options.legacy) { - return value; - } - // if it's an integer, should interpret as smallest BSON integer - // that can represent it exactly. (if out of range, interpret as double.) - if (Math.floor(value) === value) { - if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) - return new Int32(value); - if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) - return Long.fromNumber(value); - } - // If the number is a non-integer or out of integer range, should interpret as BSON Double. - return new Double(value); - } - // from here on out we're looking for bson types, so bail if its not an object - if (value == null || typeof value !== 'object') - return value; - // upgrade deprecated undefined to null - if (value.$undefined) - return null; - var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); - for (var i = 0; i < keys.length; i++) { - var c = keysToCodecs[keys[i]]; - if (c) - return c.fromExtendedJSON(value, options); - } - if (value.$date != null) { - var d = value.$date; - var date = new Date(); - if (options.legacy) { - if (typeof d === 'number') - date.setTime(d); - else if (typeof d === 'string') - date.setTime(Date.parse(d)); - } - else { - if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (Long.isLong(d)) - date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) - date.setTime(d); - } - return date; - } - if (value.$code != null) { - var copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return Code.fromExtendedJSON(value); - } - if (isDBRefLike(value) || value.$dbPointer) { - var v = value.$ref ? value : value.$dbPointer; - // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) - // because of the order JSON.parse goes through the document - if (v instanceof DBRef) - return v; - var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); - var valid_1 = true; - dollarKeys.forEach(function (k) { - if (['$ref', '$id', '$db'].indexOf(k) === -1) - valid_1 = false; - }); - // only make DBRef if $ keys are all valid - if (valid_1) - return DBRef.fromExtendedJSON(v); - } - return value; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function serializeArray(array, options) { - return array.map(function (v, index) { - options.seenObjects.push({ propertyName: "index " + index, obj: null }); - try { - return serializeValue(v, options); - } - finally { - options.seenObjects.pop(); - } - }); - } - function getISOString(date) { - var isoStr = date.toISOString(); - // we should only show milliseconds in timestamp if they're non-zero - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function serializeValue(value, options) { - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); - if (index !== -1) { - var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); - var leadingPart = props - .slice(0, index) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var alreadySeen = props[index]; - var circularPart = ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var current = props[props.length - 1]; - var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new BSONTypeError('Converting circular structure to EJSON:\n' + - (" " + leadingPart + alreadySeen + circularPart + current + "\n") + - (" " + leadingSpace + "\\" + dashes + "/")); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || isDate(value)) { - var dateNum = value.getTime(), - // is it in year range 1970-9999? - inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - // it's an integer - if (Math.floor(value) === value) { - var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; - // interpret as being of the smallest BSON integer type that can represent the number exactly - if (int32Range) - return { $numberInt: value.toString() }; - if (int64Range) - return { $numberLong: value.toString() }; - } - return { $numberDouble: value.toString() }; - } - if (value instanceof RegExp || isRegExp(value)) { - var flags = value.flags; - if (flags === undefined) { - var match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - var rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - if (value != null && typeof value === 'object') - return serializeDocument(value, options); - return value; - } - var BSON_TYPE_MAPPINGS = { - Binary: function (o) { return new Binary(o.value(), o.sub_type); }, - Code: function (o) { return new Code(o.code, o.scope); }, - DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, - Decimal128: function (o) { return new Decimal128(o.bytes); }, - Double: function (o) { return new Double(o.value); }, - Int32: function (o) { return new Int32(o.value); }, - Long: function (o) { - return Long.fromBits( - // underscore variants for 1.x backwards compatibility - o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); - }, - MaxKey: function () { return new MaxKey(); }, - MinKey: function () { return new MinKey(); }, - ObjectID: function (o) { return new ObjectId(o); }, - ObjectId: function (o) { return new ObjectId(o); }, - BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, - Symbol: function (o) { return new BSONSymbol(o.value); }, - Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } - }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function serializeDocument(doc, options) { - if (doc == null || typeof doc !== 'object') - throw new BSONError('not an object instance'); - var bsontype = doc._bsontype; - if (typeof bsontype === 'undefined') { - // It's a regular object. Recursively serialize its property values. - var _doc = {}; - for (var name in doc) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - _doc[name] = serializeValue(doc[name], options); - } - finally { - options.seenObjects.pop(); - } - } - return _doc; - } - else if (isBSONType(doc)) { - // the "document" is really just a BSON type object - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var outDoc = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - // There's no EJSON serialization function on the object. It's probably an - // object created by a previous version of this library (or another library) - // that's duck-typing objects to look like they were generated by this library). - // Copy the object into this library's version of that type. - var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - // Two BSON types may have nested objects that may need to be serialized too - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } - else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); - } - return outDoc.toExtendedJSON(options); - } - else { - throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } - } - /** - * EJSON parse / stringify API - * @public - */ - // the namespace here is used to emulate `export * as EJSON from '...'` - // which as of now (sept 2020) api-extractor does not support - // eslint-disable-next-line @typescript-eslint/no-namespace - exports.EJSON = void 0; - (function (EJSON) { - /** - * Parse an Extended JSON string, constructing the JavaScript value or object described by that - * string. - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const text = '{ "int32": { "$numberInt": "10" } }'; - * - * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } - * console.log(EJSON.parse(text, { relaxed: false })); - * - * // prints { int32: 10 } - * console.log(EJSON.parse(text)); - * ``` - */ - function parse(text, options) { - var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); - // relaxed implies not strict - if (typeof finalOptions.relaxed === 'boolean') - finalOptions.strict = !finalOptions.relaxed; - if (typeof finalOptions.strict === 'boolean') - finalOptions.relaxed = !finalOptions.strict; - return JSON.parse(text, function (key, value) { - if (key.indexOf('\x00') !== -1) { - throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); - } - return deserializeValue(value, finalOptions); - }); - } - EJSON.parse = parse; - /** - * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer - * function is specified or optionally including only the specified properties if a replacer array - * is specified. - * - * @param value - The value to convert to extended JSON - * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string - * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. - * @param options - Optional settings - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const Int32 = require('mongodb').Int32; - * const doc = { int32: new Int32(10) }; - * - * // prints '{"int32":{"$numberInt":"10"}}' - * console.log(EJSON.stringify(doc, { relaxed: false })); - * - * // prints '{"int32":10}' - * console.log(EJSON.stringify(doc)); - * ``` - */ - function stringify(value, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - replacer, space, options) { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - var doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer, space); - } - EJSON.stringify = stringify; - /** - * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - * - * @param value - The object to serialize - * @param options - Optional settings passed to the `stringify` function - */ - function serialize(value, options) { - options = options || {}; - return JSON.parse(stringify(value, options)); - } - EJSON.serialize = serialize; - /** - * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - * - * @param ejson - The Extended JSON object to deserialize - * @param options - Optional settings passed to the parse method - */ - function deserialize(ejson, options) { - options = options || {}; - return parse(JSON.stringify(ejson), options); - } - EJSON.deserialize = deserialize; - })(exports.EJSON || (exports.EJSON = {})); - - /* eslint-disable @typescript-eslint/no-explicit-any */ - /** @public */ - exports.Map = void 0; - var bsonGlobal = getGlobal(); - if (bsonGlobal.Map) { - exports.Map = bsonGlobal.Map; - } - else { - // We will return a polyfill - exports.Map = /** @class */ (function () { - function Map(array) { - if (array === void 0) { array = []; } - this._keys = []; - this._values = {}; - for (var i = 0; i < array.length; i++) { - if (array[i] == null) - continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - } - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) - return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - Map.prototype.entries = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? [key, _this._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.forEach = function (callback, self) { - self = self || this; - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - Map.prototype.keys = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - Map.prototype.values = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? _this._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Object.defineProperty(Map.prototype, "size", { - get: function () { - return this._keys.length; - }, - enumerable: false, - configurable: true - }); - return Map; - }()); - } - - /** @internal */ - var BSON_INT32_MAX = 0x7fffffff; - /** @internal */ - var BSON_INT32_MIN = -0x80000000; - /** @internal */ - var BSON_INT64_MAX = Math.pow(2, 63) - 1; - /** @internal */ - var BSON_INT64_MIN = -Math.pow(2, 63); - /** - * Any integer up to 2^53 can be precisely represented by a double. - * @internal - */ - var JS_INT_MAX = Math.pow(2, 53); - /** - * Any integer down to -2^53 can be precisely represented by a double. - * @internal - */ - var JS_INT_MIN = -Math.pow(2, 53); - /** Number BSON Type @internal */ - var BSON_DATA_NUMBER = 1; - /** String BSON Type @internal */ - var BSON_DATA_STRING = 2; - /** Object BSON Type @internal */ - var BSON_DATA_OBJECT = 3; - /** Array BSON Type @internal */ - var BSON_DATA_ARRAY = 4; - /** Binary BSON Type @internal */ - var BSON_DATA_BINARY = 5; - /** Binary BSON Type @internal */ - var BSON_DATA_UNDEFINED = 6; - /** ObjectId BSON Type @internal */ - var BSON_DATA_OID = 7; - /** Boolean BSON Type @internal */ - var BSON_DATA_BOOLEAN = 8; - /** Date BSON Type @internal */ - var BSON_DATA_DATE = 9; - /** null BSON Type @internal */ - var BSON_DATA_NULL = 10; - /** RegExp BSON Type @internal */ - var BSON_DATA_REGEXP = 11; - /** Code BSON Type @internal */ - var BSON_DATA_DBPOINTER = 12; - /** Code BSON Type @internal */ - var BSON_DATA_CODE = 13; - /** Symbol BSON Type @internal */ - var BSON_DATA_SYMBOL = 14; - /** Code with Scope BSON Type @internal */ - var BSON_DATA_CODE_W_SCOPE = 15; - /** 32 bit Integer BSON Type @internal */ - var BSON_DATA_INT = 16; - /** Timestamp BSON Type @internal */ - var BSON_DATA_TIMESTAMP = 17; - /** Long BSON Type @internal */ - var BSON_DATA_LONG = 18; - /** Decimal128 BSON Type @internal */ - var BSON_DATA_DECIMAL128 = 19; - /** MinKey BSON Type @internal */ - var BSON_DATA_MIN_KEY = 0xff; - /** MaxKey BSON Type @internal */ - var BSON_DATA_MAX_KEY = 0x7f; - /** Binary Default Type @internal */ - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** Binary Function Type @internal */ - var BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** Binary Byte Array Type @internal */ - var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ - var BSON_BINARY_SUBTYPE_UUID = 3; - /** Binary UUID Type @internal */ - var BSON_BINARY_SUBTYPE_UUID_NEW = 4; - /** Binary MD5 Type @internal */ - var BSON_BINARY_SUBTYPE_MD5 = 5; - /** Encrypted BSON type @internal */ - var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; - /** Column BSON type @internal */ - var BSON_BINARY_SUBTYPE_COLUMN = 7; - /** Binary User Defined Type @internal */ - var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } - else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - return totalLength; - } - /** @internal */ - function calculateElement(name, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - value, serializeFunctions, isArray, ignoreUndefined) { - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (isArray === void 0) { isArray = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = false; } - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - switch (typeof value) { - case 'string': - return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && - value >= JS_INT_MIN && - value <= JS_INT_MAX) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - // 32 bit - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } - else { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } - else { - // 64 bit - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } - else if (value instanceof Date || isDate(value)) { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - isAnyArrayBuffer(value)) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); - } - else if (value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (value['_bsontype'] === 'Decimal128') { - return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } - else if (value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.byteLength(value.code.toString(), 'utf8') + - 1); - } - } - else if (value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4)); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); - } - } - else if (value['_bsontype'] === 'Symbol') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - buffer_1.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1); - } - else if (value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - // Add db reference if it exists - if (value.db != null) { - ordered_values['$db'] = value.db; - } - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); - } - else if (value instanceof RegExp || isRegExp(value)) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else if (value['_bsontype'] === 'BSONRegExp') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.pattern, 'utf8') + - 1 + - buffer_1.byteLength(value.options, 'utf8') + - 1); - } - else { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + - 1); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else if (serializeFunctions) { - return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + - 1); - } - } - } - return 0; - } - - var FIRST_BIT = 0x80; - var FIRST_TWO_BITS = 0xc0; - var FIRST_THREE_BITS = 0xe0; - var FIRST_FOUR_BITS = 0xf0; - var FIRST_FIVE_BITS = 0xf8; - var TWO_BIT_CHAR = 0xc0; - var THREE_BIT_CHAR = 0xe0; - var FOUR_BIT_CHAR = 0xf0; - var CONTINUING_CHAR = 0x80; - /** - * Determines if the passed in bytes are valid utf8 - * @param bytes - An array of 8-bit bytes. Must be indexable and have length property - * @param start - The index to start validating - * @param end - The index to end validating - */ - function validateUtf8(bytes, start, end) { - var continuation = 0; - for (var i = start; i < end; i += 1) { - var byte = bytes[i]; - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } - else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } - else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } - else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } - else { - return false; - } - } - } - return !continuation; - } - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); - var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); - var functionCache = {}; - function deserialize$1(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (size < 5) { - throw new BSONError("bson size must be >= 5, is " + size); - } - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); - } - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); - } - if (size + index > buffer.byteLength) { - throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); - } - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - } - var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; - function deserializeObject(buffer, index, options, isArray) { - if (isArray === void 0) { isArray = false; } - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - // Ensures default validation option if none given - var validation = options.validation == null ? { utf8: true } : options.validation; - // Shows if global utf-8 validation is enabled or disabled - var globalUTFValidation = true; - // Reflects utf-8 validation setting regardless of global or specific key validation - var validationSetting; - // Set of keys either to enable or disable validation on - var utf8KeysSet = new Set(); - // Check for boolean uniformity and empty validation option - var utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } - else { - globalUTFValidation = false; - var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - // Ensures boolean uniformity in utf-8 validation (all true or all false) - if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) { - throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - // Add keys to set that will either be validated or not based on validationSetting - if (!globalUTFValidation) { - for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) { - var key = _a[_i]; - utf8KeysSet.add(key); - } - } - // Set the start index - var startIndex = index; - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) - throw new BSONError('corrupt bson message < 5 bytes long'); - // Read the document size - var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) - throw new BSONError('corrupt bson message'); - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - var done = false; - var isPossibleDBRef = isArray ? false : null; - // While we have more left data left keep parsing - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) - break; - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.byteLength) - throw new BSONError('Bad BSON Document: illegal CString'); - // Represents the key - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - // shouldValidateKey is true if the key should be validated, false otherwise - var shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } - else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - var value = void 0; - index = i + 1; - if (elementType === BSON_DATA_STRING) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } - else if (elementType === BSON_DATA_OID) { - var oid = buffer_1.alloc(12); - buffer.copy(oid, 0, index, index + 12); - value = new ObjectId(oid); - index = index + 12; - } - else if (elementType === BSON_DATA_INT && promoteValues === false) { - value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); - } - else if (elementType === BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } - else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { - value = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } - else if (elementType === BSON_DATA_NUMBER) { - value = buffer.readDoubleLE(index); - index = index + 8; - } - else if (elementType === BSON_DATA_DATE) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new Long(lowBits, highBits).toNumber()); - } - else if (elementType === BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } - else if (elementType === BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new BSONError('bad embedded document length in bson'); - // We have a raw value - if (raw) { - value = buffer.slice(index, index + objectSize); - } - else { - var objectOptions = options; - if (!globalUTFValidation) { - objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - index = index + objectSize; - } - else if (elementType === BSON_DATA_ARRAY) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - // Stop index - var stopIndex = index + objectSize; - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) { - arrayOptions[n] = options[n]; - } - arrayOptions['raw'] = true; - } - if (!globalUTFValidation) { - arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - if (buffer[index - 1] !== 0) - throw new BSONError('invalid array terminator byte'); - if (index !== stopIndex) - throw new BSONError('corrupted array bson'); - } - else if (elementType === BSON_DATA_UNDEFINED) { - value = undefined; - } - else if (elementType === BSON_DATA_NULL) { - value = null; - } - else if (elementType === BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } - else { - value = long; - } - } - else if (elementType === BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = buffer_1.alloc(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { - value = decimal128.toObject(); - } - else { - value = decimal128; - } - } - else if (elementType === BSON_DATA_BINARY) { - var binarySize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - // Did we have a negative binary size, throw - if (binarySize < 0) - throw new BSONError('Negative binary type element size found'); - // Is the length longer than the document - if (binarySize > buffer.byteLength) - throw new BSONError('Binary type size larger than document size'); - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - if (promoteBuffers && promoteValues) { - value = buffer.slice(index, index + binarySize); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - } - } - else { - var _buffer = buffer_1.alloc(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - if (promoteBuffers && promoteValues) { - value = _buffer; - } - else { - value = new Binary(_buffer, subType); - } - } - // Update the index - index = index + binarySize; - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - value = new RegExp(source, optionsArray.join('')); - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // Set the object - value = new BSONRegExp(source, regExpOptions); - } - else if (elementType === BSON_DATA_SYMBOL) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new BSONSymbol(symbol); - index = index + stringSize; - } - else if (elementType === BSON_DATA_TIMESTAMP) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Timestamp(lowBits, highBits); - } - else if (elementType === BSON_DATA_MIN_KEY) { - value = new MinKey(); - } - else if (elementType === BSON_DATA_MAX_KEY) { - value = new MaxKey(); - } - else if (elementType === BSON_DATA_CODE) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - } - else { - value = new Code(functionString); - } - // Update parse index position - index = index + stringSize; - } - else if (elementType === BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError('code_w_scope total size shorter minimum expected length'); - } - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - // Javascript function - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // Update parse index position - index = index + stringSize; - // Parse the element - var _index = index; - // Decode the size of the object document - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - // Check if field length is too short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too short, truncating scope'); - } - // Check if totalSize field is too long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too long, clips outer document'); - } - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - value.scope = scopeObject; - } - else { - value = new Code(functionString, scopeObject); - } - } - else if (elementType === BSON_DATA_DBPOINTER) { - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) - throw new BSONError('bad string length in bson'); - // Namespace - if (validation != null && validation.utf8) { - if (!validateUtf8(buffer, index, index + stringSize - 1)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - } - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Read the oid - var oidBuffer = buffer_1.alloc(12); - buffer.copy(oidBuffer, 0, index, index + 12); - var oid = new ObjectId(oidBuffer); - // Update the index - index = index + 12; - // Upgrade to DBRef type - value = new DBRef(namespace, oid); - } - else { - throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value: value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - object[name] = value; - } - } - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) - throw new BSONError('corrupt array bson'); - throw new BSONError('corrupt object bson'); - } - // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef - if (!isPossibleDBRef) - return object; - if (isDBRefLike(object)) { - var copy = Object.assign({}, object); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object.$ref, object.$id, object.$db, copy); - } - return object; - } - /** - * Ensure eval is isolated, store the result in functionCache. - * - * @internal - */ - function isolateEval(functionString, functionCache, object) { - if (!functionCache) - return new Function(functionString); - // Check for cache hit, eval if missing and return cached function - if (functionCache[functionString] == null) { - functionCache[functionString] = new Function(functionString); - } - // Set the object - return functionCache[functionString].bind(object); - } - function getValidatedString(buffer, start, end, shouldValidateUtf8) { - var value = buffer.toString('utf8', start, end); - // if utf8 validation is on, do the check - if (shouldValidateUtf8) { - for (var i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validateUtf8(buffer, start, end)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; - } - - // Copyright (c) 2008, Fair Oaks Labs, Inc. - function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { - var e; - var m; - var c; - var bBE = endian === 'big'; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = bBE ? nBytes - 1 : 0; - var d = bBE ? -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; - } - } - if (isNaN(value)) - m = 0; - while (mLen >= 8) { - buffer[offset + i] = m & 0xff; - i += d; - m /= 256; - mLen -= 8; - } - e = (e << mLen) | m; - if (isNaN(value)) - e += 8; - eLen += mLen; - while (eLen > 0) { - buffer[offset + i] = e & 0xff; - i += d; - e /= 256; - eLen -= 8; - } - buffer[offset + i - d] |= s * 128; - } - - var regexp = /\x00/; // eslint-disable-line no-control-regex - var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); - /* - * isArray indicates if we are writing to a BSON array (type 0x04) - * which forces the "key" which really an array index as a string to be written as ascii - * This will catch any errors in index as a string generation - */ - function serializeString(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, undefined, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - } - function serializeNumber(buffer, key, value, index, isArray) { - // We have an integer value - // TODO(NODE-2529): Add support for big int - if (Number.isInteger(value) && - value >= BSON_INT32_MIN && - value <= BSON_INT32_MAX) { - // If the value fits in 32 bits encode as int32 - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } - else { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - } - return index; - } - function serializeNull(buffer, key, _, index, isArray) { - // Set long type - buffer[index++] = BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - } - function serializeBoolean(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - } - function serializeDate(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } - function serializeRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.ignoreCase) - buffer[index++] = 0x69; // i - if (value.global) - buffer[index++] = 0x73; // s - if (value.multiline) - buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } - function serializeBSONRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.pattern, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - } - function serializeMinMax(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON_DATA_NULL; - } - else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON_DATA_MIN_KEY; - } - else { - buffer[index++] = BSON_DATA_MAX_KEY; - } - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - } - function serializeObjectId(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, undefined, 'binary'); - } - else if (isUint8Array(value.id)) { - // Use the standard JS methods here because buffer.copy() is buggy with the - // browser polyfill - buffer.set(value.id.subarray(0, 12), index); - } - else { - throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - // Adjust index - return index + 12; - } - function serializeBuffer(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - buffer.set(ensureBuffer(value), index); - // Adjust the index - index = index + size; - return index; - } - function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (path === void 0) { path = []; } - for (var i = 0; i < path.length; i++) { - if (path[i] === value) - throw new BSONError('cyclic dependency detected'); - } - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - return endIndex; - } - function serializeDecimal128(buffer, key, value, index, isArray) { - buffer[index++] = BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - // Prefer the standard JS methods because their typechecking is not buggy, - // unlike the `buffer` polyfill's. - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; - } - function serializeLong(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = - value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } - function serializeInt32(buffer, key, value, index, isArray) { - value = value.valueOf(); - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; - } - function serializeDouble(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value.value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - return index; - } - function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Starting index - var startIndex = index; - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - // Writ the total - var totalSize = endIndex - startIndex; - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } - else { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - return index; - } - function serializeBinary(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - // Write the data to the object - buffer.set(data, index); - // Adjust the index - index = index + value.position; - return index; - } - function serializeSymbol(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } - function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var startIndex = index; - var output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; - } - output = Object.assign(output, value.fields); - var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; - } - function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (startingIndex === void 0) { startingIndex = 0; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (path === void 0) { path = []; } - startingIndex = startingIndex || 0; - path = path || []; - // Push the object to the path - path.push(object); - // Start place to serialize into - var index = startingIndex + 4; - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index, true); - } - else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } - else if (typeof value === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } - else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } - else if (typeof value === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } - else if (typeof value === 'object' && - isBSONType(value) && - value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else if (object instanceof exports.Map || isMap(object)) { - var iterator = object.entries(); - var done = false; - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = !!entry.done; - // Are we done, then skip and terminate - if (done) - continue; - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new BSONTypeError('toBSON function did not return an object'); - } - // Iterate over all the keys - for (var key in object) { - var value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - if (ignoreUndefined === false) - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - // Remove the path - path.pop(); - // Final padding byte for object - buffer[index++] = 0x00; - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; - } - - /** @internal */ - // Default Max Size - var MAXSIZE = 1024 * 1024 * 17; - // Current Internal Temporary Serialization Buffer - var buffer = buffer_1.alloc(MAXSIZE); - /** - * Sets the size of the internal serialization buffer. - * - * @param size - The desired size for the internal serialization buffer - * @public - */ - function setInternalBufferSize(size) { - // Resize the internal serialization buffer if needed - if (buffer.length < size) { - buffer = buffer_1.alloc(size); - } - } - /** - * Serialize a Javascript object. - * - * @param object - the Javascript object to serialize. - * @returns Buffer object containing the serialized object. - * @public - */ - function serialize(object, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = buffer_1.alloc(minInternalBufferSize); - } - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = buffer_1.alloc(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - } - /** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, - * useful when pre-allocating the space for serialization. - * - * @param object - the Javascript object to serialize. - * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. - * @returns the index pointing to the last written byte in the buffer. - * @public - */ - function serializeWithBufferAndIndex(object, finalBuffer, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - // Return the index - return startIndex + serializationIndex - 1; - } - /** - * Deserialize data as BSON. - * - * @param buffer - the buffer containing the serialized set of BSON documents. - * @returns returns the deserialized Javascript Object. - * @public - */ - function deserialize(buffer, options) { - if (options === void 0) { options = {}; } - return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options); - } - /** - * Calculate the bson size for a passed in Javascript object. - * - * @param object - the Javascript object to calculate the BSON byte size for - * @returns size of BSON object in bytes - * @public - */ - function calculateObjectSize(object, options) { - if (options === void 0) { options = {}; } - options = options || {}; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); - } - /** - * Deserialize stream data as BSON documents. - * - * @param data - the buffer containing the serialized set of BSON documents. - * @param startIndex - the start index in the data Buffer where the deserialization is to start. - * @param numberOfDocuments - number of documents to deserialize. - * @param documents - an array where to store the deserialized documents. - * @param docStartIndex - the index in the documents array from where to start inserting documents. - * @param options - additional options used for the deserialization. - * @returns next index in the buffer after deserialization **x** numbers of documents. - * @public - */ - function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - var bufferData = ensureBuffer(data); - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - // Update options with index - internalOptions.index = index; - // Parse the document at this point - documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); - // Adjust index by the document size - index = index + size; - } - // Return object containing end index of parsing and list of documents - return index; - } - /** - * BSON default export - * @deprecated Please use named exports - * @privateRemarks - * We want to someday deprecate the default export, - * so none of the new TS types are being exported on the default - * @public - */ - var BSON = { - Binary: Binary, - Code: Code, - DBRef: DBRef, - Decimal128: Decimal128, - Double: Double, - Int32: Int32, - Long: Long, - UUID: UUID, - Map: exports.Map, - MaxKey: MaxKey, - MinKey: MinKey, - ObjectId: ObjectId, - ObjectID: ObjectId, - BSONRegExp: BSONRegExp, - BSONSymbol: BSONSymbol, - Timestamp: Timestamp, - EJSON: exports.EJSON, - setInternalBufferSize: setInternalBufferSize, - serialize: serialize, - serializeWithBufferAndIndex: serializeWithBufferAndIndex, - deserialize: deserialize, - calculateObjectSize: calculateObjectSize, - deserializeStream: deserializeStream, - BSONError: BSONError, - BSONTypeError: BSONTypeError - }; - - exports.BSONError = BSONError; - exports.BSONRegExp = BSONRegExp; - exports.BSONSymbol = BSONSymbol; - exports.BSONTypeError = BSONTypeError; - exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = BSON_BINARY_SUBTYPE_BYTE_ARRAY; - exports.BSON_BINARY_SUBTYPE_COLUMN = BSON_BINARY_SUBTYPE_COLUMN; - exports.BSON_BINARY_SUBTYPE_DEFAULT = BSON_BINARY_SUBTYPE_DEFAULT; - exports.BSON_BINARY_SUBTYPE_ENCRYPTED = BSON_BINARY_SUBTYPE_ENCRYPTED; - exports.BSON_BINARY_SUBTYPE_FUNCTION = BSON_BINARY_SUBTYPE_FUNCTION; - exports.BSON_BINARY_SUBTYPE_MD5 = BSON_BINARY_SUBTYPE_MD5; - exports.BSON_BINARY_SUBTYPE_USER_DEFINED = BSON_BINARY_SUBTYPE_USER_DEFINED; - exports.BSON_BINARY_SUBTYPE_UUID = BSON_BINARY_SUBTYPE_UUID; - exports.BSON_BINARY_SUBTYPE_UUID_NEW = BSON_BINARY_SUBTYPE_UUID_NEW; - exports.BSON_DATA_ARRAY = BSON_DATA_ARRAY; - exports.BSON_DATA_BINARY = BSON_DATA_BINARY; - exports.BSON_DATA_BOOLEAN = BSON_DATA_BOOLEAN; - exports.BSON_DATA_CODE = BSON_DATA_CODE; - exports.BSON_DATA_CODE_W_SCOPE = BSON_DATA_CODE_W_SCOPE; - exports.BSON_DATA_DATE = BSON_DATA_DATE; - exports.BSON_DATA_DBPOINTER = BSON_DATA_DBPOINTER; - exports.BSON_DATA_DECIMAL128 = BSON_DATA_DECIMAL128; - exports.BSON_DATA_INT = BSON_DATA_INT; - exports.BSON_DATA_LONG = BSON_DATA_LONG; - exports.BSON_DATA_MAX_KEY = BSON_DATA_MAX_KEY; - exports.BSON_DATA_MIN_KEY = BSON_DATA_MIN_KEY; - exports.BSON_DATA_NULL = BSON_DATA_NULL; - exports.BSON_DATA_NUMBER = BSON_DATA_NUMBER; - exports.BSON_DATA_OBJECT = BSON_DATA_OBJECT; - exports.BSON_DATA_OID = BSON_DATA_OID; - exports.BSON_DATA_REGEXP = BSON_DATA_REGEXP; - exports.BSON_DATA_STRING = BSON_DATA_STRING; - exports.BSON_DATA_SYMBOL = BSON_DATA_SYMBOL; - exports.BSON_DATA_TIMESTAMP = BSON_DATA_TIMESTAMP; - exports.BSON_DATA_UNDEFINED = BSON_DATA_UNDEFINED; - exports.BSON_INT32_MAX = BSON_INT32_MAX; - exports.BSON_INT32_MIN = BSON_INT32_MIN; - exports.BSON_INT64_MAX = BSON_INT64_MAX; - exports.BSON_INT64_MIN = BSON_INT64_MIN; - exports.Binary = Binary; - exports.Code = Code; - exports.DBRef = DBRef; - exports.Decimal128 = Decimal128; - exports.Double = Double; - exports.Int32 = Int32; - exports.Long = Long; - exports.LongWithoutOverridesClass = LongWithoutOverridesClass; - exports.MaxKey = MaxKey; - exports.MinKey = MinKey; - exports.ObjectID = ObjectId; - exports.ObjectId = ObjectId; - exports.Timestamp = Timestamp; - exports.UUID = UUID; - exports.calculateObjectSize = calculateObjectSize; - exports.default = BSON; - exports.deserialize = deserialize; - exports.deserializeStream = deserializeStream; - exports.serialize = serialize; - exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; - exports.setInternalBufferSize = setInternalBufferSize; - - Object.defineProperty(exports, '__esModule', { value: true }); - - return exports; - -}({})); -//# sourceMappingURL=bson.bundle.js.map diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.bundle.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.bundle.js.map deleted file mode 100644 index 47f7a72..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.bundle.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bson.bundle.js","sources":["../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/buffer/index.js","../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"sourcesContent":["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n var proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n var copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(buf).copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["byteLength","toByteArray","fromByteArray","lookup","revLookup","Arr","Uint8Array","Array","code","i","len","length","charCodeAt","getLens","b64","Error","validLen","indexOf","placeHoldersLen","lens","_byteLength","tmp","arr","curByte","tripletToBase64","num","encodeChunk","uint8","start","end","output","push","join","extraBytes","parts","maxChunkLength","len2","buffer","offset","isLE","mLen","nBytes","e","m","eLen","eMax","eBias","nBits","d","s","NaN","Infinity","Math","pow","value","c","rt","abs","isNaN","floor","log","LN2","customInspectSymbol","Symbol","exports","Buffer","SlowBuffer","K_MAX_LENGTH","TYPED_ARRAY_SUPPORT","typedArraySupport","console","error","proto","foo","Object","setPrototypeOf","prototype","defineProperty","enumerable","get","isBuffer","undefined","byteOffset","createBuffer","RangeError","buf","arg","encodingOrOffset","TypeError","allocUnsafe","from","poolSize","fromString","ArrayBuffer","isView","fromArrayView","isInstance","fromArrayBuffer","SharedArrayBuffer","valueOf","b","fromObject","toPrimitive","assertSize","size","alloc","fill","encoding","checked","allocUnsafeSlow","string","isEncoding","actual","write","slice","fromArrayLike","array","arrayView","copy","obj","numberIsNaN","type","isArray","data","toString","_isBuffer","compare","a","x","y","min","String","toLowerCase","concat","list","pos","set","call","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","swap16","swap32","swap64","apply","toLocaleString","equals","inspect","str","max","INSPECT_MAX_BYTES","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","includes","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","asciiToBytes","base64Write","ucs2Write","utf16leToBytes","isFinite","toJSON","_arr","base64","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","MAX_ARGUMENTS_LENGTH","codePoints","fromCharCode","ret","out","hexSliceLookupTable","bytes","newBuf","subarray","checkOffset","ext","readUintLE","readUIntLE","noAssert","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","ieee754","readFloatBE","readDoubleLE","readDoubleBE","checkInt","writeUintLE","writeUIntLE","maxBytes","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","checkIEEE754","writeFloat","littleEndian","writeFloatLE","writeFloatBE","writeDouble","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","base64clean","split","units","leadSurrogate","byteArray","hi","lo","src","dst","constructor","name","alphabet","table","i16","extendStatics","__proto__","p","hasOwnProperty","__extends","__","create","__assign","assign","t","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","EJSON","bsonMap","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;;;;;;CAEA,gBAAkB,GAAGA,UAArB;CACA,iBAAmB,GAAGC,WAAtB;CACA,mBAAqB,GAAGC,aAAxB;CAEA,IAAIC,MAAM,GAAG,EAAb;CACA,IAAIC,SAAS,GAAG,EAAhB;CACA,IAAIC,GAAG,GAAG,OAAOC,UAAP,KAAsB,WAAtB,GAAoCA,UAApC,GAAiDC,KAA3D;CAEA,IAAIC,IAAI,GAAG,kEAAX;;CACA,KAAK,IAAIC,CAAC,GAAG,CAAR,EAAWC,GAAG,GAAGF,IAAI,CAACG,MAA3B,EAAmCF,CAAC,GAAGC,GAAvC,EAA4C,EAAED,CAA9C,EAAiD;CAC/CN,EAAAA,MAAM,CAACM,CAAD,CAAN,GAAYD,IAAI,CAACC,CAAD,CAAhB;CACAL,EAAAA,SAAS,CAACI,IAAI,CAACI,UAAL,CAAgBH,CAAhB,CAAD,CAAT,GAAgCA,CAAhC;CACD;CAGD;;;CACAL,SAAS,CAAC,IAAIQ,UAAJ,CAAe,CAAf,CAAD,CAAT,GAA+B,EAA/B;CACAR,SAAS,CAAC,IAAIQ,UAAJ,CAAe,CAAf,CAAD,CAAT,GAA+B,EAA/B;;CAEA,SAASC,OAAT,CAAkBC,GAAlB,EAAuB;CACrB,MAAIJ,GAAG,GAAGI,GAAG,CAACH,MAAd;;CAEA,MAAID,GAAG,GAAG,CAAN,GAAU,CAAd,EAAiB;CACf,UAAM,IAAIK,KAAJ,CAAU,gDAAV,CAAN;CACD,GALoB;;;;CASrB,MAAIC,QAAQ,GAAGF,GAAG,CAACG,OAAJ,CAAY,GAAZ,CAAf;CACA,MAAID,QAAQ,KAAK,CAAC,CAAlB,EAAqBA,QAAQ,GAAGN,GAAX;CAErB,MAAIQ,eAAe,GAAGF,QAAQ,KAAKN,GAAb,GAClB,CADkB,G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U,CAAC,KAAK,CAAC;cAChB,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;cAC3B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;cAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;;SAEhC,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;;SAE9B,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAGD,aAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;;SAEhF,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;MACtB;;KAGD,OAAO,KAAK,CAAC;CACf,CAAC;CAED;;;;;;;;KAQM,IAAI,GAAG;KACX,MAAM,QAAA;KACN,IAAI,MAAA;KACJ,KAAK,OAAA;KACL,UAAU,YAAA;KACV,MAAM,QAAA;KACN,KAAK,OAAA;KACL,IAAI,MAAA;KACJ,IAAI,MAAA;KACJ,GAAG,aAAA;KACH,MAAM,QAAA;KACN,MAAM,QAAA;KACN,QAAQ,UAAA;KACR,QAAQ,EAAE,QAAQ;KAClB,UAAU,YAAA;KACV,UAAU,YAAA;KACV,SAAS,WAAA;KACT,KAAK,eAAA;KACL,qBAAqB,uBAAA;KACrB,SAAS,WAAA;KACT,2BAA2B,6BAAA;KAC3B,WAAW,aAAA;KACX,mBAAmB,qBAAA;KACnB,iBAAiB,mBAAA;KACjB,SAAS,WAAA;KACT,aAAa,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.esm.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.esm.js deleted file mode 100644 index 6dab079..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.esm.js +++ /dev/null @@ -1,5482 +0,0 @@ -import { Buffer } from 'buffer'; - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -/* global Reflect, Promise */ -var _extendStatics = function extendStatics(d, b) { - _extendStatics = Object.setPrototypeOf || { - __proto__: [] - } instanceof Array && function (d, b) { - d.__proto__ = b; - } || function (d, b) { - for (var p in b) { - if (b.hasOwnProperty(p)) d[p] = b[p]; - } - }; - - return _extendStatics(d, b); -}; - -function __extends(d, b) { - _extendStatics(d, b); - - function __() { - this.constructor = d; - } - - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var _assign = function __assign() { - _assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - - for (var p in s) { - if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - } - - return t; - }; - - return _assign.apply(this, arguments); -}; - -/** @public */ -var BSONError = /** @class */ (function (_super) { - __extends(BSONError, _super); - function BSONError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONError.prototype); - return _this; - } - Object.defineProperty(BSONError.prototype, "name", { - get: function () { - return 'BSONError'; - }, - enumerable: false, - configurable: true - }); - return BSONError; -}(Error)); -/** @public */ -var BSONTypeError = /** @class */ (function (_super) { - __extends(BSONTypeError, _super); - function BSONTypeError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONTypeError.prototype); - return _this; - } - Object.defineProperty(BSONTypeError.prototype, "name", { - get: function () { - return 'BSONTypeError'; - }, - enumerable: false, - configurable: true - }); - return BSONTypeError; -}(TypeError)); - -function checkForMath(potentialGlobal) { - // eslint-disable-next-line eqeqeq - return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; -} -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -function getGlobal() { - // eslint-disable-next-line no-undef - return (checkForMath(typeof globalThis === 'object' && globalThis) || - checkForMath(typeof window === 'object' && window) || - checkForMath(typeof self === 'object' && self) || - checkForMath(typeof global === 'object' && global) || - Function('return this')()); -} - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param fn - The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace('function(', 'function ('); -} -function isReactNative() { - var g = getGlobal(); - return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; -} -var insecureRandomBytes = function insecureRandomBytes(size) { - var insecureWarning = isReactNative() - ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' - : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; - console.warn(insecureWarning); - var result = Buffer.alloc(size); - for (var i = 0; i < size; ++i) - result[i] = Math.floor(Math.random() * 256); - return result; -}; -var detectRandomBytes = function () { - if (typeof window !== 'undefined') { - // browser crypto implementation(s) - var target_1 = window.crypto || window.msCrypto; // allow for IE11 - if (target_1 && target_1.getRandomValues) { - return function (size) { return target_1.getRandomValues(Buffer.alloc(size)); }; - } - } - if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { - // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global - return function (size) { return global.crypto.getRandomValues(Buffer.alloc(size)); }; - } - var requiredRandomBytes; - try { - // eslint-disable-next-line @typescript-eslint/no-var-requires - requiredRandomBytes = require('crypto').randomBytes; - } - catch (e) { - // keep the fallback - } - // NOTE: in transpiled cases the above require might return null/undefined - return requiredRandomBytes || insecureRandomBytes; -}; -var randomBytes = detectRandomBytes(); -function isAnyArrayBuffer(value) { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); -} -function isUint8Array(value) { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; -} -function isBigInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigInt64Array]'; -} -function isBigUInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigUint64Array]'; -} -function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} -function isMap(d) { - return Object.prototype.toString.call(d) === '[object Map]'; -} -// To ensure that 0.4 of node works correctly -function isDate(d) { - return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; -} -/** - * @internal - * this is to solve the `'someKey' in x` problem where x is unknown. - * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 - */ -function isObjectLike(candidate) { - return typeof candidate === 'object' && candidate !== null; -} -function deprecate(fn, message) { - var warned = false; - function deprecated() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!warned) { - console.warn(message); - warned = true; - } - return fn.apply(this, args); - } - return deprecated; -} - -/** - * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. - * - * @param potentialBuffer - The potential buffer - * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that - * wraps a passed in Uint8Array - * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in - */ -function ensureBuffer(potentialBuffer) { - if (ArrayBuffer.isView(potentialBuffer)) { - return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - if (isAnyArrayBuffer(potentialBuffer)) { - return Buffer.from(potentialBuffer); - } - throw new BSONTypeError('Must use either Buffer or TypedArray'); -} - -// Validation regex for v4 uuid (validates with or without dashes) -var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; -var uuidValidateString = function (str) { - return typeof str === 'string' && VALIDATION_REGEX.test(str); -}; -var uuidHexStringToBuffer = function (hexString) { - if (!uuidValidateString(hexString)) { - throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); - } - var sanitizedHexString = hexString.replace(/-/g, ''); - return Buffer.from(sanitizedHexString, 'hex'); -}; -var bufferToUuidHexString = function (buffer, includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - return includeDashes - ? buffer.toString('hex', 0, 4) + - '-' + - buffer.toString('hex', 4, 6) + - '-' + - buffer.toString('hex', 6, 8) + - '-' + - buffer.toString('hex', 8, 10) + - '-' + - buffer.toString('hex', 10, 16) - : buffer.toString('hex'); -}; - -var BYTE_LENGTH = 16; -var kId$1 = Symbol('id'); -/** - * A class representation of the BSON UUID type. - * @public - */ -var UUID = /** @class */ (function () { - /** - * Create an UUID type - * - * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. - */ - function UUID(input) { - if (typeof input === 'undefined') { - // The most common use case (blank id, new UUID() instance) - this.id = UUID.generate(); - } - else if (input instanceof UUID) { - this[kId$1] = Buffer.from(input.id); - this.__id = input.__id; - } - else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { - this.id = ensureBuffer(input); - } - else if (typeof input === 'string') { - this.id = uuidHexStringToBuffer(input); - } - else { - throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); - } - } - Object.defineProperty(UUID.prototype, "id", { - /** - * The UUID bytes - * @readonly - */ - get: function () { - return this[kId$1]; - }, - set: function (value) { - this[kId$1] = value; - if (UUID.cacheHexString) { - this.__id = bufferToUuidHexString(value); - } - }, - enumerable: false, - configurable: true - }); - /** - * Generate a 16 byte uuid v4 buffer used in UUIDs - */ - /** - * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) - * @param includeDashes - should the string exclude dash-separators. - * */ - UUID.prototype.toHexString = function (includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - var uuidHexString = bufferToUuidHexString(this.id, includeDashes); - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - return uuidHexString; - }; - /** - * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. - */ - UUID.prototype.toString = function (encoding) { - return encoding ? this.id.toString(encoding) : this.toHexString(); - }; - /** - * Converts the id into its JSON string representation. - * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - */ - UUID.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this UUID with `otherID`. - * - * @param otherId - UUID instance to compare against. - */ - UUID.prototype.equals = function (otherId) { - if (!otherId) { - return false; - } - if (otherId instanceof UUID) { - return otherId.id.equals(this.id); - } - try { - return new UUID(otherId).id.equals(this.id); - } - catch (_a) { - return false; - } - }; - /** - * Creates a Binary instance from the current UUID. - */ - UUID.prototype.toBinary = function () { - return new Binary(this.id, Binary.SUBTYPE_UUID); - }; - /** - * Generates a populated buffer containing a v4 uuid - */ - UUID.generate = function () { - var bytes = randomBytes(BYTE_LENGTH); - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - return Buffer.from(bytes); - }; - /** - * Checks if a value is a valid bson UUID - * @param input - UUID, string or Buffer to validate. - */ - UUID.isValid = function (input) { - if (!input) { - return false; - } - if (input instanceof UUID) { - return true; - } - if (typeof input === 'string') { - return uuidValidateString(input); - } - if (isUint8Array(input)) { - // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) - if (input.length !== BYTE_LENGTH) { - return false; - } - try { - // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx - // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx - return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; - } - catch (_a) { - return false; - } - } - return false; - }; - /** - * Creates an UUID from a hex string representation of an UUID. - * @param hexString - 32 or 36 character hex string (dashes excluded/included). - */ - UUID.createFromHexString = function (hexString) { - var buffer = uuidHexStringToBuffer(hexString); - return new UUID(buffer); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 36 character hex string representation. - * @internal - */ - UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - UUID.prototype.inspect = function () { - return "new UUID(\"" + this.toHexString() + "\")"; - }; - return UUID; -}()); -Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); - -/** - * A class representation of the BSON Binary type. - * @public - */ -var Binary = /** @class */ (function () { - /** - * @param buffer - a buffer object containing the binary data. - * @param subType - the option binary type. - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) - return new Binary(buffer, subType); - if (!(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer)) { - throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); - } - this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer == null) { - // create an empty binary buffer - this.buffer = Buffer.alloc(Binary.BUFFER_SIZE); - this.position = 0; - } - else { - if (typeof buffer === 'string') { - // string - this.buffer = Buffer.from(buffer, 'binary'); - } - else if (Array.isArray(buffer)) { - // number[] - this.buffer = Buffer.from(buffer); - } - else { - // Buffer | TypedArray | ArrayBuffer - this.buffer = ensureBuffer(buffer); - } - this.position = this.buffer.byteLength; - } - } - /** - * Updates this binary with byte_value. - * - * @param byteValue - a single byte we wish to write. - */ - Binary.prototype.put = function (byteValue) { - // If it's a string and a has more than one character throw an error - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new BSONTypeError('only accepts single character String'); - } - else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new BSONTypeError('only accepts single character Uint8Array or Array'); - // Decode the byte value once - var decodedByte; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } - else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } - else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); - } - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decodedByte; - } - else { - var buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decodedByte; - } - }; - /** - * Writes a buffer or string to the binary. - * - * @param sequence - a string or buffer to be written to the Binary BSON object. - * @param offset - specify the binary of where to write the content. - */ - Binary.prototype.write = function (sequence, offset) { - offset = typeof offset === 'number' ? offset : this.position; - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + sequence.length) { - var buffer = Buffer.alloc(this.buffer.length + sequence.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - // Assign the new buffer - this.buffer = buffer; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ensureBuffer(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } - else if (typeof sequence === 'string') { - this.buffer.write(sequence, offset, sequence.length, 'binary'); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - }; - /** - * Reads **length** bytes starting at **position**. - * - * @param position - read from the given position in the Binary. - * @param length - the number of bytes to read. - */ - Binary.prototype.read = function (position, length) { - length = length && length > 0 ? length : this.position; - // Let's return the data based on the type we have - return this.buffer.slice(position, position + length); - }; - /** - * Returns the value of this binary as a string. - * @param asRaw - Will skip converting to a string - * @remarks - * This is handy when calling this function conditionally for some key value pairs and not others - */ - Binary.prototype.value = function (asRaw) { - asRaw = !!asRaw; - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - // If it's a node.js buffer object - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return this.buffer.toString('binary', 0, this.position); - }; - /** the length of the binary sequence */ - Binary.prototype.length = function () { - return this.position; - }; - Binary.prototype.toJSON = function () { - return this.buffer.toString('base64'); - }; - Binary.prototype.toString = function (format) { - return this.buffer.toString(format); - }; - /** @internal */ - Binary.prototype.toExtendedJSON = function (options) { - options = options || {}; - var base64String = this.buffer.toString('base64'); - var subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - }; - Binary.prototype.toUUID = function () { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID(this.buffer.slice(0, this.position)); - } - throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); - }; - /** @internal */ - Binary.fromExtendedJSON = function (doc, options) { - options = options || {}; - var data; - var type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = Buffer.from(doc.$binary, 'base64'); - } - else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = Buffer.from(doc.$binary.base64, 'base64'); - } - } - } - else if ('$uuid' in doc) { - type = 4; - data = uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); - } - return new Binary(data, type); - }; - /** @internal */ - Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Binary.prototype.inspect = function () { - var asBuffer = this.value(true); - return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; - }; - /** - * Binary default subtype - * @internal - */ - Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** Initial buffer default size */ - Binary.BUFFER_SIZE = 256; - /** Default BSON type */ - Binary.SUBTYPE_DEFAULT = 0; - /** Function BSON type */ - Binary.SUBTYPE_FUNCTION = 1; - /** Byte Array BSON type */ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ - Binary.SUBTYPE_UUID_OLD = 3; - /** UUID BSON type */ - Binary.SUBTYPE_UUID = 4; - /** MD5 BSON type */ - Binary.SUBTYPE_MD5 = 5; - /** Encrypted BSON type */ - Binary.SUBTYPE_ENCRYPTED = 6; - /** Column BSON type */ - Binary.SUBTYPE_COLUMN = 7; - /** User BSON type */ - Binary.SUBTYPE_USER_DEFINED = 128; - return Binary; -}()); -Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); - -/** - * A class representation of the BSON Code type. - * @public - */ -var Code = /** @class */ (function () { - /** - * @param code - a string or function. - * @param scope - an optional scope for the function. - */ - function Code(code, scope) { - if (!(this instanceof Code)) - return new Code(code, scope); - this.code = code; - this.scope = scope; - } - Code.prototype.toJSON = function () { - return { code: this.code, scope: this.scope }; - }; - /** @internal */ - Code.prototype.toExtendedJSON = function () { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - }; - /** @internal */ - Code.fromExtendedJSON = function (doc) { - return new Code(doc.$code, doc.$scope); - }; - /** @internal */ - Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Code.prototype.inspect = function () { - var codeJson = this.toJSON(); - return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; - }; - return Code; -}()); -Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); - -/** @internal */ -function isDBRefLike(value) { - return (isObjectLike(value) && - value.$id != null && - typeof value.$ref === 'string' && - (value.$db == null || typeof value.$db === 'string')); -} -/** - * A class representation of the BSON DBRef type. - * @public - */ -var DBRef = /** @class */ (function () { - /** - * @param collection - the collection name. - * @param oid - the reference ObjectId. - * @param db - optional db name, if omitted the reference is local to the current db. - */ - function DBRef(collection, oid, db, fields) { - if (!(this instanceof DBRef)) - return new DBRef(collection, oid, db, fields); - // check if namespace has been provided - var parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - Object.defineProperty(DBRef.prototype, "namespace", { - // Property provided for compatibility with the 1.x parser - // the 1.x parser used a "namespace" property, while 4.x uses "collection" - /** @internal */ - get: function () { - return this.collection; - }, - set: function (value) { - this.collection = value; - }, - enumerable: false, - configurable: true - }); - DBRef.prototype.toJSON = function () { - var o = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o.$db = this.db; - return o; - }; - /** @internal */ - DBRef.prototype.toExtendedJSON = function (options) { - options = options || {}; - var o = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o; - } - if (this.db) - o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - }; - /** @internal */ - DBRef.fromExtendedJSON = function (doc) { - var copy = Object.assign({}, doc); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - }; - /** @internal */ - DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - DBRef.prototype.inspect = function () { - // NOTE: if OID is an ObjectId class it will just print the oid string. - var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; - }; - return DBRef; -}()); -Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); - -/** - * wasm optimizations, to do native i64 multiplication and divide - */ -var wasm = undefined; -try { - wasm = new WebAssembly.Instance(new WebAssembly.Module( - // prettier-ignore - new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; -} -catch (_a) { - // no wasm support -} -var TWO_PWR_16_DBL = 1 << 16; -var TWO_PWR_24_DBL = 1 << 24; -var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; -var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; -var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; -/** A cache of the Long representations of small integer values. */ -var INT_CACHE = {}; -/** A cache of the Long representations of small unsigned integer values. */ -var UINT_CACHE = {}; -/** - * A class representing a 64-bit integer - * @public - * @remarks - * The internal representation of a long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16 bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. - */ -var Long = /** @class */ (function () { - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * - * Acceptable signatures are: - * - Long(low, high, unsigned?) - * - Long(bigint, unsigned?) - * - Long(string, unsigned?) - * - * @param low - The low (signed) 32 bits of the long - * @param high - The high (signed) 32 bits of the long - * @param unsigned - Whether unsigned or not, defaults to signed - */ - function Long(low, high, unsigned) { - if (low === void 0) { low = 0; } - if (!(this instanceof Long)) - return new Long(low, high, unsigned); - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } - else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } - else { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - Object.defineProperty(this, '__isLong__', { - value: true, - configurable: false, - writable: false, - enumerable: false - }); - } - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. - * Each is assumed to use 32 bits. - * @param lowBits - The low 32 bits - * @param highBits - The high 32 bits - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBits = function (lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - }; - /** - * Returns a Long representing the given 32 bit integer value. - * @param value - The 32 bit integer in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromInt = function (value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } - else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromNumber = function (value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } - else { - if (value <= -TWO_PWR_63_DBL) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; - } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBigInt = function (value, unsigned) { - return Long.fromString(value.toString(), unsigned); - }; - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param str - The textual representation of the Long - * @param unsigned - Whether unsigned or not, defaults to signed - * @param radix - The radix in which the text is written (2-36), defaults to 10 - * @returns The corresponding Long value - */ - Long.fromString = function (str, unsigned, radix) { - if (str.length === 0) - throw Error('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - (radix = unsigned), (unsigned = false); - } - else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - var p; - if ((p = str.indexOf('-')) > 0) - throw Error('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } - else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - }; - /** - * Creates a Long from its byte representation. - * @param bytes - Byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @param le - Whether little or big endian, defaults to big endian - * @returns The corresponding Long value - */ - Long.fromBytes = function (bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - }; - /** - * Creates a Long from its little endian byte representation. - * @param bytes - Little endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesLE = function (bytes, unsigned) { - return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); - }; - /** - * Creates a Long from its big endian byte representation. - * @param bytes - Big endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesBE = function (bytes, unsigned) { - return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); - }; - /** - * Tests if the specified object is a Long. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Long.isLong = function (value) { - return isObjectLike(value) && value['__isLong__'] === true; - }; - /** - * Converts the specified value to a Long. - * @param unsigned - Whether unsigned or not, defaults to signed - */ - Long.fromValue = function (val, unsigned) { - if (typeof val === 'number') - return Long.fromNumber(val, unsigned); - if (typeof val === 'string') - return Long.fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); - }; - /** Returns the sum of this and the specified Long. */ - Long.prototype.add = function (addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** - * Returns the sum of this and the specified Long. - * @returns Sum - */ - Long.prototype.and = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - /** - * Compares this Long's value with the specified's. - * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater - */ - Long.prototype.compare = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - // At this point the sign bits are the same - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; - /** This is an alias of {@link Long.compare} */ - Long.prototype.comp = function (other) { - return this.compare(other); - }; - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. - * @returns Quotient - */ - Long.prototype.divide = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw Error('division by zero'); - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if (!this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } - else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } - else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } - else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } - else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return Long.UONE; - res = Long.UZERO; - } - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - /**This is an alias of {@link Long.divide} */ - Long.prototype.div = function (divisor) { - return this.divide(divisor); - }; - /** - * Tests if this Long's value equals the specified's. - * @param other - Other value - */ - Long.prototype.equals = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - /** This is an alias of {@link Long.equals} */ - Long.prototype.eq = function (other) { - return this.equals(other); - }; - /** Gets the high 32 bits as a signed integer. */ - Long.prototype.getHighBits = function () { - return this.high; - }; - /** Gets the high 32 bits as an unsigned integer. */ - Long.prototype.getHighBitsUnsigned = function () { - return this.high >>> 0; - }; - /** Gets the low 32 bits as a signed integer. */ - Long.prototype.getLowBits = function () { - return this.low; - }; - /** Gets the low 32 bits as an unsigned integer. */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low >>> 0; - }; - /** Gets the number of bits needed to represent the absolute value of this Long. */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - // Unsigned Longs are never negative - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - var val = this.high !== 0 ? this.high : this.low; - var bit; - for (bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - }; - /** Tests if this Long's value is greater than the specified's. */ - Long.prototype.greaterThan = function (other) { - return this.comp(other) > 0; - }; - /** This is an alias of {@link Long.greaterThan} */ - Long.prototype.gt = function (other) { - return this.greaterThan(other); - }; - /** Tests if this Long's value is greater than or equal the specified's. */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.comp(other) >= 0; - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.gte = function (other) { - return this.greaterThanOrEqual(other); - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.ge = function (other) { - return this.greaterThanOrEqual(other); - }; - /** Tests if this Long's value is even. */ - Long.prototype.isEven = function () { - return (this.low & 1) === 0; - }; - /** Tests if this Long's value is negative. */ - Long.prototype.isNegative = function () { - return !this.unsigned && this.high < 0; - }; - /** Tests if this Long's value is odd. */ - Long.prototype.isOdd = function () { - return (this.low & 1) === 1; - }; - /** Tests if this Long's value is positive. */ - Long.prototype.isPositive = function () { - return this.unsigned || this.high >= 0; - }; - /** Tests if this Long's value equals zero. */ - Long.prototype.isZero = function () { - return this.high === 0 && this.low === 0; - }; - /** Tests if this Long's value is less than the specified's. */ - Long.prototype.lessThan = function (other) { - return this.comp(other) < 0; - }; - /** This is an alias of {@link Long#lessThan}. */ - Long.prototype.lt = function (other) { - return this.lessThan(other); - }; - /** Tests if this Long's value is less than or equal the specified's. */ - Long.prototype.lessThanOrEqual = function (other) { - return this.comp(other) <= 0; - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.lte = function (other) { - return this.lessThanOrEqual(other); - }; - /** Returns this Long modulo the specified. */ - Long.prototype.modulo = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.mod = function (divisor) { - return this.modulo(divisor); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.rem = function (divisor) { - return this.modulo(divisor); - }; - /** - * Returns the product of this and the specified Long. - * @param multiplier - Multiplier - * @returns Product - */ - Long.prototype.multiply = function (multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - // use wasm support if present - if (wasm) { - var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } - else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - // If both longs are small, use float multiplication - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** This is an alias of {@link Long.multiply} */ - Long.prototype.mul = function (multiplier) { - return this.multiply(multiplier); - }; - /** Returns the Negation of this Long's value. */ - Long.prototype.negate = function () { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); - }; - /** This is an alias of {@link Long.negate} */ - Long.prototype.neg = function () { - return this.negate(); - }; - /** Returns the bitwise NOT of this Long. */ - Long.prototype.not = function () { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - }; - /** Tests if this Long's value differs from the specified's. */ - Long.prototype.notEquals = function (other) { - return !this.equals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.neq = function (other) { - return this.notEquals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.ne = function (other) { - return this.notEquals(other); - }; - /** - * Returns the bitwise OR of this Long and the specified. - */ - Long.prototype.or = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftLeft = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - }; - /** This is an alias of {@link Long.shiftLeft} */ - Long.prototype.shl = function (numBits) { - return this.shiftLeft(numBits); - }; - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRight = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - }; - /** This is an alias of {@link Long.shiftRight} */ - Long.prototype.shr = function (numBits) { - return this.shiftRight(numBits); - }; - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } - else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shr_u = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shru = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** - * Returns the difference of this and the specified Long. - * @param subtrahend - Subtrahend - * @returns Difference - */ - Long.prototype.subtract = function (subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - /** This is an alias of {@link Long.subtract} */ - Long.prototype.sub = function (subtrahend) { - return this.subtract(subtrahend); - }; - /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ - Long.prototype.toInt = function () { - return this.unsigned ? this.low >>> 0 : this.low; - }; - /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ - Long.prototype.toNumber = function () { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - /** Converts the Long to a BigInt (arbitrary precision). */ - Long.prototype.toBigInt = function () { - return BigInt(this.toString()); - }; - /** - * Converts this Long to its byte representation. - * @param le - Whether little or big endian, defaults to big endian - * @returns Byte representation - */ - Long.prototype.toBytes = function (le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - /** - * Converts this Long to its little endian byte representation. - * @returns Little endian byte representation - */ - Long.prototype.toBytesLE = function () { - var hi = this.high, lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - }; - /** - * Converts this Long to its big endian byte representation. - * @returns Big endian byte representation - */ - Long.prototype.toBytesBE = function () { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - }; - /** - * Converts this Long to signed. - */ - Long.prototype.toSigned = function () { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); - }; - /** - * Converts the Long to a string written in the specified radix. - * @param radix - Radix (2-36), defaults to 10 - * @throws RangeError If `radix` is out of range - */ - Long.prototype.toString = function (radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } - else - return '-' + this.neg().toString(radix); - } - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - // eslint-disable-next-line @typescript-eslint/no-this-alias - var rem = this; - var result = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - var digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - }; - /** Converts this Long to unsigned. */ - Long.prototype.toUnsigned = function () { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - }; - /** Returns the bitwise XOR of this Long and the given one. */ - Long.prototype.xor = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - /** This is an alias of {@link Long.isZero} */ - Long.prototype.eqz = function () { - return this.isZero(); - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.le = function (other) { - return this.lessThanOrEqual(other); - }; - /* - **************************************************************** - * BSON SPECIFIC ADDITIONS * - **************************************************************** - */ - Long.prototype.toExtendedJSON = function (options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; - }; - Long.fromExtendedJSON = function (doc, options) { - var result = Long.fromString(doc.$numberLong); - return options && options.relaxed ? result.toNumber() : result; - }; - /** @internal */ - Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Long.prototype.inspect = function () { - return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; - }; - Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); - /** Maximum unsigned value. */ - Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); - /** Signed zero */ - Long.ZERO = Long.fromInt(0); - /** Unsigned zero. */ - Long.UZERO = Long.fromInt(0, true); - /** Signed one. */ - Long.ONE = Long.fromInt(1); - /** Unsigned one. */ - Long.UONE = Long.fromInt(1, true); - /** Signed negative one. */ - Long.NEG_ONE = Long.fromInt(-1); - /** Maximum signed value. */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - /** Minimum signed value. */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - return Long; -}()); -Object.defineProperty(Long.prototype, '__isLong__', { value: true }); -Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); - -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Detect if the value is a digit -function isDigit(value) { - return !isNaN(parseInt(value, 10)); -} -// Divide two uint128 values -function divideu128(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (var i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - return { quotient: value, rem: _rem }; -} -// Multiply two Long values and return the 128 bit value -function multiply64x2(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - // Return the 128 bit result - return { high: productHigh, low: productLow }; -} -function lessThan(left, right) { - // Make values unsigned - var uhleft = left.high >>> 0; - var uhright = right.high >>> 0; - // Compare high bits first - if (uhleft < uhright) { - return true; - } - else if (uhleft === uhright) { - var ulleft = left.low >>> 0; - var ulright = right.low >>> 0; - if (ulleft < ulright) - return true; - } - return false; -} -function invalidErr(string, message) { - throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); -} -/** - * A class representation of the BSON Decimal128 type. - * @public - */ -var Decimal128 = /** @class */ (function () { - /** - * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, - * or a string representation as returned by .toString() - */ - function Decimal128(bytes) { - if (!(this instanceof Decimal128)) - return new Decimal128(bytes); - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } - else { - this.bytes = bytes; - } - } - /** - * Create a Decimal128 instance from a string representation - * - * @param representation - a numeric string representation. - */ - Decimal128.fromString = function (representation) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = new Long(0, 0); - // The low 17 digits of the significand - var significandLow = new Long(0, 0); - // The biased exponent - var biasedExponent = 0; - // Read index - var index = 0; - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (representation.length >= 7000) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - // Results - var stringMatch = representation.match(PARSE_STRING_REGEXP); - var infMatch = representation.match(PARSE_INF_REGEXP); - var nanMatch = representation.match(PARSE_NAN_REGEXP); - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - if (stringMatch) { - // full_match = stringMatch[0] - // sign = stringMatch[1] - var unsignedNumber = stringMatch[2]; - // stringMatch[3] is undefined if a whole number (ex "1", 12") - // but defined if a number w/ decimal in it (ex "1.0, 12.2") - var e = stringMatch[4]; - var expSign = stringMatch[5]; - var expNumber = stringMatch[6]; - // they provided e, but didn't give an exponent number. for ex "1e" - if (e && expNumber === undefined) - invalidErr(representation, 'missing exponent power'); - // they provided e, but didn't give a number before it. for ex "e1" - if (e && unsignedNumber === undefined) - invalidErr(representation, 'missing exponent base'); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - // Get the negative or positive sign - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - // Check if user passed Infinity or NaN - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - else if (representation[index] === 'N') { - return new Decimal128(Buffer.from(NAN_BUFFER)); - } - } - // Read all the digits - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) - invalidErr(representation, 'contains multiple periods'); - sawRadix = true; - index = index + 1; - continue; - } - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - // Only store 34 digits - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - if (sawRadix && !nDigitsRead) - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - // Read exponent if exists - if (representation[index] === 'e' || representation[index] === 'E') { - // Read exponent digits - var match = representation.substr(++index).match(EXPONENT_REGEX); - // No digits read - if (!match || !match[2]) - return new Decimal128(Buffer.from(NAN_BUFFER)); - // Get exponent - exponent = parseInt(match[0], 10); - // Adjust the index - index = index + match[0].length; - } - // Return not a number - if (representation[index]) - return new Decimal128(Buffer.from(NAN_BUFFER)); - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } - else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } - else { - exponent = exponent - radixPosition; - } - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit. can only do this if < significant digits than # stored. - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } - else { - // adjust to round - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } - else { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits) { - var endOfString = nDigitsRead; - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - // if negative, we need to increment again to account for - sign at start. - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - var dIdx = lastDigit; - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } - else { - return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - } - } - } - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } - else if (lastDigit - firstDigit < 17) { - var dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - else { - var dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - significandLow = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } - else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - dec.low = significand.low; - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - // Encode into a buffer - var buffer = Buffer.alloc(16); - index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - // Return the new Decimal128 - return new Decimal128(buffer); - }; - /** Create a string representation of the raw Decimal128 value */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) - significand[i] = 0; - // read pointer into significand - var index = 0; - // true if the number is zero - var is_zero = false; - // the most significant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: [0, 0, 0, 0] }; - // indexing variables - var j, k; - // Output string - var string = []; - // Unpack index - index = 0; - // Buffer reference - var buffer = this.bytes; - // Unpack the low 64bits into a long - // bits 96 - 127 - var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 64 - 95 - var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack the high 64bits into a long - // bits 32 - 63 - var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 0 - 31 - var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack index - index = 0; - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - // Decode combination field and exponent - // bits 1 - 5 - var combination = (high >> 26) & COMBINATION_MASK; - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } - else if (combination === COMBINATION_NAN) { - return 'NaN'; - } - else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } - else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - // unbiased exponent - var exponent = biased_exponent - EXPONENT_BIAS; - // Create string of significand digits - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0) { - is_zero = true; - } - else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Perform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) - continue; - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } - else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - // the exponent if scientific notation is used - var scientific_exponent = significand_digits - 1 + exponent; - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - // if there are too many significant digits, we should just be treating numbers - // as + or - 0 and using the non-scientific exponent (this is for the "invalid - // representation should be treated as 0/-0" spec cases in decimal128-1.json) - if (significand_digits > 34) { - string.push("" + 0); - if (exponent > 0) - string.push('E+' + exponent); - else if (exponent < 0) - string.push('E' + exponent); - return string.join(''); - } - string.push("" + significand[index++]); - significand_digits = significand_digits - 1; - if (significand_digits) { - string.push('.'); - } - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } - else { - string.push("" + scientific_exponent); - } - } - else { - // Regular format with no decimal place - if (exponent >= 0) { - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - } - else { - var radix_position = significand_digits + exponent; - // non-zero digits before radix - if (radix_position > 0) { - for (var i = 0; i < radix_position; i++) { - string.push("" + significand[index++]); - } - } - else { - string.push('0'); - } - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push("" + significand[index++]); - } - } - } - return string.join(''); - }; - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.prototype.toExtendedJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.fromExtendedJSON = function (doc) { - return Decimal128.fromString(doc.$numberDecimal); - }; - /** @internal */ - Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Decimal128.prototype.inspect = function () { - return "new Decimal128(\"" + this.toString() + "\")"; - }; - return Decimal128; -}()); -Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); - -/** - * A class representation of the BSON Double type. - * @public - */ -var Double = /** @class */ (function () { - /** - * Create a Double type - * - * @param value - the number we want to represent as a double. - */ - function Double(value) { - if (!(this instanceof Double)) - return new Double(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; - } - /** - * Access the number value. - * - * @returns returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - Double.prototype.toJSON = function () { - return this.value; - }; - Double.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - /** @internal */ - Double.prototype.toExtendedJSON = function (options) { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user - // explicitly provided `-0` then we need to ensure the sign makes it into the output - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: "-" + this.value.toFixed(1) }; - } - var $numberDouble; - if (Number.isInteger(this.value)) { - $numberDouble = this.value.toFixed(1); - if ($numberDouble.length >= 13) { - $numberDouble = this.value.toExponential(13).toUpperCase(); - } - } - else { - $numberDouble = this.value.toString(); - } - return { $numberDouble: $numberDouble }; - }; - /** @internal */ - Double.fromExtendedJSON = function (doc, options) { - var doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - }; - /** @internal */ - Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Double.prototype.inspect = function () { - var eJSON = this.toExtendedJSON(); - return "new Double(" + eJSON.$numberDouble + ")"; - }; - return Double; -}()); -Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); - -/** - * A class representation of a BSON Int32 type. - * @public - */ -var Int32 = /** @class */ (function () { - /** - * Create an Int32 type - * - * @param value - the number we want to represent as an int32. - */ - function Int32(value) { - if (!(this instanceof Int32)) - return new Int32(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value | 0; - } - /** - * Access the number value. - * - * @returns returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - Int32.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - Int32.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - Int32.prototype.toExtendedJSON = function (options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; - }; - /** @internal */ - Int32.fromExtendedJSON = function (doc, options) { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - }; - /** @internal */ - Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Int32.prototype.inspect = function () { - return "new Int32(" + this.valueOf() + ")"; - }; - return Int32; -}()); -Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); - -/** - * A class representation of the BSON MaxKey type. - * @public - */ -var MaxKey = /** @class */ (function () { - function MaxKey() { - if (!(this instanceof MaxKey)) - return new MaxKey(); - } - /** @internal */ - MaxKey.prototype.toExtendedJSON = function () { - return { $maxKey: 1 }; - }; - /** @internal */ - MaxKey.fromExtendedJSON = function () { - return new MaxKey(); - }; - /** @internal */ - MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MaxKey.prototype.inspect = function () { - return 'new MaxKey()'; - }; - return MaxKey; -}()); -Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); - -/** - * A class representation of the BSON MinKey type. - * @public - */ -var MinKey = /** @class */ (function () { - function MinKey() { - if (!(this instanceof MinKey)) - return new MinKey(); - } - /** @internal */ - MinKey.prototype.toExtendedJSON = function () { - return { $minKey: 1 }; - }; - /** @internal */ - MinKey.fromExtendedJSON = function () { - return new MinKey(); - }; - /** @internal */ - MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MinKey.prototype.inspect = function () { - return 'new MinKey()'; - }; - return MinKey; -}()); -Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); -// Unique sequence for the current process (initialized on first use) -var PROCESS_UNIQUE = null; -var kId = Symbol('id'); -/** - * A class representation of the BSON ObjectId type. - * @public - */ -var ObjectId = /** @class */ (function () { - /** - * Create an ObjectId type - * - * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. - */ - function ObjectId(inputId) { - if (!(this instanceof ObjectId)) - return new ObjectId(inputId); - // workingId is set based on type of input and whether valid id exists for the input - var workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer'); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = Buffer.from(inputId.toHexString(), 'hex'); - } - else { - workingId = inputId.id; - } - } - else { - workingId = inputId; - } - // the following cases use workingId to construct an ObjectId - if (workingId == null || typeof workingId === 'number') { - // The most common use case (blank id, new objectId instance) - // Generate a new id - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } - else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ensureBuffer(workingId); - } - else if (typeof workingId === 'string') { - if (workingId.length === 12) { - var bytes = Buffer.from(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes'); - } - } - else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = Buffer.from(workingId, 'hex'); - } - else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters'); - } - } - else { - throw new BSONTypeError('Argument passed in does not match the accepted types'); - } - // If we are caching the hex string - if (ObjectId.cacheHexString) { - this.__id = this.id.toString('hex'); - } - } - Object.defineProperty(ObjectId.prototype, "id", { - /** - * The ObjectId bytes - * @readonly - */ - get: function () { - return this[kId]; - }, - set: function (value) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = value.toString('hex'); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectId.prototype, "generationTime", { - /** - * The generation time of this ObjectId instance - * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch - */ - get: function () { - return this.id.readInt32BE(0); - }, - set: function (value) { - // Encode time into first 4 bytes - this.id.writeUInt32BE(value, 0); - }, - enumerable: false, - configurable: true - }); - /** Returns the ObjectId id as a 24 character hex string representation */ - ObjectId.prototype.toHexString = function () { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - var hexString = this.id.toString('hex'); - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - return hexString; - }; - /** - * Update the ObjectId index - * @privateRemarks - * Used in generating new ObjectId's on the driver - * @internal - */ - ObjectId.getInc = function () { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - }; - /** - * Generate a 12 byte id buffer used in ObjectId's - * - * @param time - pass in a second based timestamp. - */ - ObjectId.generate = function (time) { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - var inc = ObjectId.getInc(); - var buffer = Buffer.alloc(12); - // 4-byte timestamp - buffer.writeUInt32BE(time, 0); - // set PROCESS_UNIQUE if yet not initialized - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = randomBytes(5); - } - // 5-byte process unique - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - // 3-byte counter - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - return buffer; - }; - /** - * Converts the id into a 24 character hex string for printing - * - * @param format - The Buffer toString format parameter. - */ - ObjectId.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (format) - return this.id.toString(format); - return this.toHexString(); - }; - /** Converts to its JSON the 24 character hex string representation. */ - ObjectId.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this ObjectId with `otherID`. - * - * @param otherId - ObjectId instance to compare against. - */ - ObjectId.prototype.equals = function (otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (otherId instanceof ObjectId) { - return this.toString() === otherId.toString(); - } - if (typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - isUint8Array(this.id)) { - return otherId === Buffer.prototype.toString.call(this.id, 'latin1'); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return Buffer.from(otherId).equals(this.id); - } - if (typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function') { - return otherId.toHexString() === this.toHexString(); - } - return false; - }; - /** Returns the generation date (accurate up to the second) that this ID was generated. */ - ObjectId.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id.readUInt32BE(0); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - /** @internal */ - ObjectId.createPk = function () { - return new ObjectId(); - }; - /** - * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. - * - * @param time - an integer number representing a number of seconds. - */ - ObjectId.createFromTime = function (time) { - var buffer = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer.writeUInt32BE(time, 0); - // Return the new objectId - return new ObjectId(buffer); - }; - /** - * Creates an ObjectId from a hex string representation of an ObjectId. - * - * @param hexString - create a ObjectId from a passed in 24 character hexstring. - */ - ObjectId.createFromHexString = function (hexString) { - // Throw an error if it's not a valid setup - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - return new ObjectId(Buffer.from(hexString, 'hex')); - }; - /** - * Checks if a value is a valid bson ObjectId - * - * @param id - ObjectId instance to validate. - */ - ObjectId.isValid = function (id) { - if (id == null) - return false; - if (typeof id === 'number') { - return true; - } - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - if (id instanceof ObjectId) { - return true; - } - if (isUint8Array(id) && id.length === 12) { - return true; - } - // Duck-Typing detection of ObjectId like objects - if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { - if (typeof id.id === 'string') { - return id.id.length === 12; - } - return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); - } - return false; - }; - /** @internal */ - ObjectId.prototype.toExtendedJSON = function () { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - }; - /** @internal */ - ObjectId.fromExtendedJSON = function (doc) { - return new ObjectId(doc.$oid); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 24 character hex string representation. - * @internal - */ - ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - ObjectId.prototype.inspect = function () { - return "new ObjectId(\"" + this.toHexString() + "\")"; - }; - /** @internal */ - ObjectId.index = Math.floor(Math.random() * 0xffffff); - return ObjectId; -}()); -// Deprecated methods -Object.defineProperty(ObjectId.prototype, 'generate', { - value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') -}); -Object.defineProperty(ObjectId.prototype, 'getInc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId.prototype, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId, 'get_inc', { - value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); - -function alphabetize(str) { - return str.split('').sort().join(''); -} -/** - * A class representation of the BSON RegExp type. - * @public - */ -var BSONRegExp = /** @class */ (function () { - /** - * @param pattern - The regular expression pattern to match - * @param options - The regular expression options - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) - return new BSONRegExp(pattern, options); - this.pattern = pattern; - this.options = alphabetize(options !== null && options !== void 0 ? options : ''); - if (this.pattern.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); - } - if (this.options.indexOf('\x00') !== -1) { - throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); - } - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u')) { - throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported"); - } - } - } - BSONRegExp.parseOptions = function (options) { - return options ? options.split('').sort().join('') : ''; - }; - /** @internal */ - BSONRegExp.prototype.toExtendedJSON = function (options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - }; - /** @internal */ - BSONRegExp.fromExtendedJSON = function (doc) { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - // This is for $regex query operators that have extended json values. - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc; - } - } - else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); - } - throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); - }; - return BSONRegExp; -}()); -Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); - -/** - * A class representation of the BSON Symbol type. - * @public - */ -var BSONSymbol = /** @class */ (function () { - /** - * @param value - the string representing the symbol. - */ - function BSONSymbol(value) { - if (!(this instanceof BSONSymbol)) - return new BSONSymbol(value); - this.value = value; - } - /** Access the wrapped string value. */ - BSONSymbol.prototype.valueOf = function () { - return this.value; - }; - BSONSymbol.prototype.toString = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.inspect = function () { - return "new BSONSymbol(\"" + this.value + "\")"; - }; - BSONSymbol.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.toExtendedJSON = function () { - return { $symbol: this.value }; - }; - /** @internal */ - BSONSymbol.fromExtendedJSON = function (doc) { - return new BSONSymbol(doc.$symbol); - }; - /** @internal */ - BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - return BSONSymbol; -}()); -Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); - -/** @public */ -var LongWithoutOverridesClass = Long; -/** @public */ -var Timestamp = /** @class */ (function (_super) { - __extends(Timestamp, _super); - function Timestamp(low, high) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - ///@ts-expect-error - if (!(_this instanceof Timestamp)) - return new Timestamp(low, high); - if (Long.isLong(low)) { - _this = _super.call(this, low.low, low.high, true) || this; - } - else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { - _this = _super.call(this, low.i, low.t, true) || this; - } - else { - _this = _super.call(this, low, high, true) || this; - } - Object.defineProperty(_this, '_bsontype', { - value: 'Timestamp', - writable: false, - configurable: false, - enumerable: false - }); - return _this; - } - Timestamp.prototype.toJSON = function () { - return { - $timestamp: this.toString() - }; - }; - /** Returns a Timestamp represented by the given (32-bit) integer value. */ - Timestamp.fromInt = function (value) { - return new Timestamp(Long.fromInt(value, true)); - }; - /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ - Timestamp.fromNumber = function (value) { - return new Timestamp(Long.fromNumber(value, true)); - }; - /** - * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. - * - * @param lowBits - the low 32-bits. - * @param highBits - the high 32-bits. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - /** - * Returns a Timestamp from the given string, optionally using the given radix. - * - * @param str - the textual representation of the Timestamp. - * @param optRadix - the radix in which the text is written. - */ - Timestamp.fromString = function (str, optRadix) { - return new Timestamp(Long.fromString(str, true, optRadix)); - }; - /** @internal */ - Timestamp.prototype.toExtendedJSON = function () { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - }; - /** @internal */ - Timestamp.fromExtendedJSON = function (doc) { - return new Timestamp(doc.$timestamp); - }; - /** @internal */ - Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Timestamp.prototype.inspect = function () { - return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; - }; - Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - return Timestamp; -}(LongWithoutOverridesClass)); - -function isBSONType(value) { - return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); -} -// INT32 boundaries -var BSON_INT32_MAX$1 = 0x7fffffff; -var BSON_INT32_MIN$1 = -0x80000000; -// INT64 boundaries -var BSON_INT64_MAX$1 = 0x7fffffffffffffff; -var BSON_INT64_MIN$1 = -0x8000000000000000; -// all the types where we don't need to do any special processing and can just pass the EJSON -//straight to type.fromExtendedJSON -var keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function deserializeValue(value, options) { - if (options === void 0) { options = {}; } - if (typeof value === 'number') { - if (options.relaxed || options.legacy) { - return value; - } - // if it's an integer, should interpret as smallest BSON integer - // that can represent it exactly. (if out of range, interpret as double.) - if (Math.floor(value) === value) { - if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1) - return new Int32(value); - if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) - return Long.fromNumber(value); - } - // If the number is a non-integer or out of integer range, should interpret as BSON Double. - return new Double(value); - } - // from here on out we're looking for bson types, so bail if its not an object - if (value == null || typeof value !== 'object') - return value; - // upgrade deprecated undefined to null - if (value.$undefined) - return null; - var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); - for (var i = 0; i < keys.length; i++) { - var c = keysToCodecs[keys[i]]; - if (c) - return c.fromExtendedJSON(value, options); - } - if (value.$date != null) { - var d = value.$date; - var date = new Date(); - if (options.legacy) { - if (typeof d === 'number') - date.setTime(d); - else if (typeof d === 'string') - date.setTime(Date.parse(d)); - } - else { - if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (Long.isLong(d)) - date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) - date.setTime(d); - } - return date; - } - if (value.$code != null) { - var copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return Code.fromExtendedJSON(value); - } - if (isDBRefLike(value) || value.$dbPointer) { - var v = value.$ref ? value : value.$dbPointer; - // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) - // because of the order JSON.parse goes through the document - if (v instanceof DBRef) - return v; - var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); - var valid_1 = true; - dollarKeys.forEach(function (k) { - if (['$ref', '$id', '$db'].indexOf(k) === -1) - valid_1 = false; - }); - // only make DBRef if $ keys are all valid - if (valid_1) - return DBRef.fromExtendedJSON(v); - } - return value; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeArray(array, options) { - return array.map(function (v, index) { - options.seenObjects.push({ propertyName: "index " + index, obj: null }); - try { - return serializeValue(v, options); - } - finally { - options.seenObjects.pop(); - } - }); -} -function getISOString(date) { - var isoStr = date.toISOString(); - // we should only show milliseconds in timestamp if they're non-zero - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeValue(value, options) { - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); - if (index !== -1) { - var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); - var leadingPart = props - .slice(0, index) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var alreadySeen = props[index]; - var circularPart = ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var current = props[props.length - 1]; - var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new BSONTypeError('Converting circular structure to EJSON:\n' + - (" " + leadingPart + alreadySeen + circularPart + current + "\n") + - (" " + leadingSpace + "\\" + dashes + "/")); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || isDate(value)) { - var dateNum = value.getTime(), - // is it in year range 1970-9999? - inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - // it's an integer - if (Math.floor(value) === value) { - var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; - // interpret as being of the smallest BSON integer type that can represent the number exactly - if (int32Range) - return { $numberInt: value.toString() }; - if (int64Range) - return { $numberLong: value.toString() }; - } - return { $numberDouble: value.toString() }; - } - if (value instanceof RegExp || isRegExp(value)) { - var flags = value.flags; - if (flags === undefined) { - var match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - var rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - if (value != null && typeof value === 'object') - return serializeDocument(value, options); - return value; -} -var BSON_TYPE_MAPPINGS = { - Binary: function (o) { return new Binary(o.value(), o.sub_type); }, - Code: function (o) { return new Code(o.code, o.scope); }, - DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, - Decimal128: function (o) { return new Decimal128(o.bytes); }, - Double: function (o) { return new Double(o.value); }, - Int32: function (o) { return new Int32(o.value); }, - Long: function (o) { - return Long.fromBits( - // underscore variants for 1.x backwards compatibility - o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); - }, - MaxKey: function () { return new MaxKey(); }, - MinKey: function () { return new MinKey(); }, - ObjectID: function (o) { return new ObjectId(o); }, - ObjectId: function (o) { return new ObjectId(o); }, - BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); }, - Symbol: function (o) { return new BSONSymbol(o.value); }, - Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); } -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeDocument(doc, options) { - if (doc == null || typeof doc !== 'object') - throw new BSONError('not an object instance'); - var bsontype = doc._bsontype; - if (typeof bsontype === 'undefined') { - // It's a regular object. Recursively serialize its property values. - var _doc = {}; - for (var name in doc) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - _doc[name] = serializeValue(doc[name], options); - } - finally { - options.seenObjects.pop(); - } - } - return _doc; - } - else if (isBSONType(doc)) { - // the "document" is really just a BSON type object - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var outDoc = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - // There's no EJSON serialization function on the object. It's probably an - // object created by a previous version of this library (or another library) - // that's duck-typing objects to look like they were generated by this library). - // Copy the object into this library's version of that type. - var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - // Two BSON types may have nested objects that may need to be serialized too - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } - else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); - } - return outDoc.toExtendedJSON(options); - } - else { - throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } -} -/** - * EJSON parse / stringify API - * @public - */ -// the namespace here is used to emulate `export * as EJSON from '...'` -// which as of now (sept 2020) api-extractor does not support -// eslint-disable-next-line @typescript-eslint/no-namespace -var EJSON; -(function (EJSON) { - /** - * Parse an Extended JSON string, constructing the JavaScript value or object described by that - * string. - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const text = '{ "int32": { "$numberInt": "10" } }'; - * - * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } - * console.log(EJSON.parse(text, { relaxed: false })); - * - * // prints { int32: 10 } - * console.log(EJSON.parse(text)); - * ``` - */ - function parse(text, options) { - var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); - // relaxed implies not strict - if (typeof finalOptions.relaxed === 'boolean') - finalOptions.strict = !finalOptions.relaxed; - if (typeof finalOptions.strict === 'boolean') - finalOptions.relaxed = !finalOptions.strict; - return JSON.parse(text, function (key, value) { - if (key.indexOf('\x00') !== -1) { - throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); - } - return deserializeValue(value, finalOptions); - }); - } - EJSON.parse = parse; - /** - * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer - * function is specified or optionally including only the specified properties if a replacer array - * is specified. - * - * @param value - The value to convert to extended JSON - * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string - * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. - * @param options - Optional settings - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const Int32 = require('mongodb').Int32; - * const doc = { int32: new Int32(10) }; - * - * // prints '{"int32":{"$numberInt":"10"}}' - * console.log(EJSON.stringify(doc, { relaxed: false })); - * - * // prints '{"int32":10}' - * console.log(EJSON.stringify(doc)); - * ``` - */ - function stringify(value, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - replacer, space, options) { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - var doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer, space); - } - EJSON.stringify = stringify; - /** - * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - * - * @param value - The object to serialize - * @param options - Optional settings passed to the `stringify` function - */ - function serialize(value, options) { - options = options || {}; - return JSON.parse(stringify(value, options)); - } - EJSON.serialize = serialize; - /** - * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - * - * @param ejson - The Extended JSON object to deserialize - * @param options - Optional settings passed to the parse method - */ - function deserialize(ejson, options) { - options = options || {}; - return parse(JSON.stringify(ejson), options); - } - EJSON.deserialize = deserialize; -})(EJSON || (EJSON = {})); - -/* eslint-disable @typescript-eslint/no-explicit-any */ -/** @public */ -var bsonMap; -var bsonGlobal = getGlobal(); -if (bsonGlobal.Map) { - bsonMap = bsonGlobal.Map; -} -else { - // We will return a polyfill - bsonMap = /** @class */ (function () { - function Map(array) { - if (array === void 0) { array = []; } - this._keys = []; - this._values = {}; - for (var i = 0; i < array.length; i++) { - if (array[i] == null) - continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - } - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) - return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - Map.prototype.entries = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? [key, _this._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.forEach = function (callback, self) { - self = self || this; - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - Map.prototype.keys = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - Map.prototype.values = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? _this._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Object.defineProperty(Map.prototype, "size", { - get: function () { - return this._keys.length; - }, - enumerable: false, - configurable: true - }); - return Map; - }()); -} - -/** @internal */ -var BSON_INT32_MAX = 0x7fffffff; -/** @internal */ -var BSON_INT32_MIN = -0x80000000; -/** @internal */ -var BSON_INT64_MAX = Math.pow(2, 63) - 1; -/** @internal */ -var BSON_INT64_MIN = -Math.pow(2, 63); -/** - * Any integer up to 2^53 can be precisely represented by a double. - * @internal - */ -var JS_INT_MAX = Math.pow(2, 53); -/** - * Any integer down to -2^53 can be precisely represented by a double. - * @internal - */ -var JS_INT_MIN = -Math.pow(2, 53); -/** Number BSON Type @internal */ -var BSON_DATA_NUMBER = 1; -/** String BSON Type @internal */ -var BSON_DATA_STRING = 2; -/** Object BSON Type @internal */ -var BSON_DATA_OBJECT = 3; -/** Array BSON Type @internal */ -var BSON_DATA_ARRAY = 4; -/** Binary BSON Type @internal */ -var BSON_DATA_BINARY = 5; -/** Binary BSON Type @internal */ -var BSON_DATA_UNDEFINED = 6; -/** ObjectId BSON Type @internal */ -var BSON_DATA_OID = 7; -/** Boolean BSON Type @internal */ -var BSON_DATA_BOOLEAN = 8; -/** Date BSON Type @internal */ -var BSON_DATA_DATE = 9; -/** null BSON Type @internal */ -var BSON_DATA_NULL = 10; -/** RegExp BSON Type @internal */ -var BSON_DATA_REGEXP = 11; -/** Code BSON Type @internal */ -var BSON_DATA_DBPOINTER = 12; -/** Code BSON Type @internal */ -var BSON_DATA_CODE = 13; -/** Symbol BSON Type @internal */ -var BSON_DATA_SYMBOL = 14; -/** Code with Scope BSON Type @internal */ -var BSON_DATA_CODE_W_SCOPE = 15; -/** 32 bit Integer BSON Type @internal */ -var BSON_DATA_INT = 16; -/** Timestamp BSON Type @internal */ -var BSON_DATA_TIMESTAMP = 17; -/** Long BSON Type @internal */ -var BSON_DATA_LONG = 18; -/** Decimal128 BSON Type @internal */ -var BSON_DATA_DECIMAL128 = 19; -/** MinKey BSON Type @internal */ -var BSON_DATA_MIN_KEY = 0xff; -/** MaxKey BSON Type @internal */ -var BSON_DATA_MAX_KEY = 0x7f; -/** Binary Default Type @internal */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** Binary Function Type @internal */ -var BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** Binary Byte Array Type @internal */ -var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ -var BSON_BINARY_SUBTYPE_UUID = 3; -/** Binary UUID Type @internal */ -var BSON_BINARY_SUBTYPE_UUID_NEW = 4; -/** Binary MD5 Type @internal */ -var BSON_BINARY_SUBTYPE_MD5 = 5; -/** Encrypted BSON type @internal */ -var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; -/** Column BSON type @internal */ -var BSON_BINARY_SUBTYPE_COLUMN = 7; -/** Binary User Defined Type @internal */ -var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } - else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - return totalLength; -} -/** @internal */ -function calculateElement(name, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -value, serializeFunctions, isArray, ignoreUndefined) { - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (isArray === void 0) { isArray = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = false; } - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && - value >= JS_INT_MIN && - value <= JS_INT_MAX) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } - else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } - else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } - else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - isAnyArrayBuffer(value)) { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); - } - else if (value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } - else if (value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1); - } - } - else if (value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4)); - } - else { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); - } - } - else if (value['_bsontype'] === 'Symbol') { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - Buffer.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1); - } - else if (value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - // Add db reference if it exists - if (value.db != null) { - ordered_values['$db'] = value.db; - } - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined)); - } - else if (value instanceof RegExp || isRegExp(value)) { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else if (value['_bsontype'] === 'BSONRegExp') { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.pattern, 'utf8') + - 1 + - Buffer.byteLength(value.options, 'utf8') + - 1); - } - else { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + - 1); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined)); - } - else if (serializeFunctions) { - return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1); - } - } - } - return 0; -} - -var FIRST_BIT = 0x80; -var FIRST_TWO_BITS = 0xc0; -var FIRST_THREE_BITS = 0xe0; -var FIRST_FOUR_BITS = 0xf0; -var FIRST_FIVE_BITS = 0xf8; -var TWO_BIT_CHAR = 0xc0; -var THREE_BIT_CHAR = 0xe0; -var FOUR_BIT_CHAR = 0xf0; -var CONTINUING_CHAR = 0x80; -/** - * Determines if the passed in bytes are valid utf8 - * @param bytes - An array of 8-bit bytes. Must be indexable and have length property - * @param start - The index to start validating - * @param end - The index to end validating - */ -function validateUtf8(bytes, start, end) { - var continuation = 0; - for (var i = start; i < end; i += 1) { - var byte = bytes[i]; - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } - else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } - else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } - else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } - else { - return false; - } - } - } - return !continuation; -} - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); -var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); -var functionCache = {}; -function deserialize$1(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (size < 5) { - throw new BSONError("bson size must be >= 5, is " + size); - } - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); - } - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); - } - if (size + index > buffer.byteLength) { - throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); - } - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -} -var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; -function deserializeObject(buffer, index, options, isArray) { - if (isArray === void 0) { isArray = false; } - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - // Ensures default validation option if none given - var validation = options.validation == null ? { utf8: true } : options.validation; - // Shows if global utf-8 validation is enabled or disabled - var globalUTFValidation = true; - // Reflects utf-8 validation setting regardless of global or specific key validation - var validationSetting; - // Set of keys either to enable or disable validation on - var utf8KeysSet = new Set(); - // Check for boolean uniformity and empty validation option - var utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } - else { - globalUTFValidation = false; - var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - // Ensures boolean uniformity in utf-8 validation (all true or all false) - if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) { - throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - // Add keys to set that will either be validated or not based on validationSetting - if (!globalUTFValidation) { - for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) { - var key = _a[_i]; - utf8KeysSet.add(key); - } - } - // Set the start index - var startIndex = index; - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) - throw new BSONError('corrupt bson message < 5 bytes long'); - // Read the document size - var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) - throw new BSONError('corrupt bson message'); - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - var done = false; - var isPossibleDBRef = isArray ? false : null; - // While we have more left data left keep parsing - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) - break; - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.byteLength) - throw new BSONError('Bad BSON Document: illegal CString'); - // Represents the key - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - // shouldValidateKey is true if the key should be validated, false otherwise - var shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } - else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - var value = void 0; - index = i + 1; - if (elementType === BSON_DATA_STRING) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } - else if (elementType === BSON_DATA_OID) { - var oid = Buffer.alloc(12); - buffer.copy(oid, 0, index, index + 12); - value = new ObjectId(oid); - index = index + 12; - } - else if (elementType === BSON_DATA_INT && promoteValues === false) { - value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); - } - else if (elementType === BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } - else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { - value = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } - else if (elementType === BSON_DATA_NUMBER) { - value = buffer.readDoubleLE(index); - index = index + 8; - } - else if (elementType === BSON_DATA_DATE) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new Long(lowBits, highBits).toNumber()); - } - else if (elementType === BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } - else if (elementType === BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new BSONError('bad embedded document length in bson'); - // We have a raw value - if (raw) { - value = buffer.slice(index, index + objectSize); - } - else { - var objectOptions = options; - if (!globalUTFValidation) { - objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - index = index + objectSize; - } - else if (elementType === BSON_DATA_ARRAY) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - // Stop index - var stopIndex = index + objectSize; - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) { - arrayOptions[n] = options[n]; - } - arrayOptions['raw'] = true; - } - if (!globalUTFValidation) { - arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - if (buffer[index - 1] !== 0) - throw new BSONError('invalid array terminator byte'); - if (index !== stopIndex) - throw new BSONError('corrupted array bson'); - } - else if (elementType === BSON_DATA_UNDEFINED) { - value = undefined; - } - else if (elementType === BSON_DATA_NULL) { - value = null; - } - else if (elementType === BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } - else { - value = long; - } - } - else if (elementType === BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = Buffer.alloc(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { - value = decimal128.toObject(); - } - else { - value = decimal128; - } - } - else if (elementType === BSON_DATA_BINARY) { - var binarySize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - // Did we have a negative binary size, throw - if (binarySize < 0) - throw new BSONError('Negative binary type element size found'); - // Is the length longer than the document - if (binarySize > buffer.byteLength) - throw new BSONError('Binary type size larger than document size'); - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - if (promoteBuffers && promoteValues) { - value = buffer.slice(index, index + binarySize); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - } - } - else { - var _buffer = Buffer.alloc(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - if (promoteBuffers && promoteValues) { - value = _buffer; - } - else { - value = new Binary(_buffer, subType); - } - } - // Update the index - index = index + binarySize; - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - value = new RegExp(source, optionsArray.join('')); - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // Set the object - value = new BSONRegExp(source, regExpOptions); - } - else if (elementType === BSON_DATA_SYMBOL) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new BSONSymbol(symbol); - index = index + stringSize; - } - else if (elementType === BSON_DATA_TIMESTAMP) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Timestamp(lowBits, highBits); - } - else if (elementType === BSON_DATA_MIN_KEY) { - value = new MinKey(); - } - else if (elementType === BSON_DATA_MAX_KEY) { - value = new MaxKey(); - } - else if (elementType === BSON_DATA_CODE) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - } - else { - value = new Code(functionString); - } - // Update parse index position - index = index + stringSize; - } - else if (elementType === BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError('code_w_scope total size shorter minimum expected length'); - } - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - // Javascript function - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // Update parse index position - index = index + stringSize; - // Parse the element - var _index = index; - // Decode the size of the object document - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - // Check if field length is too short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too short, truncating scope'); - } - // Check if totalSize field is too long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too long, clips outer document'); - } - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - value.scope = scopeObject; - } - else { - value = new Code(functionString, scopeObject); - } - } - else if (elementType === BSON_DATA_DBPOINTER) { - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) - throw new BSONError('bad string length in bson'); - // Namespace - if (validation != null && validation.utf8) { - if (!validateUtf8(buffer, index, index + stringSize - 1)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - } - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Read the oid - var oidBuffer = Buffer.alloc(12); - buffer.copy(oidBuffer, 0, index, index + 12); - var oid = new ObjectId(oidBuffer); - // Update the index - index = index + 12; - // Upgrade to DBRef type - value = new DBRef(namespace, oid); - } - else { - throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value: value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - object[name] = value; - } - } - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) - throw new BSONError('corrupt array bson'); - throw new BSONError('corrupt object bson'); - } - // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef - if (!isPossibleDBRef) - return object; - if (isDBRefLike(object)) { - var copy = Object.assign({}, object); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object.$ref, object.$id, object.$db, copy); - } - return object; -} -/** - * Ensure eval is isolated, store the result in functionCache. - * - * @internal - */ -function isolateEval(functionString, functionCache, object) { - if (!functionCache) - return new Function(functionString); - // Check for cache hit, eval if missing and return cached function - if (functionCache[functionString] == null) { - functionCache[functionString] = new Function(functionString); - } - // Set the object - return functionCache[functionString].bind(object); -} -function getValidatedString(buffer, start, end, shouldValidateUtf8) { - var value = buffer.toString('utf8', start, end); - // if utf8 validation is on, do the check - if (shouldValidateUtf8) { - for (var i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validateUtf8(buffer, start, end)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; -} - -// Copyright (c) 2008, Fair Oaks Labs, Inc. -function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { - var e; - var m; - var c; - var bBE = endian === 'big'; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = bBE ? nBytes - 1 : 0; - var d = bBE ? -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; - } - } - if (isNaN(value)) - m = 0; - while (mLen >= 8) { - buffer[offset + i] = m & 0xff; - i += d; - m /= 256; - mLen -= 8; - } - e = (e << mLen) | m; - if (isNaN(value)) - e += 8; - eLen += mLen; - while (eLen > 0) { - buffer[offset + i] = e & 0xff; - i += d; - e /= 256; - eLen -= 8; - } - buffer[offset + i - d] |= s * 128; -} - -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); -/* - * isArray indicates if we are writing to a BSON array (type 0x04) - * which forces the "key" which really an array index as a string to be written as ascii - * This will catch any errors in index as a string generation - */ -function serializeString(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, undefined, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -} -function serializeNumber(buffer, key, value, index, isArray) { - // We have an integer value - // TODO(NODE-2529): Add support for big int - if (Number.isInteger(value) && - value >= BSON_INT32_MIN && - value <= BSON_INT32_MAX) { - // If the value fits in 32 bits encode as int32 - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } - else { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - } - return index; -} -function serializeNull(buffer, key, _, index, isArray) { - // Set long type - buffer[index++] = BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeBoolean(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} -function serializeDate(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.ignoreCase) - buffer[index++] = 0x69; // i - if (value.global) - buffer[index++] = 0x73; // s - if (value.multiline) - buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -} -function serializeBSONRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.pattern, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; -} -function serializeMinMax(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON_DATA_NULL; - } - else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON_DATA_MIN_KEY; - } - else { - buffer[index++] = BSON_DATA_MAX_KEY; - } - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeObjectId(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, undefined, 'binary'); - } - else if (isUint8Array(value.id)) { - // Use the standard JS methods here because buffer.copy() is buggy with the - // browser polyfill - buffer.set(value.id.subarray(0, 12), index); - } - else { - throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - // Adjust index - return index + 12; -} -function serializeBuffer(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - buffer.set(ensureBuffer(value), index); - // Adjust the index - index = index + size; - return index; -} -function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (path === void 0) { path = []; } - for (var i = 0; i < path.length; i++) { - if (path[i] === value) - throw new BSONError('cyclic dependency detected'); - } - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - return endIndex; -} -function serializeDecimal128(buffer, key, value, index, isArray) { - buffer[index++] = BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - // Prefer the standard JS methods because their typechecking is not buggy, - // unlike the `buffer` polyfill's. - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; -} -function serializeLong(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = - value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeInt32(buffer, key, value, index, isArray) { - value = value.valueOf(); - // Set int type 32 bits or less - buffer[index++] = BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -} -function serializeDouble(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value.value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - return index; -} -function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} -function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Starting index - var startIndex = index; - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - // Writ the total - var totalSize = endIndex - startIndex; - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } - else { - buffer[index++] = BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - return index; -} -function serializeBinary(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - // Write the data to the object - buffer.set(data, index); - // Adjust the index - index = index + value.position; - return index; -} -function serializeSymbol(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} -function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var startIndex = index; - var output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; - } - output = Object.assign(output, value.fields); - var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} -function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (startingIndex === void 0) { startingIndex = 0; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (path === void 0) { path = []; } - startingIndex = startingIndex || 0; - path = path || []; - // Push the object to the path - path.push(object); - // Start place to serialize into - var index = startingIndex + 4; - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index, true); - } - else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } - else if (typeof value === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } - else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } - else if (typeof value === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } - else if (typeof value === 'object' && - isBSONType(value) && - value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else if (object instanceof bsonMap || isMap(object)) { - var iterator = object.entries(); - var done = false; - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = !!entry.done; - // Are we done, then skip and terminate - if (done) - continue; - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new BSONTypeError('toBSON function did not return an object'); - } - // Iterate over all the keys - for (var key in object) { - var value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - if (ignoreUndefined === false) - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - // Remove the path - path.pop(); - // Final padding byte for object - buffer[index++] = 0x00; - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -/** @internal */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; -// Current Internal Temporary Serialization Buffer -var buffer = Buffer.alloc(MAXSIZE); -/** - * Sets the size of the internal serialization buffer. - * - * @param size - The desired size for the internal serialization buffer - * @public - */ -function setInternalBufferSize(size) { - // Resize the internal serialization buffer if needed - if (buffer.length < size) { - buffer = Buffer.alloc(size); - } -} -/** - * Serialize a Javascript object. - * - * @param object - the Javascript object to serialize. - * @returns Buffer object containing the serialized object. - * @public - */ -function serialize(object, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = Buffer.alloc(minInternalBufferSize); - } - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = Buffer.alloc(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -} -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, - * useful when pre-allocating the space for serialization. - * - * @param object - the Javascript object to serialize. - * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. - * @returns the index pointing to the last written byte in the buffer. - * @public - */ -function serializeWithBufferAndIndex(object, finalBuffer, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - // Attempt to serialize - var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - // Return the index - return startIndex + serializationIndex - 1; -} -/** - * Deserialize data as BSON. - * - * @param buffer - the buffer containing the serialized set of BSON documents. - * @returns returns the deserialized Javascript Object. - * @public - */ -function deserialize(buffer, options) { - if (options === void 0) { options = {}; } - return deserialize$1(buffer instanceof Buffer ? buffer : ensureBuffer(buffer), options); -} -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param object - the Javascript object to calculate the BSON byte size for - * @returns size of BSON object in bytes - * @public - */ -function calculateObjectSize(object, options) { - if (options === void 0) { options = {}; } - options = options || {}; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); -} -/** - * Deserialize stream data as BSON documents. - * - * @param data - the buffer containing the serialized set of BSON documents. - * @param startIndex - the start index in the data Buffer where the deserialization is to start. - * @param numberOfDocuments - number of documents to deserialize. - * @param documents - an array where to store the deserialized documents. - * @param docStartIndex - the index in the documents array from where to start inserting documents. - * @param options - additional options used for the deserialization. - * @returns next index in the buffer after deserialization **x** numbers of documents. - * @public - */ -function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - var bufferData = ensureBuffer(data); - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - // Update options with index - internalOptions.index = index; - // Parse the document at this point - documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions); - // Adjust index by the document size - index = index + size; - } - // Return object containing end index of parsing and list of documents - return index; -} -/** - * BSON default export - * @deprecated Please use named exports - * @privateRemarks - * We want to someday deprecate the default export, - * so none of the new TS types are being exported on the default - * @public - */ -var BSON = { - Binary: Binary, - Code: Code, - DBRef: DBRef, - Decimal128: Decimal128, - Double: Double, - Int32: Int32, - Long: Long, - UUID: UUID, - Map: bsonMap, - MaxKey: MaxKey, - MinKey: MinKey, - ObjectId: ObjectId, - ObjectID: ObjectId, - BSONRegExp: BSONRegExp, - BSONSymbol: BSONSymbol, - Timestamp: Timestamp, - EJSON: EJSON, - setInternalBufferSize: setInternalBufferSize, - serialize: serialize, - serializeWithBufferAndIndex: serializeWithBufferAndIndex, - deserialize: deserialize, - calculateObjectSize: calculateObjectSize, - deserializeStream: deserializeStream, - BSONError: BSONError, - BSONTypeError: BSONTypeError -}; - -export default BSON; -export { BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize }; -//# sourceMappingURL=bson.esm.js.map diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.esm.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.esm.js.map deleted file mode 100644 index 0cfb9d7..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/dist/bson.esm.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bson.esm.js","sources":["../node_modules/tslib/tslib.es6.js","../src/error.ts","../src/utils/global.ts","../src/parser/utils.ts","../src/ensure_buffer.ts","../src/uuid_utils.ts","../src/uuid.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/extended_json.ts","../src/map.ts","../src/constants.ts","../src/parser/calculate_size.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/float_parser.ts","../src/parser/serializer.ts","../src/bson.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","constructor","prototype","create","__assign","assign","t","s","i","n","arguments","length","call","apply","kId","BSON_INT32_MAX","BSON_INT32_MIN","BSON_INT64_MAX","BSON_INT64_MIN","calculateObjectSize","constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","deserialize","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT","Map","internalSerialize","internalDeserialize","internalCalculateObjectSize"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AAEA,IAAIA,cAAa,GAAG,uBAASC,CAAT,EAAYC,CAAZ,EAAe;AAC/BF,EAAAA,cAAa,GAAGG,MAAM,CAACC,cAAP,IACX;AAAEC,IAAAA,SAAS,EAAE;AAAb,eAA6BC,KAA7B,IAAsC,UAAUL,CAAV,EAAaC,CAAb,EAAgB;AAAED,IAAAA,CAAC,CAACI,SAAF,GAAcH,CAAd;AAAkB,GAD/D,IAEZ,UAAUD,CAAV,EAAaC,CAAb,EAAgB;AAAE,SAAK,IAAIK,CAAT,IAAcL,CAAd;AAAiB,UAAIA,CAAC,CAACM,cAAF,CAAiBD,CAAjB,CAAJ,EAAyBN,CAAC,CAACM,CAAD,CAAD,GAAOL,CAAC,CAACK,CAAD,CAAR;AAA1C;AAAwD,GAF9E;;AAGA,SAAOP,cAAa,CAACC,CAAD,EAAIC,CAAJ,CAApB;AACH,CALD;;AAOO,SAASO,SAAT,CAAmBR,CAAnB,EAAsBC,CAAtB,EAAyB;AAC5BF,EAAAA,cAAa,CAACC,CAAD,EAAIC,CAAJ,CAAb;;AACA,WAASQ,EAAT,GAAc;AAAE,SAAKC,WAAL,GAAmBV,CAAnB;AAAuB;;AACvCA,EAAAA,CAAC,CAACW,SAAF,GAAcV,CAAC,KAAK,IAAN,GAAaC,MAAM,CAACU,MAAP,CAAcX,CAAd,CAAb,IAAiCQ,EAAE,CAACE,SAAH,GAAeV,CAAC,CAACU,SAAjB,EAA4B,IAAIF,EAAJ,EAA7D,CAAd;AACH;;AAEM,IAAII,OAAQ,GAAG,oBAAW;AAC7BA,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AA;IACN,QAAQ,UAAA;IACR,QAAQ,EAAE,QAAQ;IAClB,UAAU,YAAA;IACV,UAAU,YAAA;IACV,SAAS,WAAA;IACT,KAAK,OAAA;IACL,qBAAqB,uBAAA;IACrB,SAAS,WAAA;IACT,2BAA2B,6BAAA;IAC3B,WAAW,aAAA;IACX,mBAAmB,qBAAA;IACnB,iBAAiB,mBAAA;IACjB,SAAS,WAAA;IACT,aAAa,eAAA;;;;;;"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/etc/prepare.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/etc/prepare.js deleted file mode 100755 index 91e6f3a..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/etc/prepare.js +++ /dev/null @@ -1,19 +0,0 @@ -#! /usr/bin/env node -var cp = require('child_process'); -var fs = require('fs'); - -var nodeMajorVersion = +process.version.match(/^v(\d+)\.\d+/)[1]; - -if (fs.existsSync('src') && nodeMajorVersion >= 10) { - cp.spawnSync('npm', ['run', 'build'], { stdio: 'inherit', shell: true }); -} else { - if (!fs.existsSync('lib')) { - console.warn('BSON: No compiled javascript present, the library is not installed correctly.'); - if (nodeMajorVersion < 10) { - console.warn( - 'This library can only be compiled in nodejs version 10 or later, currently running: ' + - nodeMajorVersion - ); - } - } -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/binary.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/binary.js deleted file mode 100644 index 4aadc5a..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/binary.js +++ /dev/null @@ -1,239 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Binary = void 0; -var buffer_1 = require("buffer"); -var ensure_buffer_1 = require("./ensure_buffer"); -var uuid_utils_1 = require("./uuid_utils"); -var uuid_1 = require("./uuid"); -var error_1 = require("./error"); -/** - * A class representation of the BSON Binary type. - * @public - */ -var Binary = /** @class */ (function () { - /** - * @param buffer - a buffer object containing the binary data. - * @param subType - the option binary type. - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) - return new Binary(buffer, subType); - if (!(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer)) { - throw new error_1.BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); - } - this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer == null) { - // create an empty binary buffer - this.buffer = buffer_1.Buffer.alloc(Binary.BUFFER_SIZE); - this.position = 0; - } - else { - if (typeof buffer === 'string') { - // string - this.buffer = buffer_1.Buffer.from(buffer, 'binary'); - } - else if (Array.isArray(buffer)) { - // number[] - this.buffer = buffer_1.Buffer.from(buffer); - } - else { - // Buffer | TypedArray | ArrayBuffer - this.buffer = ensure_buffer_1.ensureBuffer(buffer); - } - this.position = this.buffer.byteLength; - } - } - /** - * Updates this binary with byte_value. - * - * @param byteValue - a single byte we wish to write. - */ - Binary.prototype.put = function (byteValue) { - // If it's a string and a has more than one character throw an error - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new error_1.BSONTypeError('only accepts single character String'); - } - else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new error_1.BSONTypeError('only accepts single character Uint8Array or Array'); - // Decode the byte value once - var decodedByte; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } - else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } - else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new error_1.BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); - } - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decodedByte; - } - else { - var buffer = buffer_1.Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decodedByte; - } - }; - /** - * Writes a buffer or string to the binary. - * - * @param sequence - a string or buffer to be written to the Binary BSON object. - * @param offset - specify the binary of where to write the content. - */ - Binary.prototype.write = function (sequence, offset) { - offset = typeof offset === 'number' ? offset : this.position; - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + sequence.length) { - var buffer = buffer_1.Buffer.alloc(this.buffer.length + sequence.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - // Assign the new buffer - this.buffer = buffer; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ensure_buffer_1.ensureBuffer(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } - else if (typeof sequence === 'string') { - this.buffer.write(sequence, offset, sequence.length, 'binary'); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - }; - /** - * Reads **length** bytes starting at **position**. - * - * @param position - read from the given position in the Binary. - * @param length - the number of bytes to read. - */ - Binary.prototype.read = function (position, length) { - length = length && length > 0 ? length : this.position; - // Let's return the data based on the type we have - return this.buffer.slice(position, position + length); - }; - /** - * Returns the value of this binary as a string. - * @param asRaw - Will skip converting to a string - * @remarks - * This is handy when calling this function conditionally for some key value pairs and not others - */ - Binary.prototype.value = function (asRaw) { - asRaw = !!asRaw; - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - // If it's a node.js buffer object - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return this.buffer.toString('binary', 0, this.position); - }; - /** the length of the binary sequence */ - Binary.prototype.length = function () { - return this.position; - }; - Binary.prototype.toJSON = function () { - return this.buffer.toString('base64'); - }; - Binary.prototype.toString = function (format) { - return this.buffer.toString(format); - }; - /** @internal */ - Binary.prototype.toExtendedJSON = function (options) { - options = options || {}; - var base64String = this.buffer.toString('base64'); - var subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - }; - Binary.prototype.toUUID = function () { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new uuid_1.UUID(this.buffer.slice(0, this.position)); - } - throw new error_1.BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); - }; - /** @internal */ - Binary.fromExtendedJSON = function (doc, options) { - options = options || {}; - var data; - var type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = buffer_1.Buffer.from(doc.$binary, 'base64'); - } - else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = buffer_1.Buffer.from(doc.$binary.base64, 'base64'); - } - } - } - else if ('$uuid' in doc) { - type = 4; - data = uuid_utils_1.uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new error_1.BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); - } - return new Binary(data, type); - }; - /** @internal */ - Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Binary.prototype.inspect = function () { - var asBuffer = this.value(true); - return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; - }; - /** - * Binary default subtype - * @internal - */ - Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** Initial buffer default size */ - Binary.BUFFER_SIZE = 256; - /** Default BSON type */ - Binary.SUBTYPE_DEFAULT = 0; - /** Function BSON type */ - Binary.SUBTYPE_FUNCTION = 1; - /** Byte Array BSON type */ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ - Binary.SUBTYPE_UUID_OLD = 3; - /** UUID BSON type */ - Binary.SUBTYPE_UUID = 4; - /** MD5 BSON type */ - Binary.SUBTYPE_MD5 = 5; - /** Encrypted BSON type */ - Binary.SUBTYPE_ENCRYPTED = 6; - /** Column BSON type */ - Binary.SUBTYPE_COLUMN = 7; - /** User BSON type */ - Binary.SUBTYPE_USER_DEFINED = 128; - return Binary; -}()); -exports.Binary = Binary; -Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); -//# sourceMappingURL=binary.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/binary.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/binary.js.map deleted file mode 100644 index a59b7f6..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/binary.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"binary.js","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,2CAAqD;AACrD,+BAA4C;AAE5C,iCAAmD;AAmBnD;;;GAGG;AACH;IAkCE;;;OAGG;IACH,gBAAY,MAAgC,EAAE,OAAgB;QAC5D,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAElE,IACE,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC;YACjB,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ,CAAC;YAC7B,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC;YAC3B,CAAC,CAAC,MAAM,YAAY,WAAW,CAAC;YAChC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EACtB;YACA,MAAM,IAAI,qBAAa,CACrB,kFAAkF,CACnF,CAAC;SACH;QAED,IAAI,CAAC,QAAQ,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,MAAM,CAAC,2BAA2B,CAAC;QAE9D,IAAI,MAAM,IAAI,IAAI,EAAE;YAClB,gCAAgC;YAChC,IAAI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_modules/mongodb-collection-sample/node_modules/bson/lib/bson.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/bson.js deleted file mode 100644 index 88cc59e..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/bson.js +++ /dev/null @@ -1,252 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.UUID = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0; -exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = exports.BSONTypeError = exports.BSONError = exports.ObjectID = exports.Decimal128 = void 0; -var buffer_1 = require("buffer"); -var binary_1 = require("./binary"); -Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return binary_1.Binary; } }); -var code_1 = require("./code"); -Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return code_1.Code; } }); -var db_ref_1 = require("./db_ref"); -Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return db_ref_1.DBRef; } }); -var decimal128_1 = require("./decimal128"); -Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return decimal128_1.Decimal128; } }); -var double_1 = require("./double"); -Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return double_1.Double; } }); -var ensure_buffer_1 = require("./ensure_buffer"); -var extended_json_1 = require("./extended_json"); -var int_32_1 = require("./int_32"); -Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return int_32_1.Int32; } }); -var long_1 = require("./long"); -Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return long_1.Long; } }); -var map_1 = require("./map"); -Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return map_1.Map; } }); -var max_key_1 = require("./max_key"); -Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return max_key_1.MaxKey; } }); -var min_key_1 = require("./min_key"); -Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return min_key_1.MinKey; } }); -var objectid_1 = require("./objectid"); -Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return objectid_1.ObjectId; } }); -Object.defineProperty(exports, "ObjectID", { enumerable: true, get: function () { return objectid_1.ObjectId; } }); -var error_1 = require("./error"); -var calculate_size_1 = require("./parser/calculate_size"); -// Parts of the parser -var deserializer_1 = require("./parser/deserializer"); -var serializer_1 = require("./parser/serializer"); -var regexp_1 = require("./regexp"); -Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return regexp_1.BSONRegExp; } }); -var symbol_1 = require("./symbol"); -Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return symbol_1.BSONSymbol; } }); -var timestamp_1 = require("./timestamp"); -Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_1.Timestamp; } }); -var uuid_1 = require("./uuid"); -Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return uuid_1.UUID; } }); -var constants_1 = require("./constants"); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_BYTE_ARRAY", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_BYTE_ARRAY; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_DEFAULT", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_DEFAULT; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_FUNCTION", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_FUNCTION; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_MD5", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_MD5; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_USER_DEFINED", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_USER_DEFINED; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID_NEW", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID_NEW; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_ENCRYPTED", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_ENCRYPTED; } }); -Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_COLUMN", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_COLUMN; } }); -Object.defineProperty(exports, "BSON_DATA_ARRAY", { enumerable: true, get: function () { return constants_1.BSON_DATA_ARRAY; } }); -Object.defineProperty(exports, "BSON_DATA_BINARY", { enumerable: true, get: function () { return constants_1.BSON_DATA_BINARY; } }); -Object.defineProperty(exports, "BSON_DATA_BOOLEAN", { enumerable: true, get: function () { return constants_1.BSON_DATA_BOOLEAN; } }); -Object.defineProperty(exports, "BSON_DATA_CODE", { enumerable: true, get: function () { return constants_1.BSON_DATA_CODE; } }); -Object.defineProperty(exports, "BSON_DATA_CODE_W_SCOPE", { enumerable: true, get: function () { return constants_1.BSON_DATA_CODE_W_SCOPE; } }); -Object.defineProperty(exports, "BSON_DATA_DATE", { enumerable: true, get: function () { return constants_1.BSON_DATA_DATE; } }); -Object.defineProperty(exports, "BSON_DATA_DBPOINTER", { enumerable: true, get: function () { return constants_1.BSON_DATA_DBPOINTER; } }); -Object.defineProperty(exports, "BSON_DATA_DECIMAL128", { enumerable: true, get: function () { return constants_1.BSON_DATA_DECIMAL128; } }); -Object.defineProperty(exports, "BSON_DATA_INT", { enumerable: true, get: function () { return constants_1.BSON_DATA_INT; } }); -Object.defineProperty(exports, "BSON_DATA_LONG", { enumerable: true, get: function () { return constants_1.BSON_DATA_LONG; } }); -Object.defineProperty(exports, "BSON_DATA_MAX_KEY", { enumerable: true, get: function () { return constants_1.BSON_DATA_MAX_KEY; } }); -Object.defineProperty(exports, "BSON_DATA_MIN_KEY", { enumerable: true, get: function () { return constants_1.BSON_DATA_MIN_KEY; } }); -Object.defineProperty(exports, "BSON_DATA_NULL", { enumerable: true, get: function () { return constants_1.BSON_DATA_NULL; } }); -Object.defineProperty(exports, "BSON_DATA_NUMBER", { enumerable: true, get: function () { return constants_1.BSON_DATA_NUMBER; } }); -Object.defineProperty(exports, "BSON_DATA_OBJECT", { enumerable: true, get: function () { return constants_1.BSON_DATA_OBJECT; } }); -Object.defineProperty(exports, "BSON_DATA_OID", { enumerable: true, get: function () { return constants_1.BSON_DATA_OID; } }); -Object.defineProperty(exports, "BSON_DATA_REGEXP", { enumerable: true, get: function () { return constants_1.BSON_DATA_REGEXP; } }); -Object.defineProperty(exports, "BSON_DATA_STRING", { enumerable: true, get: function () { return constants_1.BSON_DATA_STRING; } }); -Object.defineProperty(exports, "BSON_DATA_SYMBOL", { enumerable: true, get: function () { return constants_1.BSON_DATA_SYMBOL; } }); -Object.defineProperty(exports, "BSON_DATA_TIMESTAMP", { enumerable: true, get: function () { return constants_1.BSON_DATA_TIMESTAMP; } }); -Object.defineProperty(exports, "BSON_DATA_UNDEFINED", { enumerable: true, get: function () { return constants_1.BSON_DATA_UNDEFINED; } }); -Object.defineProperty(exports, "BSON_INT32_MAX", { enumerable: true, get: function () { return constants_1.BSON_INT32_MAX; } }); -Object.defineProperty(exports, "BSON_INT32_MIN", { enumerable: true, get: function () { return constants_1.BSON_INT32_MIN; } }); -Object.defineProperty(exports, "BSON_INT64_MAX", { enumerable: true, get: function () { return constants_1.BSON_INT64_MAX; } }); -Object.defineProperty(exports, "BSON_INT64_MIN", { enumerable: true, get: function () { return constants_1.BSON_INT64_MIN; } }); -var extended_json_2 = require("./extended_json"); -Object.defineProperty(exports, "EJSON", { enumerable: true, get: function () { return extended_json_2.EJSON; } }); -var timestamp_2 = require("./timestamp"); -Object.defineProperty(exports, "LongWithoutOverridesClass", { enumerable: true, get: function () { return timestamp_2.LongWithoutOverridesClass; } }); -var error_2 = require("./error"); -Object.defineProperty(exports, "BSONError", { enumerable: true, get: function () { return error_2.BSONError; } }); -Object.defineProperty(exports, "BSONTypeError", { enumerable: true, get: function () { return error_2.BSONTypeError; } }); -/** @internal */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; -// Current Internal Temporary Serialization Buffer -var buffer = buffer_1.Buffer.alloc(MAXSIZE); -/** - * Sets the size of the internal serialization buffer. - * - * @param size - The desired size for the internal serialization buffer - * @public - */ -function setInternalBufferSize(size) { - // Resize the internal serialization buffer if needed - if (buffer.length < size) { - buffer = buffer_1.Buffer.alloc(size); - } -} -exports.setInternalBufferSize = setInternalBufferSize; -/** - * Serialize a Javascript object. - * - * @param object - the Javascript object to serialize. - * @returns Buffer object containing the serialized object. - * @public - */ -function serialize(object, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = buffer_1.Buffer.alloc(minInternalBufferSize); - } - // Attempt to serialize - var serializationIndex = serializer_1.serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = buffer_1.Buffer.alloc(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -} -exports.serialize = serialize; -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, - * useful when pre-allocating the space for serialization. - * - * @param object - the Javascript object to serialize. - * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. - * @returns the index pointing to the last written byte in the buffer. - * @public - */ -function serializeWithBufferAndIndex(object, finalBuffer, options) { - if (options === void 0) { options = {}; } - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - // Attempt to serialize - var serializationIndex = serializer_1.serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - // Return the index - return startIndex + serializationIndex - 1; -} -exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; -/** - * Deserialize data as BSON. - * - * @param buffer - the buffer containing the serialized set of BSON documents. - * @returns returns the deserialized Javascript Object. - * @public - */ -function deserialize(buffer, options) { - if (options === void 0) { options = {}; } - return deserializer_1.deserialize(buffer instanceof buffer_1.Buffer ? buffer : ensure_buffer_1.ensureBuffer(buffer), options); -} -exports.deserialize = deserialize; -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param object - the Javascript object to calculate the BSON byte size for - * @returns size of BSON object in bytes - * @public - */ -function calculateObjectSize(object, options) { - if (options === void 0) { options = {}; } - options = options || {}; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - return calculate_size_1.calculateObjectSize(object, serializeFunctions, ignoreUndefined); -} -exports.calculateObjectSize = calculateObjectSize; -/** - * Deserialize stream data as BSON documents. - * - * @param data - the buffer containing the serialized set of BSON documents. - * @param startIndex - the start index in the data Buffer where the deserialization is to start. - * @param numberOfDocuments - number of documents to deserialize. - * @param documents - an array where to store the deserialized documents. - * @param docStartIndex - the index in the documents array from where to start inserting documents. - * @param options - additional options used for the deserialization. - * @returns next index in the buffer after deserialization **x** numbers of documents. - * @public - */ -function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - var bufferData = ensure_buffer_1.ensureBuffer(data); - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - // Update options with index - internalOptions.index = index; - // Parse the document at this point - documents[docStartIndex + i] = deserializer_1.deserialize(bufferData, internalOptions); - // Adjust index by the document size - index = index + size; - } - // Return object containing end index of parsing and list of documents - return index; -} -exports.deserializeStream = deserializeStream; -/** - * BSON default export - * @deprecated Please use named exports - * @privateRemarks - * We want to someday deprecate the default export, - * so none of the new TS types are being exported on the default - * @public - */ -var BSON = { - Binary: binary_1.Binary, - Code: code_1.Code, - DBRef: db_ref_1.DBRef, - Decimal128: decimal128_1.Decimal128, - Double: double_1.Double, - Int32: int_32_1.Int32, - Long: long_1.Long, - UUID: uuid_1.UUID, - Map: map_1.Map, - MaxKey: max_key_1.MaxKey, - MinKey: min_key_1.MinKey, - ObjectId: objectid_1.ObjectId, - ObjectID: objectid_1.ObjectId, - BSONRegExp: regexp_1.BSONRegExp, - BSONSymbol: symbol_1.BSONSymbol, - Timestamp: timestamp_1.Timestamp, - EJSON: extended_json_1.EJSON, - setInternalBufferSize: setInternalBufferSize, - serialize: serialize, - serializeWithBufferAndIndex: serializeWithBufferAndIndex, - deserialize: deserialize, - calculateObjectSize: calculateObjectSize, - deserializeStream: deserializeStream, - BSONError: error_1.BSONError, - BSONTypeError: error_1.BSONTypeError -}; -exports.default = BSON; -//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/bson.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/bson.js.map deleted file mode 100644 index a195407..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/bson.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;;AAAA,iCAAgC;AAChC,mCAAkC;AAoFhC,uFApFO,eAAM,OAoFP;AAnFR,+BAA8B;AA+E5B,qFA/EO,WAAI,OA+EP;AA9EN,mCAAiC;AAiF/B,sFAjFO,cAAK,OAiFP;AAhFP,2CAA0C;AA2FxC,2FA3FO,uBAAU,OA2FP;AA1FZ,mCAAkC;AAqFhC,uFArFO,eAAM,OAqFP;AApFR,iDAA+C;AAC/C,iDAAwC;AACxC,mCAAiC;AAmF/B,sFAnFO,cAAK,OAmFP;AAlFP,+BAA8B;AA+E5B,qFA/EO,WAAI,OA+EP;AA9EN,6BAA4B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KAAK,uBAAA;IACL,qBAAqB,uBAAA;IACrB,SAAS,WAAA;IACT,2BAA2B,6BAAA;IAC3B,WAAW,aAAA;IACX,mBAAmB,qBAAA;IACnB,iBAAiB,mBAAA;IACjB,SAAS,mBAAA;IACT,aAAa,uBAAA;CACd,CAAC;AACF,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/code.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/code.js deleted file mode 100644 index 4e6dc07..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/code.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Code = void 0; -/** - * A class representation of the BSON Code type. - * @public - */ -var Code = /** @class */ (function () { - /** - * @param code - a string or function. - * @param scope - an optional scope for the function. - */ - function Code(code, scope) { - if (!(this instanceof Code)) - return new Code(code, scope); - this.code = code; - this.scope = scope; - } - Code.prototype.toJSON = function () { - return { code: this.code, scope: this.scope }; - }; - /** @internal */ - Code.prototype.toExtendedJSON = function () { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - }; - /** @internal */ - Code.fromExtendedJSON = function (doc) { - return new Code(doc.$code, doc.$scope); - }; - /** @internal */ - Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Code.prototype.inspect = function () { - var codeJson = this.toJSON(); - return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; - }; - return Code; -}()); -exports.Code = Code; -Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); -//# sourceMappingURL=code.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/code.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/code.js.map deleted file mode 100644 index e1bf73f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/code.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"code.js","sourceRoot":"","sources":["../src/code.ts"],"names":[],"mappings":";;;AAQA;;;GAGG;AACH;IAKE;;;OAGG;IACH,cAAY,IAAuB,EAAE,KAAgB;QACnD,IAAI,CAAC,CAAC,IAAI,YAAY,IAAI,CAAC;YAAE,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAE1D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,qBAAM,GAAN;QACE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IAChD,CAAC;IAED,gBAAgB;IAChB,6BAAc,GAAd;QACE,IAAI,IAAI,CAAC,KAAK,EAAE;YACd,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;SACjD;QAED,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;IAC9B,CAAC;IAED,gBAAgB;IACT,qBAAgB,GAAvB,UAAwB,GAAiB;QACvC,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,gBAAgB;IAChB,eAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,sBAAO,GAAP;QACE,IAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC/B,OAAO,gBAAa,QAAQ,CAAC,IAAI,WAC/B,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,OAAK,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAG,CAAC,CAAC,CAAC,EAAE,OAC1D,CAAC;IACN,CAAC;IACH,WAAC;AAAD,CAAC,AA7CD,IA6CC;AA7CY,oBAAI;AA+CjB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/constants.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/constants.js deleted file mode 100644 index ff8b68d..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/constants.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_LONG = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_INT = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_CODE = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_REGEXP = exports.BSON_DATA_NULL = exports.BSON_DATA_DATE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_OID = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_DATA_OBJECT = exports.BSON_DATA_STRING = exports.BSON_DATA_NUMBER = exports.JS_INT_MIN = exports.JS_INT_MAX = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = void 0; -/** @internal */ -exports.BSON_INT32_MAX = 0x7fffffff; -/** @internal */ -exports.BSON_INT32_MIN = -0x80000000; -/** @internal */ -exports.BSON_INT64_MAX = Math.pow(2, 63) - 1; -/** @internal */ -exports.BSON_INT64_MIN = -Math.pow(2, 63); -/** - * Any integer up to 2^53 can be precisely represented by a double. - * @internal - */ -exports.JS_INT_MAX = Math.pow(2, 53); -/** - * Any integer down to -2^53 can be precisely represented by a double. - * @internal - */ -exports.JS_INT_MIN = -Math.pow(2, 53); -/** Number BSON Type @internal */ -exports.BSON_DATA_NUMBER = 1; -/** String BSON Type @internal */ -exports.BSON_DATA_STRING = 2; -/** Object BSON Type @internal */ -exports.BSON_DATA_OBJECT = 3; -/** Array BSON Type @internal */ -exports.BSON_DATA_ARRAY = 4; -/** Binary BSON Type @internal */ -exports.BSON_DATA_BINARY = 5; -/** Binary BSON Type @internal */ -exports.BSON_DATA_UNDEFINED = 6; -/** ObjectId BSON Type @internal */ -exports.BSON_DATA_OID = 7; -/** Boolean BSON Type @internal */ -exports.BSON_DATA_BOOLEAN = 8; -/** Date BSON Type @internal */ -exports.BSON_DATA_DATE = 9; -/** null BSON Type @internal */ -exports.BSON_DATA_NULL = 10; -/** RegExp BSON Type @internal */ -exports.BSON_DATA_REGEXP = 11; -/** Code BSON Type @internal */ -exports.BSON_DATA_DBPOINTER = 12; -/** Code BSON Type @internal */ -exports.BSON_DATA_CODE = 13; -/** Symbol BSON Type @internal */ -exports.BSON_DATA_SYMBOL = 14; -/** Code with Scope BSON Type @internal */ -exports.BSON_DATA_CODE_W_SCOPE = 15; -/** 32 bit Integer BSON Type @internal */ -exports.BSON_DATA_INT = 16; -/** Timestamp BSON Type @internal */ -exports.BSON_DATA_TIMESTAMP = 17; -/** Long BSON Type @internal */ -exports.BSON_DATA_LONG = 18; -/** Decimal128 BSON Type @internal */ -exports.BSON_DATA_DECIMAL128 = 19; -/** MinKey BSON Type @internal */ -exports.BSON_DATA_MIN_KEY = 0xff; -/** MaxKey BSON Type @internal */ -exports.BSON_DATA_MAX_KEY = 0x7f; -/** Binary Default Type @internal */ -exports.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** Binary Function Type @internal */ -exports.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** Binary Byte Array Type @internal */ -exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ -exports.BSON_BINARY_SUBTYPE_UUID = 3; -/** Binary UUID Type @internal */ -exports.BSON_BINARY_SUBTYPE_UUID_NEW = 4; -/** Binary MD5 Type @internal */ -exports.BSON_BINARY_SUBTYPE_MD5 = 5; -/** Encrypted BSON type @internal */ -exports.BSON_BINARY_SUBTYPE_ENCRYPTED = 6; -/** Column BSON type @internal */ -exports.BSON_BINARY_SUBTYPE_COLUMN = 7; -/** Binary User Defined Type @internal */ -exports.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; -//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/constants.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/constants.js.map deleted file mode 100644 index 3b9c0ca..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/constants.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAA,gBAAgB;AACH,QAAA,cAAc,GAAG,UAAU,CAAC;AACzC,gBAAgB;AACH,QAAA,cAAc,GAAG,CAAC,UAAU,CAAC;AAC1C,gBAAgB;AACH,QAAA,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AA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E,CAAC;AAEjC,qCAAqC;AACxB,QAAA,oBAAoB,GAAG,EAAE,CAAC;AAEvC,iCAAiC;AACpB,QAAA,iBAAiB,GAAG,IAAI,CAAC;AAEtC,iCAAiC;AACpB,QAAA,iBAAiB,GAAG,IAAI,CAAC;AAEtC,oCAAoC;AACvB,QAAA,2BAA2B,GAAG,CAAC,CAAC;AAE7C,qCAAqC;AACxB,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C,uCAAuC;AAC1B,QAAA,8BAA8B,GAAG,CAAC,CAAC;AAEhD,gGAAgG;AACnF,QAAA,wBAAwB,GAAG,CAAC,CAAC;AAE1C,iCAAiC;AACpB,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C,gCAAgC;AACnB,QAAA,uBAAuB,GAAG,CAAC,CAAC;AAEzC,oCAAoC;AACvB,QAAA,6BAA6B,GAAG,CAAC,CAAC;AAE/C,iCAAiC;AACpB,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C,yCAAyC;AAC5B,QAAA,gCAAgC,GAAG,GAAG,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/db_ref.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/db_ref.js deleted file mode 100644 index ea7f157..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/db_ref.js +++ /dev/null @@ -1,96 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DBRef = exports.isDBRefLike = void 0; -var utils_1 = require("./parser/utils"); -/** @internal */ -function isDBRefLike(value) { - return (utils_1.isObjectLike(value) && - value.$id != null && - typeof value.$ref === 'string' && - (value.$db == null || typeof value.$db === 'string')); -} -exports.isDBRefLike = isDBRefLike; -/** - * A class representation of the BSON DBRef type. - * @public - */ -var DBRef = /** @class */ (function () { - /** - * @param collection - the collection name. - * @param oid - the reference ObjectId. - * @param db - optional db name, if omitted the reference is local to the current db. - */ - function DBRef(collection, oid, db, fields) { - if (!(this instanceof DBRef)) - return new DBRef(collection, oid, db, fields); - // check if namespace has been provided - var parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - Object.defineProperty(DBRef.prototype, "namespace", { - // Property provided for compatibility with the 1.x parser - // the 1.x parser used a "namespace" property, while 4.x uses "collection" - /** @internal */ - get: function () { - return this.collection; - }, - set: function (value) { - this.collection = value; - }, - enumerable: false, - configurable: true - }); - DBRef.prototype.toJSON = function () { - var o = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o.$db = this.db; - return o; - }; - /** @internal */ - DBRef.prototype.toExtendedJSON = function (options) { - options = options || {}; - var o = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o; - } - if (this.db) - o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - }; - /** @internal */ - DBRef.fromExtendedJSON = function (doc) { - var copy = Object.assign({}, doc); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - }; - /** @internal */ - DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - DBRef.prototype.inspect = function () { - // NOTE: if OID is an ObjectId class it will just print the oid string. - var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; - }; - return DBRef; -}()); -exports.DBRef = DBRef; -Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); -//# sourceMappingURL=db_ref.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/db_ref.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/db_ref.js.map deleted file mode 100644 index 359088f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/db_ref.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"db_ref.js","sourceRoot":"","sources":["../src/db_ref.ts"],"names":[],"mappings":";;;AAGA,wCAA8C;AAS9C,gBAAgB;AAChB,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,CACL,oBAAY,CAAC,KAAK,CAAC;QACnB,KAAK,CAAC,GAAG,IAAI,IAAI;QACjB,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,IAAI,OAAO,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,CACrD,CAAC;AACJ,CAAC;AAPD,kCAOC;AAED;;;GAGG;AACH;IAQE;;;;OAIG;IACH,eAAY,UAAkB,EAAE,GAAa,EAAE,EAAW,EAAE,MAAiB;QAC3E,IAAI,CAAC,CAAC,IAAI,YAAY,KAAK,CAAC;YAAE,OAAO,IAAI,KAAK,CAAC,UAAU,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;QAE5E,uCAAuC;QACvC,IAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACpC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,EAAE,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;YACnB,oEAAoE;YACpE,UAAU,GAAG,KAAK,CAAC,KAAK,EAAG,CAAC;SAC7B;QAED,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;IAC7B,CAAC;IAMD,sBAAI,4BAAS;QAJb,0DAA0D;QAC1D,0EAA0E;QAE1E,gBAAgB;aAChB;YACE,OAAO,IA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AC,CAAC;IACrD,CAAC;IAED,gBAAgB;IAChB,gBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,uBAAO,GAAP;QACE,uEAAuE;QACvE,IAAM,GAAG,GACP,IAAI,CAAC,GAAG,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;QAC7F,OAAO,iBAAc,IAAI,CAAC,SAAS,2BAAoB,GAAG,YACxD,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,SAAM,IAAI,CAAC,EAAE,OAAG,CAAC,CAAC,CAAC,EAAE,OAC9B,CAAC;IACN,CAAC;IACH,YAAC;AAAD,CAAC,AA9FD,IA8FC;AA9FY,sBAAK;AAgGlB,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/decimal128.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/decimal128.js deleted file mode 100644 index 8df4db7..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/decimal128.js +++ /dev/null @@ -1,661 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Decimal128 = void 0; -var buffer_1 = require("buffer"); -var error_1 = require("./error"); -var long_1 = require("./long"); -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Detect if the value is a digit -function isDigit(value) { - return !isNaN(parseInt(value, 10)); -} -// Divide two uint128 values -function divideu128(value) { - var DIVISOR = long_1.Long.fromNumber(1000 * 1000 * 1000); - var _rem = long_1.Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (var i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new long_1.Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - return { quotient: value, rem: _rem }; -} -// Multiply two Long values and return the 128 bit value -function multiply64x2(left, right) { - if (!left && !right) { - return { high: long_1.Long.fromNumber(0), low: long_1.Long.fromNumber(0) }; - } - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new long_1.Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new long_1.Long(right.getLowBits(), 0); - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new long_1.Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new long_1.Long(productLow.getLowBits(), 0)); - // Return the 128 bit result - return { high: productHigh, low: productLow }; -} -function lessThan(left, right) { - // Make values unsigned - var uhleft = left.high >>> 0; - var uhright = right.high >>> 0; - // Compare high bits first - if (uhleft < uhright) { - return true; - } - else if (uhleft === uhright) { - var ulleft = left.low >>> 0; - var ulright = right.low >>> 0; - if (ulleft < ulright) - return true; - } - return false; -} -function invalidErr(string, message) { - throw new error_1.BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); -} -/** - * A class representation of the BSON Decimal128 type. - * @public - */ -var Decimal128 = /** @class */ (function () { - /** - * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, - * or a string representation as returned by .toString() - */ - function Decimal128(bytes) { - if (!(this instanceof Decimal128)) - return new Decimal128(bytes); - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } - else { - this.bytes = bytes; - } - } - /** - * Create a Decimal128 instance from a string representation - * - * @param representation - a numeric string representation. - */ - Decimal128.fromString = function (representation) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = new long_1.Long(0, 0); - // The low 17 digits of the significand - var significandLow = new long_1.Long(0, 0); - // The biased exponent - var biasedExponent = 0; - // Read index - var index = 0; - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (representation.length >= 7000) { - throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - // Results - var stringMatch = representation.match(PARSE_STRING_REGEXP); - var infMatch = representation.match(PARSE_INF_REGEXP); - var nanMatch = representation.match(PARSE_NAN_REGEXP); - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - if (stringMatch) { - // full_match = stringMatch[0] - // sign = stringMatch[1] - var unsignedNumber = stringMatch[2]; - // stringMatch[3] is undefined if a whole number (ex "1", 12") - // but defined if a number w/ decimal in it (ex "1.0, 12.2") - var e = stringMatch[4]; - var expSign = stringMatch[5]; - var expNumber = stringMatch[6]; - // they provided e, but didn't give an exponent number. for ex "1e" - if (e && expNumber === undefined) - invalidErr(representation, 'missing exponent power'); - // they provided e, but didn't give a number before it. for ex "e1" - if (e && unsignedNumber === undefined) - invalidErr(representation, 'missing exponent base'); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - // Get the negative or positive sign - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - // Check if user passed Infinity or NaN - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - else if (representation[index] === 'N') { - return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); - } - } - // Read all the digits - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) - invalidErr(representation, 'contains multiple periods'); - sawRadix = true; - index = index + 1; - continue; - } - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - // Only store 34 digits - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - if (sawRadix && !nDigitsRead) - throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); - // Read exponent if exists - if (representation[index] === 'e' || representation[index] === 'E') { - // Read exponent digits - var match = representation.substr(++index).match(EXPONENT_REGEX); - // No digits read - if (!match || !match[2]) - return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); - // Get exponent - exponent = parseInt(match[0], 10); - // Adjust the index - index = index + match[0].length; - } - // Return not a number - if (representation[index]) - return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } - else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } - else { - exponent = exponent - radixPosition; - } - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit. can only do this if < significant digits than # stored. - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } - else { - // adjust to round - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } - else { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits) { - var endOfString = nDigitsRead; - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - // if negative, we need to increment again to account for - sign at start. - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - var dIdx = lastDigit; - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } - else { - return new Decimal128(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - } - } - } - // Encode significand - // The high 17 digits of the significand - significandHigh = long_1.Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = long_1.Long.fromNumber(0); - // read a zero - if (significantDigits === 0) { - significandHigh = long_1.Long.fromNumber(0); - significandLow = long_1.Long.fromNumber(0); - } - else if (lastDigit - firstDigit < 17) { - var dIdx = firstDigit; - significandLow = long_1.Long.fromNumber(digits[dIdx++]); - significandHigh = new long_1.Long(0, 0); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); - significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); - } - } - else { - var dIdx = firstDigit; - significandHigh = long_1.Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(long_1.Long.fromNumber(10)); - significandHigh = significandHigh.add(long_1.Long.fromNumber(digits[dIdx])); - } - significandLow = long_1.Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); - significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); - } - } - var significand = multiply64x2(significandHigh, long_1.Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(long_1.Long.fromNumber(1)); - } - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: long_1.Long.fromNumber(0), high: long_1.Long.fromNumber(0) }; - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(long_1.Long.fromNumber(1)).equals(long_1.Long.fromNumber(1))) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(long_1.Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent).and(long_1.Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x7fffffffffff))); - } - else { - dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x1ffffffffffff))); - } - dec.low = significand.low; - // Encode sign - if (isNegative) { - dec.high = dec.high.or(long_1.Long.fromString('9223372036854775808')); - } - // Encode into a buffer - var buffer = buffer_1.Buffer.alloc(16); - index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - // Return the new Decimal128 - return new Decimal128(buffer); - }; - /** Create a string representation of the raw Decimal128 value */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) - significand[i] = 0; - // read pointer into significand - var index = 0; - // true if the number is zero - var is_zero = false; - // the most significant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: [0, 0, 0, 0] }; - // indexing variables - var j, k; - // Output string - var string = []; - // Unpack index - index = 0; - // Buffer reference - var buffer = this.bytes; - // Unpack the low 64bits into a long - // bits 96 - 127 - var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 64 - 95 - var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack the high 64bits into a long - // bits 32 - 63 - var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 0 - 31 - var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Unpack index - index = 0; - // Create the state of the decimal - var dec = { - low: new long_1.Long(low, midl), - high: new long_1.Long(midh, high) - }; - if (dec.high.lessThan(long_1.Long.ZERO)) { - string.push('-'); - } - // Decode combination field and exponent - // bits 1 - 5 - var combination = (high >> 26) & COMBINATION_MASK; - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } - else if (combination === COMBINATION_NAN) { - return 'NaN'; - } - else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } - else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - // unbiased exponent - var exponent = biased_exponent - EXPONENT_BIAS; - // Create string of significand digits - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0) { - is_zero = true; - } - else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Perform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) - continue; - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } - else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - // the exponent if scientific notation is used - var scientific_exponent = significand_digits - 1 + exponent; - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - // if there are too many significant digits, we should just be treating numbers - // as + or - 0 and using the non-scientific exponent (this is for the "invalid - // representation should be treated as 0/-0" spec cases in decimal128-1.json) - if (significand_digits > 34) { - string.push("" + 0); - if (exponent > 0) - string.push('E+' + exponent); - else if (exponent < 0) - string.push('E' + exponent); - return string.join(''); - } - string.push("" + significand[index++]); - significand_digits = significand_digits - 1; - if (significand_digits) { - string.push('.'); - } - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } - else { - string.push("" + scientific_exponent); - } - } - else { - // Regular format with no decimal place - if (exponent >= 0) { - for (var i = 0; i < significand_digits; i++) { - string.push("" + significand[index++]); - } - } - else { - var radix_position = significand_digits + exponent; - // non-zero digits before radix - if (radix_position > 0) { - for (var i = 0; i < radix_position; i++) { - string.push("" + significand[index++]); - } - } - else { - string.push('0'); - } - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push("" + significand[index++]); - } - } - } - return string.join(''); - }; - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.prototype.toExtendedJSON = function () { - return { $numberDecimal: this.toString() }; - }; - /** @internal */ - Decimal128.fromExtendedJSON = function (doc) { - return Decimal128.fromString(doc.$numberDecimal); - }; - /** @internal */ - Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Decimal128.prototype.inspect = function () { - return "new Decimal128(\"" + this.toString() + "\")"; - }; - return Decimal128; -}()); -exports.Decimal128 = Decimal128; -Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); -//# sourceMappingURL=decimal128.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/decimal128.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/decimal128.js.map deleted file mode 100644 index 361d621..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/decimal128.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"decimal128.js","sourceRoot":"","sources":["../src/decimal128.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AACxC,+BAA8B;AAE9B,IAAM,mBAAmB,GAAG,+CAA+C,CAAC;AAC5E,IAAM,gBAAgB,GAAG,0BAA0B,CAAC;AACpD,IAAM,gBAAgB,GAAG,eAAe,CAAC;AAEzC,IAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,IAAM,YAAY,GAAG,CAAC,IAAI,CAAC;AAC3B,IAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,IAAM,UAAU,GAAG,EAAE,CAAC;AAEtB,yDAAyD;AACzD,IAAM,UAAU,GAAG;IACjB,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAA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AAAD,CAAC,AAnoBD,IAmoBC;AAnoBY,gCAAU;AAqoBvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/double.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/double.js deleted file mode 100644 index 5a2ce61..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/double.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Double = void 0; -/** - * A class representation of the BSON Double type. - * @public - */ -var Double = /** @class */ (function () { - /** - * Create a Double type - * - * @param value - the number we want to represent as a double. - */ - function Double(value) { - if (!(this instanceof Double)) - return new Double(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; - } - /** - * Access the number value. - * - * @returns returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - Double.prototype.toJSON = function () { - return this.value; - }; - Double.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - /** @internal */ - Double.prototype.toExtendedJSON = function (options) { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user - // explicitly provided `-0` then we need to ensure the sign makes it into the output - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: "-" + this.value.toFixed(1) }; - } - var $numberDouble; - if (Number.isInteger(this.value)) { - $numberDouble = this.value.toFixed(1); - if ($numberDouble.length >= 13) { - $numberDouble = this.value.toExponential(13).toUpperCase(); - } - } - else { - $numberDouble = this.value.toString(); - } - return { $numberDouble: $numberDouble }; - }; - /** @internal */ - Double.fromExtendedJSON = function (doc, options) { - var doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - }; - /** @internal */ - Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Double.prototype.inspect = function () { - var eJSON = this.toExtendedJSON(); - return "new Double(" + eJSON.$numberDouble + ")"; - }; - return Double; -}()); -exports.Double = Double; -Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); -//# sourceMappingURL=double.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/double.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/double.js.map deleted file mode 100644 index a89a67e..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/double.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"double.js","sourceRoot":"","sources":["../src/double.ts"],"names":[],"mappings":";;;AAOA;;;GAGG;AACH;IAIE;;;;OAIG;IACH,gBAAY,KAAa;QACvB,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;QAExD,IAAK,KAAiB,YAAY,MAAM,EAAE;YACxC,KAAK,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;SACzB;QAED,IAAI,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,wBAAO,GAAP;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,uBAAM,GAAN;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,yBAAQ,GAAR,UAAS,KAAc;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd,UAAe,OAAsB;QACnC,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;YA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AG,CAAC;IAC9C,CAAC;IACH,aAAC;AAAD,CAAC,AA5ED,IA4EC;AA5EY,wBAAM;AA8EnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/ensure_buffer.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/ensure_buffer.js deleted file mode 100644 index f417fe2..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/ensure_buffer.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ensureBuffer = void 0; -var buffer_1 = require("buffer"); -var error_1 = require("./error"); -var utils_1 = require("./parser/utils"); -/** - * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. - * - * @param potentialBuffer - The potential buffer - * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that - * wraps a passed in Uint8Array - * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in - */ -function ensureBuffer(potentialBuffer) { - if (ArrayBuffer.isView(potentialBuffer)) { - return buffer_1.Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - if (utils_1.isAnyArrayBuffer(potentialBuffer)) { - return buffer_1.Buffer.from(potentialBuffer); - } - throw new error_1.BSONTypeError('Must use either Buffer or TypedArray'); -} -exports.ensureBuffer = ensureBuffer; -//# sourceMappingURL=ensure_buffer.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/ensure_buffer.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/ensure_buffer.js.map deleted file mode 100644 index 82bcfd3..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/ensure_buffer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ensure_buffer.js","sourceRoot":"","sources":["../src/ensure_buffer.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AACxC,wCAAkD;AAElD;;;;;;;GAOG;AACH,SAAgB,YAAY,CAAC,eAAuD;IAClF,IAAI,WAAW,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE;QACvC,OAAO,eAAM,CAAC,IAAI,CAChB,eAAe,CAAC,MAAM,EACtB,eAAe,CAAC,UAAU,EAC1B,eAAe,CAAC,UAAU,CAC3B,CAAC;KACH;IAED,IAAI,wBAAgB,CAAC,eAAe,CAAC,EAAE;QACrC,OAAO,eAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;KACrC;IAED,MAAM,IAAI,qBAAa,CAAC,sCAAsC,CAAC,CAAC;AAClE,CAAC;AAdD,oCAcC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/error.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/error.js deleted file mode 100644 index 035ce86..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/error.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BSONTypeError = exports.BSONError = void 0; -/** @public */ -var BSONError = /** @class */ (function (_super) { - __extends(BSONError, _super); - function BSONError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONError.prototype); - return _this; - } - Object.defineProperty(BSONError.prototype, "name", { - get: function () { - return 'BSONError'; - }, - enumerable: false, - configurable: true - }); - return BSONError; -}(Error)); -exports.BSONError = BSONError; -/** @public */ -var BSONTypeError = /** @class */ (function (_super) { - __extends(BSONTypeError, _super); - function BSONTypeError(message) { - var _this = _super.call(this, message) || this; - Object.setPrototypeOf(_this, BSONTypeError.prototype); - return _this; - } - Object.defineProperty(BSONTypeError.prototype, "name", { - get: function () { - return 'BSONTypeError'; - }, - enumerable: false, - configurable: true - }); - return BSONTypeError; -}(TypeError)); -exports.BSONTypeError = BSONTypeError; -//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/error.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/error.js.map deleted file mode 100644 index 2acd4ef..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/error.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,cAAc;AACd;IAA+B,6BAAK;IAClC,mBAAY,OAAe;QAA3B,YACE,kBAAM,OAAO,CAAC,SAEf;QADC,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;;IACnD,CAAC;IAED,sBAAI,2BAAI;aAAR;YACE,OAAO,WAAW,CAAC;QACrB,CAAC;;;OAAA;IACH,gBAAC;AAAD,CAAC,AATD,CAA+B,KAAK,GASnC;AATY,8BAAS;AAWtB,cAAc;AACd;IAAmC,iCAAS;IAC1C,uBAAY,OAAe;QAA3B,YACE,kBAAM,OAAO,CAAC,SAEf;QADC,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;;IACvD,CAAC;IAED,sBAAI,+BAAI;aAAR;YACE,OAAO,eAAe,CAAC;QACzB,CAAC;;;OAAA;IACH,oBAAC;AAAD,CAAC,AATD,CAAmC,SAAS,GAS3C;AATY,sCAAa"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/extended_json.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/extended_json.js deleted file mode 100644 index cf489f2..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/extended_json.js +++ /dev/null @@ -1,378 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EJSON = exports.isBSONType = void 0; -var binary_1 = require("./binary"); -var code_1 = require("./code"); -var db_ref_1 = require("./db_ref"); -var decimal128_1 = require("./decimal128"); -var double_1 = require("./double"); -var error_1 = require("./error"); -var int_32_1 = require("./int_32"); -var long_1 = require("./long"); -var max_key_1 = require("./max_key"); -var min_key_1 = require("./min_key"); -var objectid_1 = require("./objectid"); -var utils_1 = require("./parser/utils"); -var regexp_1 = require("./regexp"); -var symbol_1 = require("./symbol"); -var timestamp_1 = require("./timestamp"); -function isBSONType(value) { - return (utils_1.isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); -} -exports.isBSONType = isBSONType; -// INT32 boundaries -var BSON_INT32_MAX = 0x7fffffff; -var BSON_INT32_MIN = -0x80000000; -// INT64 boundaries -var BSON_INT64_MAX = 0x7fffffffffffffff; -var BSON_INT64_MIN = -0x8000000000000000; -// all the types where we don't need to do any special processing and can just pass the EJSON -//straight to type.fromExtendedJSON -var keysToCodecs = { - $oid: objectid_1.ObjectId, - $binary: binary_1.Binary, - $uuid: binary_1.Binary, - $symbol: symbol_1.BSONSymbol, - $numberInt: int_32_1.Int32, - $numberDecimal: decimal128_1.Decimal128, - $numberDouble: double_1.Double, - $numberLong: long_1.Long, - $minKey: min_key_1.MinKey, - $maxKey: max_key_1.MaxKey, - $regex: regexp_1.BSONRegExp, - $regularExpression: regexp_1.BSONRegExp, - $timestamp: timestamp_1.Timestamp -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function deserializeValue(value, options) { - if (options === void 0) { options = {}; } - if (typeof value === 'number') { - if (options.relaxed || options.legacy) { - return value; - } - // if it's an integer, should interpret as smallest BSON integer - // that can represent it exactly. (if out of range, interpret as double.) - if (Math.floor(value) === value) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) - return new int_32_1.Int32(value); - if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) - return long_1.Long.fromNumber(value); - } - // If the number is a non-integer or out of integer range, should interpret as BSON Double. - return new double_1.Double(value); - } - // from here on out we're looking for bson types, so bail if its not an object - if (value == null || typeof value !== 'object') - return value; - // upgrade deprecated undefined to null - if (value.$undefined) - return null; - var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); - for (var i = 0; i < keys.length; i++) { - var c = keysToCodecs[keys[i]]; - if (c) - return c.fromExtendedJSON(value, options); - } - if (value.$date != null) { - var d = value.$date; - var date = new Date(); - if (options.legacy) { - if (typeof d === 'number') - date.setTime(d); - else if (typeof d === 'string') - date.setTime(Date.parse(d)); - } - else { - if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (long_1.Long.isLong(d)) - date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) - date.setTime(d); - } - return date; - } - if (value.$code != null) { - var copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return code_1.Code.fromExtendedJSON(value); - } - if (db_ref_1.isDBRefLike(value) || value.$dbPointer) { - var v = value.$ref ? value : value.$dbPointer; - // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) - // because of the order JSON.parse goes through the document - if (v instanceof db_ref_1.DBRef) - return v; - var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); - var valid_1 = true; - dollarKeys.forEach(function (k) { - if (['$ref', '$id', '$db'].indexOf(k) === -1) - valid_1 = false; - }); - // only make DBRef if $ keys are all valid - if (valid_1) - return db_ref_1.DBRef.fromExtendedJSON(v); - } - return value; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeArray(array, options) { - return array.map(function (v, index) { - options.seenObjects.push({ propertyName: "index " + index, obj: null }); - try { - return serializeValue(v, options); - } - finally { - options.seenObjects.pop(); - } - }); -} -function getISOString(date) { - var isoStr = date.toISOString(); - // we should only show milliseconds in timestamp if they're non-zero - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeValue(value, options) { - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); - if (index !== -1) { - var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); - var leadingPart = props - .slice(0, index) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var alreadySeen = props[index]; - var circularPart = ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(function (prop) { return prop + " -> "; }) - .join(''); - var current = props[props.length - 1]; - var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new error_1.BSONTypeError('Converting circular structure to EJSON:\n' + - (" " + leadingPart + alreadySeen + circularPart + current + "\n") + - (" " + leadingSpace + "\\" + dashes + "/")); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || utils_1.isDate(value)) { - var dateNum = value.getTime(), - // is it in year range 1970-9999? - inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - // it's an integer - if (Math.floor(value) === value) { - var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; - // interpret as being of the smallest BSON integer type that can represent the number exactly - if (int32Range) - return { $numberInt: value.toString() }; - if (int64Range) - return { $numberLong: value.toString() }; - } - return { $numberDouble: value.toString() }; - } - if (value instanceof RegExp || utils_1.isRegExp(value)) { - var flags = value.flags; - if (flags === undefined) { - var match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - var rx = new regexp_1.BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - if (value != null && typeof value === 'object') - return serializeDocument(value, options); - return value; -} -var BSON_TYPE_MAPPINGS = { - Binary: function (o) { return new binary_1.Binary(o.value(), o.sub_type); }, - Code: function (o) { return new code_1.Code(o.code, o.scope); }, - DBRef: function (o) { return new db_ref_1.DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, - Decimal128: function (o) { return new decimal128_1.Decimal128(o.bytes); }, - Double: function (o) { return new double_1.Double(o.value); }, - Int32: function (o) { return new int_32_1.Int32(o.value); }, - Long: function (o) { - return long_1.Long.fromBits( - // underscore variants for 1.x backwards compatibility - o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); - }, - MaxKey: function () { return new max_key_1.MaxKey(); }, - MinKey: function () { return new min_key_1.MinKey(); }, - ObjectID: function (o) { return new objectid_1.ObjectId(o); }, - ObjectId: function (o) { return new objectid_1.ObjectId(o); }, - BSONRegExp: function (o) { return new regexp_1.BSONRegExp(o.pattern, o.options); }, - Symbol: function (o) { return new symbol_1.BSONSymbol(o.value); }, - Timestamp: function (o) { return timestamp_1.Timestamp.fromBits(o.low, o.high); } -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeDocument(doc, options) { - if (doc == null || typeof doc !== 'object') - throw new error_1.BSONError('not an object instance'); - var bsontype = doc._bsontype; - if (typeof bsontype === 'undefined') { - // It's a regular object. Recursively serialize its property values. - var _doc = {}; - for (var name in doc) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - _doc[name] = serializeValue(doc[name], options); - } - finally { - options.seenObjects.pop(); - } - } - return _doc; - } - else if (isBSONType(doc)) { - // the "document" is really just a BSON type object - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var outDoc = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - // There's no EJSON serialization function on the object. It's probably an - // object created by a previous version of this library (or another library) - // that's duck-typing objects to look like they were generated by this library). - // Copy the object into this library's version of that type. - var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - // Two BSON types may have nested objects that may need to be serialized too - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new code_1.Code(outDoc.code, serializeValue(outDoc.scope, options)); - } - else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new db_ref_1.DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); - } - return outDoc.toExtendedJSON(options); - } - else { - throw new error_1.BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } -} -/** - * EJSON parse / stringify API - * @public - */ -// the namespace here is used to emulate `export * as EJSON from '...'` -// which as of now (sept 2020) api-extractor does not support -// eslint-disable-next-line @typescript-eslint/no-namespace -var EJSON; -(function (EJSON) { - /** - * Parse an Extended JSON string, constructing the JavaScript value or object described by that - * string. - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const text = '{ "int32": { "$numberInt": "10" } }'; - * - * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } - * console.log(EJSON.parse(text, { relaxed: false })); - * - * // prints { int32: 10 } - * console.log(EJSON.parse(text)); - * ``` - */ - function parse(text, options) { - var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); - // relaxed implies not strict - if (typeof finalOptions.relaxed === 'boolean') - finalOptions.strict = !finalOptions.relaxed; - if (typeof finalOptions.strict === 'boolean') - finalOptions.relaxed = !finalOptions.strict; - return JSON.parse(text, function (key, value) { - if (key.indexOf('\x00') !== -1) { - throw new error_1.BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); - } - return deserializeValue(value, finalOptions); - }); - } - EJSON.parse = parse; - /** - * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer - * function is specified or optionally including only the specified properties if a replacer array - * is specified. - * - * @param value - The value to convert to extended JSON - * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string - * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. - * @param options - Optional settings - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const Int32 = require('mongodb').Int32; - * const doc = { int32: new Int32(10) }; - * - * // prints '{"int32":{"$numberInt":"10"}}' - * console.log(EJSON.stringify(doc, { relaxed: false })); - * - * // prints '{"int32":10}' - * console.log(EJSON.stringify(doc)); - * ``` - */ - function stringify(value, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - replacer, space, options) { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - var doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer, space); - } - EJSON.stringify = stringify; - /** - * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - * - * @param value - The object to serialize - * @param options - Optional settings passed to the `stringify` function - */ - function serialize(value, options) { - options = options || {}; - return JSON.parse(stringify(value, options)); - } - EJSON.serialize = serialize; - /** - * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - * - * @param ejson - The Extended JSON object to deserialize - * @param options - Optional settings passed to the parse method - */ - function deserialize(ejson, options) { - options = options || {}; - return parse(JSON.stringify(ejson), options); - } - EJSON.deserialize = deserialize; -})(EJSON = exports.EJSON || (exports.EJSON = {})); -//# sourceMappingURL=extended_json.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/extended_json.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/extended_json.js.map deleted file mode 100644 index ae3a2cc..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/extended_json.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"extended_json.js","sourceRoot":"","sources":["../src/extended_json.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAElC,+BAA8B;AAC9B,mCAA8C;AAC9C,2CAA0C;AAC1C,mCAAkC;AAClC,iCAAmD;AACnD,mCAAiC;AACjC,+BAA8B;AAC9B,qCAAmC;AACnC,qCAAmC;AACnC,uCAAsC;AACtC,wCAAgE;AAChE,mCAAsC;AACtC,mCAAsC;AACtC,yCAAwC;AAqBxC,SAAgB,UAAU,CAAC,KAAc;IACvC,OAAO,CACL,oBAAY,CAAC,KAAK,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,WAAW,CAAC,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,CAC9F,CAAC;AACJ,CAAC;AAJD,gCAIC;AAED,mBAAmB;AACnB,IAAM,cAAc,GAAG,UAAU,CAAC;AAClC,IAAM,cAAc,GAAG,CAAC,UAAU,CAAC;AACnC,mBAAmB;AACnB,IAAM,cAAc,GAAG,kBAAkB,CAAC;AAC1C,IAAM,cAAc,GAAG,CAAC,kBAAkB,CAAC;AAE3C,6FAA6F;AAC7F,mCAAmC;AACnC,IAAM,YAAY,GAAG;IACnB,IAAI,EAAE,mBAAQ;IACd,OAAO,EAAE,eAAM;IACf,KAAK,EAAE,eAAM;IACb,OAAO,EAAE,mBAAU;IACnB,UAAU,EAAE,cAAK;IACjB,cA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1B,CAAA;AACH,CAAC,EArHgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAqHrB"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/float_parser.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/float_parser.js deleted file mode 100644 index f78a3a0..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/float_parser.js +++ /dev/null @@ -1,137 +0,0 @@ -"use strict"; -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White -Object.defineProperty(exports, "__esModule", { value: true }); -exports.writeIEEE754 = exports.readIEEE754 = void 0; -function readIEEE754(buffer, offset, endian, mLen, nBytes) { - var e; - var m; - var bBE = endian === 'big'; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = bBE ? 0 : nBytes - 1; - var d = bBE ? 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.readIEEE754 = readIEEE754; -function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { - var e; - var m; - var c; - var bBE = endian === 'big'; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = bBE ? nBytes - 1 : 0; - var d = bBE ? -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; - } - } - if (isNaN(value)) - m = 0; - while (mLen >= 8) { - buffer[offset + i] = m & 0xff; - i += d; - m /= 256; - mLen -= 8; - } - e = (e << mLen) | m; - if (isNaN(value)) - e += 8; - eLen += mLen; - while (eLen > 0) { - buffer[offset + i] = e & 0xff; - i += d; - e /= 256; - eLen -= 8; - } - buffer[offset + i - d] |= s * 128; -} -exports.writeIEEE754 = writeIEEE754; -//# sourceMappingURL=float_parser.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/float_parser.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/float_parser.js.map deleted file mode 100644 index 5b68843..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/float_parser.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"float_parser.js","sourceRoot":"","sources":["../src/float_parser.ts"],"names":[],"mappings":";AAAA,2CAA2C;AAC3C,uBAAuB;AACvB,EAAE;AACF,qEAAqE;AACrE,8EAA8E;AAC9E,EAAE;AACF,4EAA4E;AAC5E,2DAA2D;AAC3D,EAAE;AACF,+EAA+E;AAC/E,+EAA+E;AAC/E,4DAA4D;AAC5D,EAAE;AACF,gFAAgF;AAChF,2EAA2E;AAC3E,gDAAgD;AAChD,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,4EAA4E;AAC5E,sEAAsE;AACtE,uEAAuE;AACvE,2EAA2E;AAC3E,0EAA0E;AAC1E,0EAA0E;AAC1E,6EAA6E;AAC7E,8BAA8B;AAC9B,EAAE;AACF,EAAE;AACF,+EAA+E;;;AAI/E,SAAgB,WAAW,CACzB,MAAyB,EACzB,MAAc,EACd,MAAwB,EACxB,IAAY,EACZ,MAAc;IAEd,IA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,GAAG,CAAC;AACpC,CAAC;AA5ED,oCA4EC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/int_32.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/int_32.js deleted file mode 100644 index a09b221..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/int_32.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Int32 = void 0; -/** - * A class representation of a BSON Int32 type. - * @public - */ -var Int32 = /** @class */ (function () { - /** - * Create an Int32 type - * - * @param value - the number we want to represent as an int32. - */ - function Int32(value) { - if (!(this instanceof Int32)) - return new Int32(value); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value | 0; - } - /** - * Access the number value. - * - * @returns returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - Int32.prototype.toString = function (radix) { - return this.value.toString(radix); - }; - Int32.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - Int32.prototype.toExtendedJSON = function (options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; - }; - /** @internal */ - Int32.fromExtendedJSON = function (doc, options) { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - }; - /** @internal */ - Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Int32.prototype.inspect = function () { - return "new Int32(" + this.valueOf() + ")"; - }; - return Int32; -}()); -exports.Int32 = Int32; -Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); -//# sourceMappingURL=int_32.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/int_32.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/int_32.js.map deleted file mode 100644 index bac5cbe..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/l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,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,uBAAO,GAAP;QACE,OAAO,eAAa,IAAI,CAAC,OAAO,EAAE,MAAG,CAAC;IACxC,CAAC;IACH,YAAC;AAAD,CAAC,AAvDD,IAuDC;AAvDY,sBAAK;AAyDlB,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/long.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/long.js deleted file mode 100644 index 3de7b1a..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/long.js +++ /dev/null @@ -1,899 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Long = void 0; -var utils_1 = require("./parser/utils"); -/** - * wasm optimizations, to do native i64 multiplication and divide - */ -var wasm = undefined; -try { - wasm = new WebAssembly.Instance(new WebAssembly.Module( - // prettier-ignore - new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; -} -catch (_a) { - // no wasm support -} -var TWO_PWR_16_DBL = 1 << 16; -var TWO_PWR_24_DBL = 1 << 24; -var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; -var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; -var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; -/** A cache of the Long representations of small integer values. */ -var INT_CACHE = {}; -/** A cache of the Long representations of small unsigned integer values. */ -var UINT_CACHE = {}; -/** - * A class representing a 64-bit integer - * @public - * @remarks - * The internal representation of a long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16 bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. - */ -var Long = /** @class */ (function () { - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * - * Acceptable signatures are: - * - Long(low, high, unsigned?) - * - Long(bigint, unsigned?) - * - Long(string, unsigned?) - * - * @param low - The low (signed) 32 bits of the long - * @param high - The high (signed) 32 bits of the long - * @param unsigned - Whether unsigned or not, defaults to signed - */ - function Long(low, high, unsigned) { - if (low === void 0) { low = 0; } - if (!(this instanceof Long)) - return new Long(low, high, unsigned); - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } - else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } - else { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - Object.defineProperty(this, '__isLong__', { - value: true, - configurable: false, - writable: false, - enumerable: false - }); - } - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. - * Each is assumed to use 32 bits. - * @param lowBits - The low 32 bits - * @param highBits - The high 32 bits - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBits = function (lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - }; - /** - * Returns a Long representing the given 32 bit integer value. - * @param value - The 32 bit integer in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromInt = function (value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } - else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromNumber = function (value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } - else { - if (value <= -TWO_PWR_63_DBL) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; - } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - }; - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBigInt = function (value, unsigned) { - return Long.fromString(value.toString(), unsigned); - }; - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param str - The textual representation of the Long - * @param unsigned - Whether unsigned or not, defaults to signed - * @param radix - The radix in which the text is written (2-36), defaults to 10 - * @returns The corresponding Long value - */ - Long.fromString = function (str, unsigned, radix) { - if (str.length === 0) - throw Error('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - (radix = unsigned), (unsigned = false); - } - else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - var p; - if ((p = str.indexOf('-')) > 0) - throw Error('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } - else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - }; - /** - * Creates a Long from its byte representation. - * @param bytes - Byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @param le - Whether little or big endian, defaults to big endian - * @returns The corresponding Long value - */ - Long.fromBytes = function (bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - }; - /** - * Creates a Long from its little endian byte representation. - * @param bytes - Little endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesLE = function (bytes, unsigned) { - return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); - }; - /** - * Creates a Long from its big endian byte representation. - * @param bytes - Big endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - Long.fromBytesBE = function (bytes, unsigned) { - return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); - }; - /** - * Tests if the specified object is a Long. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Long.isLong = function (value) { - return utils_1.isObjectLike(value) && value['__isLong__'] === true; - }; - /** - * Converts the specified value to a Long. - * @param unsigned - Whether unsigned or not, defaults to signed - */ - Long.fromValue = function (val, unsigned) { - if (typeof val === 'number') - return Long.fromNumber(val, unsigned); - if (typeof val === 'string') - return Long.fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); - }; - /** Returns the sum of this and the specified Long. */ - Long.prototype.add = function (addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** - * Returns the sum of this and the specified Long. - * @returns Sum - */ - Long.prototype.and = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - /** - * Compares this Long's value with the specified's. - * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater - */ - Long.prototype.compare = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - // At this point the sign bits are the same - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; - /** This is an alias of {@link Long.compare} */ - Long.prototype.comp = function (other) { - return this.compare(other); - }; - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. - * @returns Quotient - */ - Long.prototype.divide = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw Error('division by zero'); - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if (!this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } - else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } - else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } - else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } - else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return Long.UONE; - res = Long.UZERO; - } - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - /**This is an alias of {@link Long.divide} */ - Long.prototype.div = function (divisor) { - return this.divide(divisor); - }; - /** - * Tests if this Long's value equals the specified's. - * @param other - Other value - */ - Long.prototype.equals = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - /** This is an alias of {@link Long.equals} */ - Long.prototype.eq = function (other) { - return this.equals(other); - }; - /** Gets the high 32 bits as a signed integer. */ - Long.prototype.getHighBits = function () { - return this.high; - }; - /** Gets the high 32 bits as an unsigned integer. */ - Long.prototype.getHighBitsUnsigned = function () { - return this.high >>> 0; - }; - /** Gets the low 32 bits as a signed integer. */ - Long.prototype.getLowBits = function () { - return this.low; - }; - /** Gets the low 32 bits as an unsigned integer. */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low >>> 0; - }; - /** Gets the number of bits needed to represent the absolute value of this Long. */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - // Unsigned Longs are never negative - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - var val = this.high !== 0 ? this.high : this.low; - var bit; - for (bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - }; - /** Tests if this Long's value is greater than the specified's. */ - Long.prototype.greaterThan = function (other) { - return this.comp(other) > 0; - }; - /** This is an alias of {@link Long.greaterThan} */ - Long.prototype.gt = function (other) { - return this.greaterThan(other); - }; - /** Tests if this Long's value is greater than or equal the specified's. */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.comp(other) >= 0; - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.gte = function (other) { - return this.greaterThanOrEqual(other); - }; - /** This is an alias of {@link Long.greaterThanOrEqual} */ - Long.prototype.ge = function (other) { - return this.greaterThanOrEqual(other); - }; - /** Tests if this Long's value is even. */ - Long.prototype.isEven = function () { - return (this.low & 1) === 0; - }; - /** Tests if this Long's value is negative. */ - Long.prototype.isNegative = function () { - return !this.unsigned && this.high < 0; - }; - /** Tests if this Long's value is odd. */ - Long.prototype.isOdd = function () { - return (this.low & 1) === 1; - }; - /** Tests if this Long's value is positive. */ - Long.prototype.isPositive = function () { - return this.unsigned || this.high >= 0; - }; - /** Tests if this Long's value equals zero. */ - Long.prototype.isZero = function () { - return this.high === 0 && this.low === 0; - }; - /** Tests if this Long's value is less than the specified's. */ - Long.prototype.lessThan = function (other) { - return this.comp(other) < 0; - }; - /** This is an alias of {@link Long#lessThan}. */ - Long.prototype.lt = function (other) { - return this.lessThan(other); - }; - /** Tests if this Long's value is less than or equal the specified's. */ - Long.prototype.lessThanOrEqual = function (other) { - return this.comp(other) <= 0; - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.lte = function (other) { - return this.lessThanOrEqual(other); - }; - /** Returns this Long modulo the specified. */ - Long.prototype.modulo = function (divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.mod = function (divisor) { - return this.modulo(divisor); - }; - /** This is an alias of {@link Long.modulo} */ - Long.prototype.rem = function (divisor) { - return this.modulo(divisor); - }; - /** - * Returns the product of this and the specified Long. - * @param multiplier - Multiplier - * @returns Product - */ - Long.prototype.multiply = function (multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - // use wasm support if present - if (wasm) { - var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } - else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - // If both longs are small, use float multiplication - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - /** This is an alias of {@link Long.multiply} */ - Long.prototype.mul = function (multiplier) { - return this.multiply(multiplier); - }; - /** Returns the Negation of this Long's value. */ - Long.prototype.negate = function () { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); - }; - /** This is an alias of {@link Long.negate} */ - Long.prototype.neg = function () { - return this.negate(); - }; - /** Returns the bitwise NOT of this Long. */ - Long.prototype.not = function () { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - }; - /** Tests if this Long's value differs from the specified's. */ - Long.prototype.notEquals = function (other) { - return !this.equals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.neq = function (other) { - return this.notEquals(other); - }; - /** This is an alias of {@link Long.notEquals} */ - Long.prototype.ne = function (other) { - return this.notEquals(other); - }; - /** - * Returns the bitwise OR of this Long and the specified. - */ - Long.prototype.or = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftLeft = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - }; - /** This is an alias of {@link Long.shiftLeft} */ - Long.prototype.shl = function (numBits) { - return this.shiftLeft(numBits); - }; - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRight = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - }; - /** This is an alias of {@link Long.shiftRight} */ - Long.prototype.shr = function (numBits) { - return this.shiftRight(numBits); - }; - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } - else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shr_u = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** This is an alias of {@link Long.shiftRightUnsigned} */ - Long.prototype.shru = function (numBits) { - return this.shiftRightUnsigned(numBits); - }; - /** - * Returns the difference of this and the specified Long. - * @param subtrahend - Subtrahend - * @returns Difference - */ - Long.prototype.subtract = function (subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - /** This is an alias of {@link Long.subtract} */ - Long.prototype.sub = function (subtrahend) { - return this.subtract(subtrahend); - }; - /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ - Long.prototype.toInt = function () { - return this.unsigned ? this.low >>> 0 : this.low; - }; - /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ - Long.prototype.toNumber = function () { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - /** Converts the Long to a BigInt (arbitrary precision). */ - Long.prototype.toBigInt = function () { - return BigInt(this.toString()); - }; - /** - * Converts this Long to its byte representation. - * @param le - Whether little or big endian, defaults to big endian - * @returns Byte representation - */ - Long.prototype.toBytes = function (le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - /** - * Converts this Long to its little endian byte representation. - * @returns Little endian byte representation - */ - Long.prototype.toBytesLE = function () { - var hi = this.high, lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - }; - /** - * Converts this Long to its big endian byte representation. - * @returns Big endian byte representation - */ - Long.prototype.toBytesBE = function () { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - }; - /** - * Converts this Long to signed. - */ - Long.prototype.toSigned = function () { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); - }; - /** - * Converts the Long to a string written in the specified radix. - * @param radix - Radix (2-36), defaults to 10 - * @throws RangeError If `radix` is out of range - */ - Long.prototype.toString = function (radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } - else - return '-' + this.neg().toString(radix); - } - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - // eslint-disable-next-line @typescript-eslint/no-this-alias - var rem = this; - var result = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - var digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - }; - /** Converts this Long to unsigned. */ - Long.prototype.toUnsigned = function () { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - }; - /** Returns the bitwise XOR of this Long and the given one. */ - Long.prototype.xor = function (other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - /** This is an alias of {@link Long.isZero} */ - Long.prototype.eqz = function () { - return this.isZero(); - }; - /** This is an alias of {@link Long.lessThanOrEqual} */ - Long.prototype.le = function (other) { - return this.lessThanOrEqual(other); - }; - /* - **************************************************************** - * BSON SPECIFIC ADDITIONS * - **************************************************************** - */ - Long.prototype.toExtendedJSON = function (options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; - }; - Long.fromExtendedJSON = function (doc, options) { - var result = Long.fromString(doc.$numberLong); - return options && options.relaxed ? result.toNumber() : result; - }; - /** @internal */ - Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Long.prototype.inspect = function () { - return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; - }; - Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); - /** Maximum unsigned value. */ - Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); - /** Signed zero */ - Long.ZERO = Long.fromInt(0); - /** Unsigned zero. */ - Long.UZERO = Long.fromInt(0, true); - /** Signed one. */ - Long.ONE = Long.fromInt(1); - /** Unsigned one. */ - Long.UONE = Long.fromInt(1, true); - /** Signed negative one. */ - Long.NEG_ONE = Long.fromInt(-1); - /** Maximum signed value. */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - /** Minimum signed value. */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - return Long; -}()); -exports.Long = Long; -Object.defineProperty(Long.prototype, '__isLong__', { value: true }); -Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); -//# sourceMappingURL=long.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/long.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/long.js.map deleted file mode 100644 index 1d5a359..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/long.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"long.js","sourceRoot":"","sources":["../src/long.ts"],"names":[],"mappings":";;;AACA,wCAA8C;AAkB9C;;GAEG;AACH,IAAI,IAAI,GAAgC,SAAS,CAAC;AAMlD,IAAI;IACF,IAAI,GAAG,IAAI,WAAW,CAAC,QAAQ,CAC7B,IAAI,WAAW,CAAC,MAAM;IACpB,kBAAkB;IAClB,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CA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js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/map.js deleted file mode 100644 index a92ae9c..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/map.js +++ /dev/null @@ -1,123 +0,0 @@ -"use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ -// We have an ES6 Map available, return the native instance -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Map = void 0; -var global_1 = require("./utils/global"); -/** @public */ -var bsonMap; -exports.Map = bsonMap; -var bsonGlobal = global_1.getGlobal(); -if (bsonGlobal.Map) { - exports.Map = bsonMap = bsonGlobal.Map; -} -else { - // We will return a polyfill - exports.Map = bsonMap = /** @class */ (function () { - function Map(array) { - if (array === void 0) { array = []; } - this._keys = []; - this._values = {}; - for (var i = 0; i < array.length; i++) { - if (array[i] == null) - continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - } - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) - return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - Map.prototype.entries = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? [key, _this._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.forEach = function (callback, self) { - self = self || this; - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - Map.prototype.keys = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - Map.prototype.values = function () { - var _this = this; - var index = 0; - return { - next: function () { - var key = _this._keys[index++]; - return { - value: key !== undefined ? _this._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - Object.defineProperty(Map.prototype, "size", { - get: function () { - return this._keys.length; - }, - enumerable: false, - configurable: true - }); - return Map; - }()); -} -//# sourceMappingURL=map.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/map.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/map.js.map deleted file mode 100644 index 972de88..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/map.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"map.js","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,2DAA2D;;;AAE3D,yCAA2C;AAE3C,cAAc;AACd,IAAI,OAAuB,CAAC;AAgHR,sBAAG;AA9GvB,IAAM,UAAU,GAAG,kBAAS,EAA4B,CAAC;AACzD,IAAI,UAAU,CAAC,GAAG,EAAE;IAClB,cAAA,OAAO,GAAG,UAAU,CAAC,GAAG,CAAC;CAC1B;KAAM;IACL,4BAA4B;IAC5B,cAAA,OAAO,GAAG;QAGR,aAAY,KAA2B;YAA3B,sBAAA,EAAA,UAA2B;YACrC,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;YAElB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACrC,IAAI,KAAK,CAAC,CAAC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key.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/max_key.js deleted file mode 100644 index c889eb8..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/max_key.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MaxKey = void 0; -/** - * A class representation of the BSON MaxKey type. - * @public - */ -var MaxKey = /** @class */ (function () { - function MaxKey() { - if (!(this instanceof MaxKey)) - return new MaxKey(); - } - /** @internal */ - MaxKey.prototype.toExtendedJSON = function () { - return { $maxKey: 1 }; - }; - /** @internal */ - MaxKey.fromExtendedJSON = function () { - return new MaxKey(); - }; - /** @internal */ - MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MaxKey.prototype.inspect = function () { - return 'new MaxKey()'; - }; - return MaxKey; -}()); -exports.MaxKey = MaxKey; -Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); -//# sourceMappingURL=max_key.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/max_key.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/max_key.js.map deleted file mode 100644 index 5bf01f9..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/max_key.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"max_key.js","sourceRoot":"","sources":["../src/max_key.ts"],"names":[],"mappings":";;;AAKA;;;GAGG;AACH;IAGE;QACE,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,EAAE,CAAC;IACrD,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACxB,CAAC;IAED,gBAAgB;IACT,uBAAgB,GAAvB;QACE,OAAO,IAAI,MAAM,EAAE,CAAC;IACtB,CAAC;IAED,gBAAgB;IAChB,iBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,wBAAO,GAAP;QACE,OAAO,cAAc,CAAC;IACxB,CAAC;IACH,aAAC;AAAD,CAAC,AAzBD,IAyBC;AAzBY,wBAAM;AA2BnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/min_key.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/min_key.js deleted file mode 100644 index 0912043..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/min_key.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MinKey = void 0; -/** - * A class representation of the BSON MinKey type. - * @public - */ -var MinKey = /** @class */ (function () { - function MinKey() { - if (!(this instanceof MinKey)) - return new MinKey(); - } - /** @internal */ - MinKey.prototype.toExtendedJSON = function () { - return { $minKey: 1 }; - }; - /** @internal */ - MinKey.fromExtendedJSON = function () { - return new MinKey(); - }; - /** @internal */ - MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - MinKey.prototype.inspect = function () { - return 'new MinKey()'; - }; - return MinKey; -}()); -exports.MinKey = MinKey; -Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); -//# sourceMappingURL=min_key.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/min_key.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/min_key.js.map deleted file mode 100644 index 753012e..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/min_key.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"min_key.js","sourceRoot":"","sources":["../src/min_key.ts"],"names":[],"mappings":";;;AAKA;;;GAGG;AACH;IAGE;QACE,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,EAAE,CAAC;IACrD,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACxB,CAAC;IAED,gBAAgB;IACT,uBAAgB,GAAvB;QACE,OAAO,IAAI,MAAM,EAAE,CAAC;IACtB,CAAC;IAED,gBAAgB;IAChB,iBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,wBAAO,GAAP;QACE,OAAO,cAAc,CAAC;IACxB,CAAC;IACH,aAAC;AAAD,CAAC,AAzBD,IAyBC;AAzBY,wBAAM;AA2BnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/objectid.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/objectid.js deleted file mode 100644 index 678b493..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/objectid.js +++ /dev/null @@ -1,308 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ObjectId = void 0; -var buffer_1 = require("buffer"); -var ensure_buffer_1 = require("./ensure_buffer"); -var error_1 = require("./error"); -var utils_1 = require("./parser/utils"); -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); -// Unique sequence for the current process (initialized on first use) -var PROCESS_UNIQUE = null; -var kId = Symbol('id'); -/** - * A class representation of the BSON ObjectId type. - * @public - */ -var ObjectId = /** @class */ (function () { - /** - * Create an ObjectId type - * - * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. - */ - function ObjectId(inputId) { - if (!(this instanceof ObjectId)) - return new ObjectId(inputId); - // workingId is set based on type of input and whether valid id exists for the input - var workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new error_1.BSONTypeError('Argument passed in must have an id that is of type string or Buffer'); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = buffer_1.Buffer.from(inputId.toHexString(), 'hex'); - } - else { - workingId = inputId.id; - } - } - else { - workingId = inputId; - } - // the following cases use workingId to construct an ObjectId - if (workingId == null || typeof workingId === 'number') { - // The most common use case (blank id, new objectId instance) - // Generate a new id - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } - else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ensure_buffer_1.ensureBuffer(workingId); - } - else if (typeof workingId === 'string') { - if (workingId.length === 12) { - var bytes = buffer_1.Buffer.from(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } - else { - throw new error_1.BSONTypeError('Argument passed in must be a string of 12 bytes'); - } - } - else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = buffer_1.Buffer.from(workingId, 'hex'); - } - else { - throw new error_1.BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters'); - } - } - else { - throw new error_1.BSONTypeError('Argument passed in does not match the accepted types'); - } - // If we are caching the hex string - if (ObjectId.cacheHexString) { - this.__id = this.id.toString('hex'); - } - } - Object.defineProperty(ObjectId.prototype, "id", { - /** - * The ObjectId bytes - * @readonly - */ - get: function () { - return this[kId]; - }, - set: function (value) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = value.toString('hex'); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObjectId.prototype, "generationTime", { - /** - * The generation time of this ObjectId instance - * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch - */ - get: function () { - return this.id.readInt32BE(0); - }, - set: function (value) { - // Encode time into first 4 bytes - this.id.writeUInt32BE(value, 0); - }, - enumerable: false, - configurable: true - }); - /** Returns the ObjectId id as a 24 character hex string representation */ - ObjectId.prototype.toHexString = function () { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - var hexString = this.id.toString('hex'); - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - return hexString; - }; - /** - * Update the ObjectId index - * @privateRemarks - * Used in generating new ObjectId's on the driver - * @internal - */ - ObjectId.getInc = function () { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - }; - /** - * Generate a 12 byte id buffer used in ObjectId's - * - * @param time - pass in a second based timestamp. - */ - ObjectId.generate = function (time) { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - var inc = ObjectId.getInc(); - var buffer = buffer_1.Buffer.alloc(12); - // 4-byte timestamp - buffer.writeUInt32BE(time, 0); - // set PROCESS_UNIQUE if yet not initialized - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = utils_1.randomBytes(5); - } - // 5-byte process unique - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - // 3-byte counter - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - return buffer; - }; - /** - * Converts the id into a 24 character hex string for printing - * - * @param format - The Buffer toString format parameter. - */ - ObjectId.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (format) - return this.id.toString(format); - return this.toHexString(); - }; - /** Converts to its JSON the 24 character hex string representation. */ - ObjectId.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this ObjectId with `otherID`. - * - * @param otherId - ObjectId instance to compare against. - */ - ObjectId.prototype.equals = function (otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (otherId instanceof ObjectId) { - return this.toString() === otherId.toString(); - } - if (typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - utils_1.isUint8Array(this.id)) { - return otherId === buffer_1.Buffer.prototype.toString.call(this.id, 'latin1'); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return buffer_1.Buffer.from(otherId).equals(this.id); - } - if (typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function') { - return otherId.toHexString() === this.toHexString(); - } - return false; - }; - /** Returns the generation date (accurate up to the second) that this ID was generated. */ - ObjectId.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id.readUInt32BE(0); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - /** @internal */ - ObjectId.createPk = function () { - return new ObjectId(); - }; - /** - * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. - * - * @param time - an integer number representing a number of seconds. - */ - ObjectId.createFromTime = function (time) { - var buffer = buffer_1.Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer.writeUInt32BE(time, 0); - // Return the new objectId - return new ObjectId(buffer); - }; - /** - * Creates an ObjectId from a hex string representation of an ObjectId. - * - * @param hexString - create a ObjectId from a passed in 24 character hexstring. - */ - ObjectId.createFromHexString = function (hexString) { - // Throw an error if it's not a valid setup - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new error_1.BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - return new ObjectId(buffer_1.Buffer.from(hexString, 'hex')); - }; - /** - * Checks if a value is a valid bson ObjectId - * - * @param id - ObjectId instance to validate. - */ - ObjectId.isValid = function (id) { - if (id == null) - return false; - if (typeof id === 'number') { - return true; - } - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - if (id instanceof ObjectId) { - return true; - } - if (utils_1.isUint8Array(id) && id.length === 12) { - return true; - } - // Duck-Typing detection of ObjectId like objects - if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { - if (typeof id.id === 'string') { - return id.id.length === 12; - } - return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); - } - return false; - }; - /** @internal */ - ObjectId.prototype.toExtendedJSON = function () { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - }; - /** @internal */ - ObjectId.fromExtendedJSON = function (doc) { - return new ObjectId(doc.$oid); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 24 character hex string representation. - * @internal - */ - ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - ObjectId.prototype.inspect = function () { - return "new ObjectId(\"" + this.toHexString() + "\")"; - }; - /** @internal */ - ObjectId.index = Math.floor(Math.random() * 0xffffff); - return ObjectId; -}()); -exports.ObjectId = ObjectId; -// Deprecated methods -Object.defineProperty(ObjectId.prototype, 'generate', { - value: utils_1.deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') -}); -Object.defineProperty(ObjectId.prototype, 'getInc', { - value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId.prototype, 'get_inc', { - value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId, 'get_inc', { - value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') -}); -Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); -//# sourceMappingURL=objectid.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/objectid.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/objectid.js.map deleted file mode 100644 index 913ecf9..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/objectid.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"objectid.js","sourceRoot":"","sources":["../src/objectid.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,iCAAwC;AACxC,wCAAsE;AAEtE,+CAA+C;AAC/C,IAAM,iBAAiB,GAAG,IAAI,MAAM,CAAC,mBAAmB,CAAC,CAAC;AAE1D,qEAAqE;AACrE,IAAI,cAAc,GAAsB,IAAI,CAAC;AAc7C,IAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AAEzB;;;GAGG;AACH;IAaE;;;;OAIG;IACH,kBAAY,OAA4D;QACtE,IAAI,CAAC,CAAC,IAAI,YAAY,QAAQ,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC,OAAO,CAAC,CAAC;QAE9D,oFAAoF;QACpF,IAAI,SAAS,CAAC;QACd,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,IAAI,IAAI,IAAI,OAAO,EAAE;YAC7D,IAAI,OAAO,OAAO,CAAC,EAAE,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;gBACrE,MAAM,IAAI,qBAAa,CACrB,qEAAqE,CACtE,CAAC;aACH;YACD,IAAI,aAAa,IAAI,OAAO,IAAI,OAAO,OAAO,CAAC,WAAW,KAAK,UAAU,EAAE;gBACzE,SAAS,GAAG,eAAM,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,KAAK,CAAC,CAAC;aACvD;iBAAM;gBACL,SAAS,GAAG,OAAO,CAAC,EAAE,CAAC;aACxB;SACF;aAAM;YACL,SAAS,GAAG,OAAO,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AE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/calculate_size.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/calculate_size.js deleted file mode 100644 index 47930ae..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/calculate_size.js +++ /dev/null @@ -1,193 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.calculateObjectSize = void 0; -var buffer_1 = require("buffer"); -var binary_1 = require("../binary"); -var constants = require("../constants"); -var utils_1 = require("./utils"); -function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } - else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - return totalLength; -} -exports.calculateObjectSize = calculateObjectSize; -/** @internal */ -function calculateElement(name, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -value, serializeFunctions, isArray, ignoreUndefined) { - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (isArray === void 0) { isArray = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = false; } - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - switch (typeof value) { - case 'string': - return 1 + buffer_1.Buffer.byteLength(name, 'utf8') + 1 + 4 + buffer_1.Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && - value >= constants.JS_INT_MIN && - value <= constants.JS_INT_MAX) { - if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { - // 32 bit - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } - else { - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } - else { - // 64 bit - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } - else if (value instanceof Date || utils_1.isDate(value)) { - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - utils_1.isAnyArrayBuffer(value)) { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); - } - else if (value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp') { - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - else if (value['_bsontype'] === 'Decimal128') { - return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } - else if (value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); - } - else { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + - 1); - } - } - else if (value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4)); - } - else { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); - } - } - else if (value['_bsontype'] === 'Symbol') { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - buffer_1.Buffer.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1); - } - else if (value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - // Add db reference if it exists - if (value.db != null) { - ordered_values['$db'] = value.db; - } - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); - } - else if (value instanceof RegExp || utils_1.isRegExp(value)) { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else if (value['_bsontype'] === 'BSONRegExp') { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.Buffer.byteLength(value.pattern, 'utf8') + - 1 + - buffer_1.Buffer.byteLength(value.options, 'utf8') + - 1); - } - else { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || utils_1.isRegExp(value) || String.call(value) === '[object RegExp]') { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - buffer_1.Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - buffer_1.Buffer.byteLength(utils_1.normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); - } - else if (serializeFunctions) { - return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - buffer_1.Buffer.byteLength(utils_1.normalizedFunctionString(value), 'utf8') + - 1); - } - } - } - return 0; -} -//# sourceMappingURL=calculate_size.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/calculate_size.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/calculate_size.js.map deleted file mode 100644 index f257092..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/calculate_size.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"calculate_size.js","sourceRoot":"","sources":["../../src/parser/calculate_size.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,oCAAmC;AAEnC,wCAA0C;AAC1C,iCAAuF;AAEvF,SAAgB,mBAAmB,CACjC,MAAgB,EAChB,kBAA4B,EAC5B,eAAyB;IAEzB,IAAI,WAAW,GAAG,CAAC,GAAG,CAAC,CAAC;IAExB,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACtC,WAAW,IAAI,gBAAgB,CAC7B,CAAC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AAM,GAAG,CAAC,EAAE;oBACpF,OAAO,CACL,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,eAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;wBACxD,CAAC;wBACD,CAAC;wBACD,CAAC;wBACD,eAAM,CAAC,UAAU,CAAC,gCAAwB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;wBAC1D,CAAC;wBACD,mBAAmB,CAAC,KAAK,CAAC,KAAK,EAAE,kBAAkB,EAAE,eAAe,CAAC,CACtE,CAAC;iBACH;qBAAM,IAAI,kBAAkB,EAAE;oBAC7B,OAAO,CACL,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,eAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;wBACxD,CAAC;wBACD,CAAC;wBACD,eAAM,CAAC,UAAU,CAAC,gCAAwB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;wBAC1D,CAAC,CACF,CAAC;iBACH;aACF;KACJ;IAED,OAAO,CAAC,CAAC;AACX,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/deserializer.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/deserializer.js deleted file mode 100644 index c29f3e0..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/deserializer.js +++ /dev/null @@ -1,656 +0,0 @@ -"use strict"; -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.deserialize = void 0; -var buffer_1 = require("buffer"); -var binary_1 = require("../binary"); -var code_1 = require("../code"); -var constants = require("../constants"); -var db_ref_1 = require("../db_ref"); -var decimal128_1 = require("../decimal128"); -var double_1 = require("../double"); -var error_1 = require("../error"); -var int_32_1 = require("../int_32"); -var long_1 = require("../long"); -var max_key_1 = require("../max_key"); -var min_key_1 = require("../min_key"); -var objectid_1 = require("../objectid"); -var regexp_1 = require("../regexp"); -var symbol_1 = require("../symbol"); -var timestamp_1 = require("../timestamp"); -var validate_utf8_1 = require("../validate_utf8"); -// Internal long versions -var JS_INT_MAX_LONG = long_1.Long.fromNumber(constants.JS_INT_MAX); -var JS_INT_MIN_LONG = long_1.Long.fromNumber(constants.JS_INT_MIN); -var functionCache = {}; -function deserialize(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (size < 5) { - throw new error_1.BSONError("bson size must be >= 5, is " + size); - } - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new error_1.BSONError("buffer length " + buffer.length + " must be >= bson size " + size); - } - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new error_1.BSONError("buffer length " + buffer.length + " must === bson size " + size); - } - if (size + index > buffer.byteLength) { - throw new error_1.BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); - } - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new error_1.BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -} -exports.deserialize = deserialize; -var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; -function deserializeObject(buffer, index, options, isArray) { - if (isArray === void 0) { isArray = false; } - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - // Ensures default validation option if none given - var validation = options.validation == null ? { utf8: true } : options.validation; - // Shows if global utf-8 validation is enabled or disabled - var globalUTFValidation = true; - // Reflects utf-8 validation setting regardless of global or specific key validation - var validationSetting; - // Set of keys either to enable or disable validation on - var utf8KeysSet = new Set(); - // Check for boolean uniformity and empty validation option - var utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } - else { - globalUTFValidation = false; - var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new error_1.BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new error_1.BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - // Ensures boolean uniformity in utf-8 validation (all true or all false) - if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) { - throw new error_1.BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - // Add keys to set that will either be validated or not based on validationSetting - if (!globalUTFValidation) { - for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) { - var key = _a[_i]; - utf8KeysSet.add(key); - } - } - // Set the start index - var startIndex = index; - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) - throw new error_1.BSONError('corrupt bson message < 5 bytes long'); - // Read the document size - var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) - throw new error_1.BSONError('corrupt bson message'); - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - var done = false; - var isPossibleDBRef = isArray ? false : null; - // While we have more left data left keep parsing - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) - break; - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.byteLength) - throw new error_1.BSONError('Bad BSON Document: illegal CString'); - // Represents the key - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - // shouldValidateKey is true if the key should be validated, false otherwise - var shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } - else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - var value = void 0; - index = i + 1; - if (elementType === constants.BSON_DATA_STRING) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new error_1.BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } - else if (elementType === constants.BSON_DATA_OID) { - var oid = buffer_1.Buffer.alloc(12); - buffer.copy(oid, 0, index, index + 12); - value = new objectid_1.ObjectId(oid); - index = index + 12; - } - else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { - value = new int_32_1.Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); - } - else if (elementType === constants.BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } - else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) { - value = new double_1.Double(buffer.readDoubleLE(index)); - index = index + 8; - } - else if (elementType === constants.BSON_DATA_NUMBER) { - value = buffer.readDoubleLE(index); - index = index + 8; - } - else if (elementType === constants.BSON_DATA_DATE) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new long_1.Long(lowBits, highBits).toNumber()); - } - else if (elementType === constants.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new error_1.BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } - else if (elementType === constants.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new error_1.BSONError('bad embedded document length in bson'); - // We have a raw value - if (raw) { - value = buffer.slice(index, index + objectSize); - } - else { - var objectOptions = options; - if (!globalUTFValidation) { - objectOptions = __assign(__assign({}, options), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - index = index + objectSize; - } - else if (elementType === constants.BSON_DATA_ARRAY) { - var _index = index; - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - // Stop index - var stopIndex = index + objectSize; - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) { - arrayOptions[n] = options[n]; - } - arrayOptions['raw'] = true; - } - if (!globalUTFValidation) { - arrayOptions = __assign(__assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } }); - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - if (buffer[index - 1] !== 0) - throw new error_1.BSONError('invalid array terminator byte'); - if (index !== stopIndex) - throw new error_1.BSONError('corrupted array bson'); - } - else if (elementType === constants.BSON_DATA_UNDEFINED) { - value = undefined; - } - else if (elementType === constants.BSON_DATA_NULL) { - value = null; - } - else if (elementType === constants.BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new long_1.Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } - else { - value = long; - } - } - else if (elementType === constants.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = buffer_1.Buffer.alloc(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new decimal128_1.Decimal128(bytes); - // If we have an alternative mapper use that - if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { - value = decimal128.toObject(); - } - else { - value = decimal128; - } - } - else if (elementType === constants.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - // Did we have a negative binary size, throw - if (binarySize < 0) - throw new error_1.BSONError('Negative binary type element size found'); - // Is the length longer than the document - if (binarySize > buffer.byteLength) - throw new error_1.BSONError('Binary type size larger than document size'); - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - if (promoteBuffers && promoteValues) { - value = buffer.slice(index, index + binarySize); - } - else { - value = new binary_1.Binary(buffer.slice(index, index + binarySize), subType); - } - } - else { - var _buffer = buffer_1.Buffer.alloc(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - if (promoteBuffers && promoteValues) { - value = _buffer; - } - else { - value = new binary_1.Binary(_buffer, subType); - } - } - // Update the index - index = index + binarySize; - } - else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new error_1.BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new error_1.BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - value = new RegExp(source, optionsArray.join('')); - } - else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new error_1.BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - index = i + 1; - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) - throw new error_1.BSONError('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - // Set the object - value = new regexp_1.BSONRegExp(source, regExpOptions); - } - else if (elementType === constants.BSON_DATA_SYMBOL) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new error_1.BSONError('bad string length in bson'); - } - var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new symbol_1.BSONSymbol(symbol); - index = index + stringSize; - } - else if (elementType === constants.BSON_DATA_TIMESTAMP) { - var lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new timestamp_1.Timestamp(lowBits, highBits); - } - else if (elementType === constants.BSON_DATA_MIN_KEY) { - value = new min_key_1.MinKey(); - } - else if (elementType === constants.BSON_DATA_MAX_KEY) { - value = new max_key_1.MaxKey(); - } - else if (elementType === constants.BSON_DATA_CODE) { - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new error_1.BSONError('bad string length in bson'); - } - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - } - else { - value = new code_1.Code(functionString); - } - // Update parse index position - index = index + stringSize; - } - else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new error_1.BSONError('code_w_scope total size shorter minimum expected length'); - } - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new error_1.BSONError('bad string length in bson'); - } - // Javascript function - var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - // Update parse index position - index = index + stringSize; - // Parse the element - var _index = index; - // Decode the size of the object document - var objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - // Check if field length is too short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new error_1.BSONError('code_w_scope total size is too short, truncating scope'); - } - // Check if totalSize field is too long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new error_1.BSONError('code_w_scope total size is too long, clips outer document'); - } - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } - else { - value = isolateEval(functionString); - } - value.scope = scopeObject; - } - else { - value = new code_1.Code(functionString, scopeObject); - } - } - else if (elementType === constants.BSON_DATA_DBPOINTER) { - // Get the code string size - var stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) - throw new error_1.BSONError('bad string length in bson'); - // Namespace - if (validation != null && validation.utf8) { - if (!validate_utf8_1.validateUtf8(buffer, index, index + stringSize - 1)) { - throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); - } - } - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Read the oid - var oidBuffer = buffer_1.Buffer.alloc(12); - buffer.copy(oidBuffer, 0, index, index + 12); - var oid = new objectid_1.ObjectId(oidBuffer); - // Update the index - index = index + 12; - // Upgrade to DBRef type - value = new db_ref_1.DBRef(namespace, oid); - } - else { - throw new error_1.BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value: value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - object[name] = value; - } - } - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) - throw new error_1.BSONError('corrupt array bson'); - throw new error_1.BSONError('corrupt object bson'); - } - // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef - if (!isPossibleDBRef) - return object; - if (db_ref_1.isDBRefLike(object)) { - var copy = Object.assign({}, object); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new db_ref_1.DBRef(object.$ref, object.$id, object.$db, copy); - } - return object; -} -/** - * Ensure eval is isolated, store the result in functionCache. - * - * @internal - */ -function isolateEval(functionString, functionCache, object) { - if (!functionCache) - return new Function(functionString); - // Check for cache hit, eval if missing and return cached function - if (functionCache[functionString] == null) { - functionCache[functionString] = new Function(functionString); - } - // Set the object - return functionCache[functionString].bind(object); -} -function getValidatedString(buffer, start, end, shouldValidateUtf8) { - var value = buffer.toString('utf8', start, end); - // if utf8 validation is on, do the check - if (shouldValidateUtf8) { - for (var i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validate_utf8_1.validateUtf8(buffer, start, end)) { - throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; -} -//# sourceMappingURL=deserializer.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/deserializer.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/deserializer.js.map deleted file mode 100644 index 0912087..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/deserializer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"deserializer.js","sourceRoot":"","sources":["../../src/parser/deserializer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,iCAAgC;AAChC,oCAAmC;AAEnC,gCAA+B;AAC/B,wCAA0C;AAC1C,oCAA0D;AAC1D,4CAA2C;AAC3C,oCAAmC;AACnC,kCAAqC;AACrC,oCAAkC;AAClC,gCAA+B;AAC/B,sCAAoC;AACpC,sCAAoC;AACpC,wCAAuC;AACvC,oCAAuC;AACvC,oCAAuC;AACvC,0CAAyC;AACzC,kDAAgD;AAgDhD,yBAAyB;AACzB,IAAM,eAAe,GAAG,WAAI,CAAC,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AAC9D,IAAM,eAAe,GAAG,WAAI,CAAC,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AAE9D,IAAM,aAAa,GAAiC,EAAE,CAAC;AAEvD,SAAgB,WAAW,CACzB,MAAc,EACd,OAA2B,EAC3B,O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aACP;SACF;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/serializer.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/serializer.js deleted file mode 100644 index 331e9ec..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/serializer.js +++ /dev/null @@ -1,869 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.serializeInto = void 0; -var binary_1 = require("../binary"); -var constants = require("../constants"); -var ensure_buffer_1 = require("../ensure_buffer"); -var error_1 = require("../error"); -var extended_json_1 = require("../extended_json"); -var float_parser_1 = require("../float_parser"); -var long_1 = require("../long"); -var map_1 = require("../map"); -var utils_1 = require("./utils"); -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); -/* - * isArray indicates if we are writing to a BSON array (type 0x04) - * which forces the "key" which really an array index as a string to be written as ascii - * This will catch any errors in index as a string generation - */ -function serializeString(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = constants.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, undefined, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -} -function serializeNumber(buffer, key, value, index, isArray) { - // We have an integer value - // TODO(NODE-2529): Add support for big int - if (Number.isInteger(value) && - value >= constants.BSON_INT32_MIN && - value <= constants.BSON_INT32_MAX) { - // If the value fits in 32 bits encode as int32 - // Set int type 32 bits or less - buffer[index++] = constants.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } - else { - // Encode as double - buffer[index++] = constants.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - float_parser_1.writeIEEE754(buffer, value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - } - return index; -} -function serializeNull(buffer, key, _, index, isArray) { - // Set long type - buffer[index++] = constants.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeBoolean(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} -function serializeDate(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var dateInMilis = long_1.Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.ignoreCase) - buffer[index++] = 0x69; // i - if (value.global) - buffer[index++] = 0x73; // s - if (value.multiline) - buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -} -function serializeBSONRegExp(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.pattern, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; -} -function serializeMinMax(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = constants.BSON_DATA_NULL; - } - else if (value._bsontype === 'MinKey') { - buffer[index++] = constants.BSON_DATA_MIN_KEY; - } - else { - buffer[index++] = constants.BSON_DATA_MAX_KEY; - } - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeObjectId(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, undefined, 'binary'); - } - else if (utils_1.isUint8Array(value.id)) { - // Use the standard JS methods here because buffer.copy() is buggy with the - // browser polyfill - buffer.set(value.id.subarray(0, 12), index); - } - else { - throw new error_1.BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - // Adjust index - return index + 12; -} -function serializeBuffer(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - buffer.set(ensure_buffer_1.ensureBuffer(value), index); - // Adjust the index - index = index + size; - return index; -} -function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (path === void 0) { path = []; } - for (var i = 0; i < path.length; i++) { - if (path[i] === value) - throw new error_1.BSONError('cyclic dependency detected'); - } - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - return endIndex; -} -function serializeDecimal128(buffer, key, value, index, isArray) { - buffer[index++] = constants.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - // Prefer the standard JS methods because their typechecking is not buggy, - // unlike the `buffer` polyfill's. - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; -} -function serializeLong(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = - value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeInt32(buffer, key, value, index, isArray) { - value = value.valueOf(); - // Set int type 32 bits or less - buffer[index++] = constants.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -} -function serializeDouble(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = constants.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - float_parser_1.writeIEEE754(buffer, value.value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - return index; -} -function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { - if (_checkKeys === void 0) { _checkKeys = false; } - if (_depth === void 0) { _depth = 0; } - buffer[index++] = constants.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = utils_1.normalizedFunctionString(value); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} -function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (checkKeys === void 0) { checkKeys = false; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (isArray === void 0) { isArray = false; } - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Starting index - var startIndex = index; - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - // Writ the total - var totalSize = endIndex - startIndex; - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } - else { - buffer[index++] = constants.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - return index; -} -function serializeBinary(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - // Write the data to the object - buffer.set(data, index); - // Adjust the index - index = index + value.position; - return index; -} -function serializeSymbol(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} -function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = constants.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var startIndex = index; - var output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; - } - output = Object.assign(output, value.fields); - var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} -function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - if (checkKeys === void 0) { checkKeys = false; } - if (startingIndex === void 0) { startingIndex = 0; } - if (depth === void 0) { depth = 0; } - if (serializeFunctions === void 0) { serializeFunctions = false; } - if (ignoreUndefined === void 0) { ignoreUndefined = true; } - if (path === void 0) { path = []; } - startingIndex = startingIndex || 0; - path = path || []; - // Push the object to the path - path.push(object); - // Start place to serialize into - var index = startingIndex + 4; - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new error_1.BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index, true); - } - else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } - else if (typeof value === 'bigint') { - throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } - else if (value instanceof Date || utils_1.isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } - else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } - else if (utils_1.isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } - else if (value instanceof RegExp || utils_1.isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } - else if (typeof value === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } - else if (typeof value === 'object' && - extended_json_1.isBSONType(value) && - value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else if (object instanceof map_1.Map || utils_1.isMap(object)) { - var iterator = object.entries(); - var done = false; - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = !!entry.done; - // Are we done, then skip and terminate - if (done) - continue; - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint' || utils_1.isBigInt64Array(value) || utils_1.isBigUInt64Array(value)) { - throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || utils_1.isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (utils_1.isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || utils_1.isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') - throw new error_1.BSONTypeError('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new error_1.BSONTypeError('toBSON function did not return an object'); - } - // Iterate over all the keys - for (var key in object) { - var value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') - throw new error_1.BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - // Check the type of the value - var type = typeof value; - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || utils_1.isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - if (ignoreUndefined === false) - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } - else if (utils_1.isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || utils_1.isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } - else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } - else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value['_bsontype'] !== 'undefined') { - throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - // Remove the path - path.pop(); - // Final padding byte for object - buffer[index++] = 0x00; - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} -exports.serializeInto = serializeInto; -//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/serializer.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/serializer.js.map deleted file mode 100644 index 834ae18..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/serializer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../../src/parser/serializer.ts"],"names":[],"mappings":";;;AACA,oCAAmC;AAGnC,wCAA0C;AAI1C,kDAAgD;AAChD,kCAAoD;AACpD,kDAA8C;AAC9C,gDAA+C;AAE/C,gCAA+B;AAC/B,8BAA6B;AAI7B,iCAQiB;AAgBjB,IAAM,MAAM,GAAG,MAAM,CAAC,CAAC,uCAAuC;AAC9D,IAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC,CAAC;AAEnE;;;;GAIG;AAEH,SAAS,eAAe,CACtB,MAAc,EACd,GAAW,EACX,KAA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AAM,IAAI,qBAAa,CAAC,qCAAqC,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;aACrF;SACF;KACF;IAED,kBAAkB;IAClB,IAAI,CAAC,GAAG,EAAE,CAAC;IAEX,gCAAgC;IAChC,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;IAEvB,aAAa;IACb,IAAM,IAAI,GAAG,KAAK,GAAG,aAAa,CAAC;IACnC,+BAA+B;IAC/B,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;IACtC,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;IAC7C,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IAC9C,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IAC9C,OAAO,KAAK,CAAC;AACf,CAAC;AAxUD,sCAwUC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/utils.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/utils.js deleted file mode 100644 index 88817ec..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/utils.js +++ /dev/null @@ -1,111 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.deprecate = exports.isObjectLike = exports.isDate = exports.haveBuffer = exports.isMap = exports.isRegExp = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.isAnyArrayBuffer = exports.randomBytes = exports.normalizedFunctionString = void 0; -var buffer_1 = require("buffer"); -var global_1 = require("../utils/global"); -/** - * Normalizes our expected stringified form of a function across versions of node - * @param fn - The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace('function(', 'function ('); -} -exports.normalizedFunctionString = normalizedFunctionString; -function isReactNative() { - var g = global_1.getGlobal(); - return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; -} -var insecureRandomBytes = function insecureRandomBytes(size) { - var insecureWarning = isReactNative() - ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' - : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; - console.warn(insecureWarning); - var result = buffer_1.Buffer.alloc(size); - for (var i = 0; i < size; ++i) - result[i] = Math.floor(Math.random() * 256); - return result; -}; -var detectRandomBytes = function () { - if (typeof window !== 'undefined') { - // browser crypto implementation(s) - var target_1 = window.crypto || window.msCrypto; // allow for IE11 - if (target_1 && target_1.getRandomValues) { - return function (size) { return target_1.getRandomValues(buffer_1.Buffer.alloc(size)); }; - } - } - if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { - // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global - return function (size) { return global.crypto.getRandomValues(buffer_1.Buffer.alloc(size)); }; - } - var requiredRandomBytes; - try { - // eslint-disable-next-line @typescript-eslint/no-var-requires - requiredRandomBytes = require('crypto').randomBytes; - } - catch (e) { - // keep the fallback - } - // NOTE: in transpiled cases the above require might return null/undefined - return requiredRandomBytes || insecureRandomBytes; -}; -exports.randomBytes = detectRandomBytes(); -function isAnyArrayBuffer(value) { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; -function isUint8Array(value) { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; -} -exports.isUint8Array = isUint8Array; -function isBigInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigInt64Array]'; -} -exports.isBigInt64Array = isBigInt64Array; -function isBigUInt64Array(value) { - return Object.prototype.toString.call(value) === '[object BigUint64Array]'; -} -exports.isBigUInt64Array = isBigUInt64Array; -function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -function isMap(d) { - return Object.prototype.toString.call(d) === '[object Map]'; -} -exports.isMap = isMap; -/** Call to check if your environment has `Buffer` */ -function haveBuffer() { - return typeof global !== 'undefined' && typeof global.Buffer !== 'undefined'; -} -exports.haveBuffer = haveBuffer; -// To ensure that 0.4 of node works correctly -function isDate(d) { - return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; -} -exports.isDate = isDate; -/** - * @internal - * this is to solve the `'someKey' in x` problem where x is unknown. - * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 - */ -function isObjectLike(candidate) { - return typeof candidate === 'object' && candidate !== null; -} -exports.isObjectLike = isObjectLike; -function deprecate(fn, message) { - var warned = false; - function deprecated() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!warned) { - console.warn(message); - warned = true; - } - return fn.apply(this, args); - } - return deprecated; -} -exports.deprecate = deprecate; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/utils.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/utils.js.map deleted file mode 100644 index caa7cec..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/parser/utils.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/parser/utils.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,0CAA4C;AAI5C;;;GAGG;AACH,SAAgB,wBAAwB,CAAC,EAAY;IACnD,OAAO,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;AAC1D,CAAC;AAFD,4DAEC;AAED,SAAS,aAAa;IACpB,IAAM,CAAC,GAAG,kBAAS,EAAwC,CAAC;IAC5D,OAAO,OAAO,CAAC,CAAC,SAAS,KAAK,Q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,MAAM,KAAK,WAAW,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,WAAW,CAAC;AAC/E,CAAC;AAFD,gCAEC;AAED,6CAA6C;AAC7C,SAAgB,MAAM,CAAC,CAAU;IAC/B,OAAO,YAAY,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,eAAe,CAAC;AAClF,CAAC;AAFD,wBAEC;AAED;;;;GAIG;AACH,SAAgB,YAAY,CAAC,SAAkB;IAC7C,OAAO,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,IAAI,CAAC;AAC7D,CAAC;AAFD,oCAEC;AAGD,SAAgB,SAAS,CAAqB,EAAK,EAAE,OAAe;IAClE,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,SAAS,UAAU;QAAgB,cAAkB;aAAlB,UAAkB,EAAlB,qBAAkB,EAAlB,IAAkB;YAAlB,yBAAkB;;QACnD,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACtB,MAAM,GAAG,IAAI,CAAC;SACf;QACD,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,UAA0B,CAAC;AACpC,CAAC;AAVD,8BAUC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/regexp.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/regexp.js deleted file mode 100644 index 079fb3c..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/regexp.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BSONRegExp = void 0; -var error_1 = require("./error"); -function alphabetize(str) { - return str.split('').sort().join(''); -} -/** - * A class representation of the BSON RegExp type. - * @public - */ -var BSONRegExp = /** @class */ (function () { - /** - * @param pattern - The regular expression pattern to match - * @param options - The regular expression options - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) - return new BSONRegExp(pattern, options); - this.pattern = pattern; - this.options = alphabetize(options !== null && options !== void 0 ? options : ''); - if (this.pattern.indexOf('\x00') !== -1) { - throw new error_1.BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); - } - if (this.options.indexOf('\x00') !== -1) { - throw new error_1.BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); - } - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u')) { - throw new error_1.BSONError("The regular expression option [" + this.options[i] + "] is not supported"); - } - } - } - BSONRegExp.parseOptions = function (options) { - return options ? options.split('').sort().join('') : ''; - }; - /** @internal */ - BSONRegExp.prototype.toExtendedJSON = function (options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - }; - /** @internal */ - BSONRegExp.fromExtendedJSON = function (doc) { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - // This is for $regex query operators that have extended json values. - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc; - } - } - else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); - } - throw new error_1.BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); - }; - return BSONRegExp; -}()); -exports.BSONRegExp = BSONRegExp; -Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); -//# sourceMappingURL=regexp.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/regexp.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/regexp.js.map deleted file mode 100644 index 79464b5..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/regexp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"regexp.js","sourceRoot":"","sources":["../src/regexp.ts"],"names":[],"mappings":";;;AAAA,iCAAmD;AAGnD,SAAS,WAAW,CAAC,GAAW;IAC9B,OAAO,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACvC,CAAC;AAgBD;;;GAGG;AACH;IAKE;;;OAGG;IACH,oBAAY,OAAe,EAAE,OAAgB;QAC3C,IAAI,CAAC,CAAC,IAAI,YAAY,UAAU,CAAC;YAAE,OAAO,IAAI,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE3E,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,CAAC;QAE1C,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;YACvC,MAAM,IAAI,iBAAS,CACjB,2DAAyD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAG,CACxF,CAAC;SACH;QACD,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;YACvC,MAAM,IAAI,iBAAS,CACjB,0DAAwD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAG,CACvF,CAAC;SACH;QAED,mBAAmB;QACnB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC5C,IACE,CAAC,CACC,IAAI,CAAC,O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GAA4B,CAAC;iBACrC;aACF;iBAAM;gBACL,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;aAC1E;SACF;QACD,IAAI,oBAAoB,IAAI,GAAG,EAAE;YAC/B,OAAO,IAAI,UAAU,CACnB,GAAG,CAAC,kBAAkB,CAAC,OAAO,EAC9B,UAAU,CAAC,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,OAAO,CAAC,CACxD,CAAC;SACH;QACD,MAAM,IAAI,qBAAa,CAAC,8CAA4C,IAAI,CAAC,SAAS,CAAC,GAAG,CAAG,CAAC,CAAC;IAC7F,CAAC;IACH,iBAAC;AAAD,CAAC,AA5ED,IA4EC;AA5EY,gCAAU;AA8EvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/symbol.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/symbol.js deleted file mode 100644 index 02ca75f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/symbol.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BSONSymbol = void 0; -/** - * A class representation of the BSON Symbol type. - * @public - */ -var BSONSymbol = /** @class */ (function () { - /** - * @param value - the string representing the symbol. - */ - function BSONSymbol(value) { - if (!(this instanceof BSONSymbol)) - return new BSONSymbol(value); - this.value = value; - } - /** Access the wrapped string value. */ - BSONSymbol.prototype.valueOf = function () { - return this.value; - }; - BSONSymbol.prototype.toString = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.inspect = function () { - return "new BSONSymbol(\"" + this.value + "\")"; - }; - BSONSymbol.prototype.toJSON = function () { - return this.value; - }; - /** @internal */ - BSONSymbol.prototype.toExtendedJSON = function () { - return { $symbol: this.value }; - }; - /** @internal */ - BSONSymbol.fromExtendedJSON = function (doc) { - return new BSONSymbol(doc.$symbol); - }; - /** @internal */ - BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - return BSONSymbol; -}()); -exports.BSONSymbol = BSONSymbol; -Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); -//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/symbol.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/symbol.js.map deleted file mode 100644 index aa55410..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/symbol.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"symbol.js","sourceRoot":"","sources":["../src/symbol.ts"],"names":[],"mappings":";;;AAKA;;;GAGG;AACH;IAIE;;OAEG;IACH,oBAAY,KAAa;QACvB,IAAI,CAAC,CAAC,IAAI,YAAY,UAAU,CAAC;YAAE,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;QAEhE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,uCAAuC;IACvC,4BAAO,GAAP;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,6BAAQ,GAAR;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,4BAAO,GAAP;QACE,OAAO,sBAAmB,IAAI,CAAC,KAAK,QAAI,CAAC;IAC3C,CAAC;IAED,2BAAM,GAAN;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,mCAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IACjC,CAAC;IAED,gBAAgB;IACT,2BAAgB,GAAvB,UAAwB,GAAuB;QAC7C,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,gBAAgB;IAChB,qBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IACH,iBAAC;AAAD,CAAC,AA7CD,IA6CC;AA7CY,gCAAU;AA+CvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/timestamp.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/timestamp.js deleted file mode 100644 index 5750e6b..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/timestamp.js +++ /dev/null @@ -1,99 +0,0 @@ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Timestamp = exports.LongWithoutOverridesClass = void 0; -var long_1 = require("./long"); -var utils_1 = require("./parser/utils"); -/** @public */ -exports.LongWithoutOverridesClass = long_1.Long; -/** @public */ -var Timestamp = /** @class */ (function (_super) { - __extends(Timestamp, _super); - function Timestamp(low, high) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - ///@ts-expect-error - if (!(_this instanceof Timestamp)) - return new Timestamp(low, high); - if (long_1.Long.isLong(low)) { - _this = _super.call(this, low.low, low.high, true) || this; - } - else if (utils_1.isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { - _this = _super.call(this, low.i, low.t, true) || this; - } - else { - _this = _super.call(this, low, high, true) || this; - } - Object.defineProperty(_this, '_bsontype', { - value: 'Timestamp', - writable: false, - configurable: false, - enumerable: false - }); - return _this; - } - Timestamp.prototype.toJSON = function () { - return { - $timestamp: this.toString() - }; - }; - /** Returns a Timestamp represented by the given (32-bit) integer value. */ - Timestamp.fromInt = function (value) { - return new Timestamp(long_1.Long.fromInt(value, true)); - }; - /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ - Timestamp.fromNumber = function (value) { - return new Timestamp(long_1.Long.fromNumber(value, true)); - }; - /** - * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. - * - * @param lowBits - the low 32-bits. - * @param highBits - the high 32-bits. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - /** - * Returns a Timestamp from the given string, optionally using the given radix. - * - * @param str - the textual representation of the Timestamp. - * @param optRadix - the radix in which the text is written. - */ - Timestamp.fromString = function (str, optRadix) { - return new Timestamp(long_1.Long.fromString(str, true, optRadix)); - }; - /** @internal */ - Timestamp.prototype.toExtendedJSON = function () { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - }; - /** @internal */ - Timestamp.fromExtendedJSON = function (doc) { - return new Timestamp(doc.$timestamp); - }; - /** @internal */ - Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - Timestamp.prototype.inspect = function () { - return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; - }; - Timestamp.MAX_VALUE = long_1.Long.MAX_UNSIGNED_VALUE; - return Timestamp; -}(exports.LongWithoutOverridesClass)); -exports.Timestamp = Timestamp; -//# sourceMappingURL=timestamp.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/timestamp.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/timestamp.js.map deleted file mode 100644 index fb2a59f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/timestamp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../src/timestamp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,+BAA8B;AAC9B,wCAA8C;AAQ9C,cAAc;AACD,QAAA,yBAAyB,GACpC,WAAuC,CAAC;AAU1C,cAAc;AACd;IAA+B,6BAAyB;IAmBtD,mBAAY,GAA6C,EAAE,IAAa;QAAxE,iBAkBC;QAjBC,6DAA6D;QAC7D,mBAAmB;QACnB,IAAI,CAAC,CAAC,KAAI,YAAY,SAAS,CAAC;YAAE,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAElE,IAAI,WAAI,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE;YACpB,QAAA,kBAAM,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,SAAC;SAChC;aAAM,IAAI,oBAAY,CAAC,GAAG,CAAC,IAAI,OAAO,GAAG,CAAC,CAAC,KAAK,WAAW,IAAI,OAAO,GAAG,CAAC,CAAC,KAAK,WAAW,EAAE;YAC5F,QAAA,kBAAM,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,SAAC;SAC3B;aAAM;YACL,QAAA,kBAAM,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,SAAC;SACxB;QACD,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,WAAW,EAAE;YACvC,KAAK,EAAE,WAAW;YAClB,QAAQ,EAAE,KAAK;YACf,YAAY,EAAE,KAAK;YACnB,UAAU,EA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AI,CAAC,WAAW,EAAE,aAAQ,IAAI,CAAC,UAAU,EAAE,QAAK,CAAC;IAChF,CAAC;IAzFe,mBAAS,GAAG,WAAI,CAAC,kBAAkB,CAAC;IA0FtD,gBAAC;CAAA,AA7FD,CAA+B,iCAAyB,GA6FvD;AA7FY,8BAAS"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/utils/global.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/utils/global.js deleted file mode 100644 index 30218ea..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/utils/global.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getGlobal = void 0; -function checkForMath(potentialGlobal) { - // eslint-disable-next-line eqeqeq - return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; -} -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -function getGlobal() { - // eslint-disable-next-line no-undef - return (checkForMath(typeof globalThis === 'object' && globalThis) || - checkForMath(typeof window === 'object' && window) || - checkForMath(typeof self === 'object' && self) || - checkForMath(typeof global === 'object' && global) || - Function('return this')()); -} -exports.getGlobal = getGlobal; -//# sourceMappingURL=global.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/utils/global.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/utils/global.js.map deleted file mode 100644 index ebd51ab..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/utils/global.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"global.js","sourceRoot":"","sources":["../../src/utils/global.ts"],"names":[],"mappings":";;;AAMA,SAAS,YAAY,CAAC,eAAoB;IACxC,kCAAkC;IAClC,OAAO,eAAe,IAAI,eAAe,CAAC,IAAI,IAAI,IAAI,IAAI,eAAe,CAAC;AAC5E,CAAC;AAED,uEAAuE;AACvE,SAAgB,SAAS;IACvB,oCAAoC;IACpC,OAAO,CACL,YAAY,CAAC,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC;QAC1D,YAAY,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC;QAClD,YAAY,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC;QAC9C,YAAY,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC;QAClD,QAAQ,CAAC,aAAa,CAAC,EAAE,CAC1B,CAAC;AACJ,CAAC;AATD,8BASC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid.js deleted file mode 100644 index bd0bf38..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid.js +++ /dev/null @@ -1,179 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UUID = void 0; -var buffer_1 = require("buffer"); -var ensure_buffer_1 = require("./ensure_buffer"); -var binary_1 = require("./binary"); -var uuid_utils_1 = require("./uuid_utils"); -var utils_1 = require("./parser/utils"); -var error_1 = require("./error"); -var BYTE_LENGTH = 16; -var kId = Symbol('id'); -/** - * A class representation of the BSON UUID type. - * @public - */ -var UUID = /** @class */ (function () { - /** - * Create an UUID type - * - * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. - */ - function UUID(input) { - if (typeof input === 'undefined') { - // The most common use case (blank id, new UUID() instance) - this.id = UUID.generate(); - } - else if (input instanceof UUID) { - this[kId] = buffer_1.Buffer.from(input.id); - this.__id = input.__id; - } - else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { - this.id = ensure_buffer_1.ensureBuffer(input); - } - else if (typeof input === 'string') { - this.id = uuid_utils_1.uuidHexStringToBuffer(input); - } - else { - throw new error_1.BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); - } - } - Object.defineProperty(UUID.prototype, "id", { - /** - * The UUID bytes - * @readonly - */ - get: function () { - return this[kId]; - }, - set: function (value) { - this[kId] = value; - if (UUID.cacheHexString) { - this.__id = uuid_utils_1.bufferToUuidHexString(value); - } - }, - enumerable: false, - configurable: true - }); - /** - * Generate a 16 byte uuid v4 buffer used in UUIDs - */ - /** - * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) - * @param includeDashes - should the string exclude dash-separators. - * */ - UUID.prototype.toHexString = function (includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - var uuidHexString = uuid_utils_1.bufferToUuidHexString(this.id, includeDashes); - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - return uuidHexString; - }; - /** - * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. - */ - UUID.prototype.toString = function (encoding) { - return encoding ? this.id.toString(encoding) : this.toHexString(); - }; - /** - * Converts the id into its JSON string representation. - * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - */ - UUID.prototype.toJSON = function () { - return this.toHexString(); - }; - /** - * Compares the equality of this UUID with `otherID`. - * - * @param otherId - UUID instance to compare against. - */ - UUID.prototype.equals = function (otherId) { - if (!otherId) { - return false; - } - if (otherId instanceof UUID) { - return otherId.id.equals(this.id); - } - try { - return new UUID(otherId).id.equals(this.id); - } - catch (_a) { - return false; - } - }; - /** - * Creates a Binary instance from the current UUID. - */ - UUID.prototype.toBinary = function () { - return new binary_1.Binary(this.id, binary_1.Binary.SUBTYPE_UUID); - }; - /** - * Generates a populated buffer containing a v4 uuid - */ - UUID.generate = function () { - var bytes = utils_1.randomBytes(BYTE_LENGTH); - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - return buffer_1.Buffer.from(bytes); - }; - /** - * Checks if a value is a valid bson UUID - * @param input - UUID, string or Buffer to validate. - */ - UUID.isValid = function (input) { - if (!input) { - return false; - } - if (input instanceof UUID) { - return true; - } - if (typeof input === 'string') { - return uuid_utils_1.uuidValidateString(input); - } - if (utils_1.isUint8Array(input)) { - // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) - if (input.length !== BYTE_LENGTH) { - return false; - } - try { - // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx - // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx - return parseInt(input[6].toString(16)[0], 10) === binary_1.Binary.SUBTYPE_UUID; - } - catch (_a) { - return false; - } - } - return false; - }; - /** - * Creates an UUID from a hex string representation of an UUID. - * @param hexString - 32 or 36 character hex string (dashes excluded/included). - */ - UUID.createFromHexString = function (hexString) { - var buffer = uuid_utils_1.uuidHexStringToBuffer(hexString); - return new UUID(buffer); - }; - /** - * Converts to a string representation of this Id. - * - * @returns return the 36 character hex string representation. - * @internal - */ - UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { - return this.inspect(); - }; - UUID.prototype.inspect = function () { - return "new UUID(\"" + this.toHexString() + "\")"; - }; - return UUID; -}()); -exports.UUID = UUID; -Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); -//# sourceMappingURL=uuid.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid.js.map deleted file mode 100644 index 6eeb216..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"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4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,sBAAO,GAAP;QACE,OAAO,gBAAa,IAAI,CAAC,WAAW,EAAE,QAAI,CAAC;IAC7C,CAAC;IACH,WAAC;AAAD,CAAC,AA1LD,IA0LC;AA1LY,oBAAI;AA4LjB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid_utils.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid_utils.js deleted file mode 100644 index 7ccc6ac..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid_utils.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bufferToUuidHexString = exports.uuidHexStringToBuffer = exports.uuidValidateString = void 0; -var buffer_1 = require("buffer"); -var error_1 = require("./error"); -// Validation regex for v4 uuid (validates with or without dashes) -var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; -var uuidValidateString = function (str) { - return typeof str === 'string' && VALIDATION_REGEX.test(str); -}; -exports.uuidValidateString = uuidValidateString; -var uuidHexStringToBuffer = function (hexString) { - if (!exports.uuidValidateString(hexString)) { - throw new error_1.BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); - } - var sanitizedHexString = hexString.replace(/-/g, ''); - return buffer_1.Buffer.from(sanitizedHexString, 'hex'); -}; -exports.uuidHexStringToBuffer = uuidHexStringToBuffer; -var bufferToUuidHexString = function (buffer, includeDashes) { - if (includeDashes === void 0) { includeDashes = true; } - return includeDashes - ? buffer.toString('hex', 0, 4) + - '-' + - buffer.toString('hex', 4, 6) + - '-' + - buffer.toString('hex', 6, 8) + - '-' + - buffer.toString('hex', 8, 10) + - '-' + - buffer.toString('hex', 10, 16) - : buffer.toString('hex'); -}; -exports.bufferToUuidHexString = bufferToUuidHexString; -//# sourceMappingURL=uuid_utils.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid_utils.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid_utils.js.map deleted file mode 100644 index 0d7b1f1..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/uuid_utils.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"uuid_utils.js","sourceRoot":"","sources":["../src/uuid_utils.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AAExC,kEAAkE;AAClE,IAAM,gBAAgB,GACpB,uHAAuH,CAAC;AAEnH,IAAM,kBAAkB,GAAG,UAAC,GAAW;IAC5C,OAAA,OAAO,GAAG,KAAK,QAAQ,IAAI,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;AAArD,CAAqD,CAAC;AAD3C,QAAA,kBAAkB,sBACyB;AAEjD,IAAM,qBAAqB,GAAG,UAAC,SAAiB;IACrD,IAAI,CAAC,0BAAkB,CAAC,SAAS,CAAC,EAAE;QAClC,MAAM,IAAI,qBAAa,CACrB,uLAAuL,CACxL,CAAC;KACH;IAED,IAAM,kBAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACvD,OAAO,eAAM,CAAC,IAAI,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;AAChD,CAAC,CAAC;AATW,QAAA,qBAAqB,yBAShC;AAEK,IAAM,qBAAqB,GAAG,UAAC,MAAc,EAAE,aAAoB;IAApB,8BAAA,EAAA,oBAAoB;IACxE,OAAA,aAAa;QACX,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAC7B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE,CAAC;QAChC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;AAV1B,CAU0B,CAAC;AAXhB,QAAA,qBAAqB,yBAWL"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/validate_utf8.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/validate_utf8.js deleted file mode 100644 index ec78016..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/validate_utf8.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validateUtf8 = void 0; -var FIRST_BIT = 0x80; -var FIRST_TWO_BITS = 0xc0; -var FIRST_THREE_BITS = 0xe0; -var FIRST_FOUR_BITS = 0xf0; -var FIRST_FIVE_BITS = 0xf8; -var TWO_BIT_CHAR = 0xc0; -var THREE_BIT_CHAR = 0xe0; -var FOUR_BIT_CHAR = 0xf0; -var CONTINUING_CHAR = 0x80; -/** - * Determines if the passed in bytes are valid utf8 - * @param bytes - An array of 8-bit bytes. Must be indexable and have length property - * @param start - The index to start validating - * @param end - The index to end validating - */ -function validateUtf8(bytes, start, end) { - var continuation = 0; - for (var i = start; i < end; i += 1) { - var byte = bytes[i]; - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } - else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } - else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } - else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } - else { - return false; - } - } - } - return !continuation; -} -exports.validateUtf8 = validateUtf8; -//# sourceMappingURL=validate_utf8.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/validate_utf8.js.map b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/validate_utf8.js.map deleted file mode 100644 index f1e975b..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/lib/validate_utf8.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"validate_utf8.js","sourceRoot":"","sources":["../src/validate_utf8.ts"],"names":[],"mappings":";;;AAAA,IAAM,SAAS,GAAG,IAAI,CAAC;AACvB,IAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,IAAM,gBAAgB,GAAG,IAAI,CAAC;AAC9B,IAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,IAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,IAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,IAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,IAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,IAAM,eAAe,GAAG,IAAI,CAAC;AAE7B;;;;;GAKG;AACH,SAAgB,YAAY,CAC1B,KAAkC,EAClC,KAAa,EACb,GAAW;IAEX,IAAI,YAAY,GAAG,CAAC,CAAC;IAErB,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE;QACnC,IAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAEtB,IAAI,YAAY,EAAE;YAChB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC,KAAK,eAAe,EAAE;gBAC/C,OAAO,KAAK,CAAC;aACd;YACD,YAAY,IAAI,CAAC,CAAC;SACnB;aAAM,IAAI,IAAI,GAAG,SAAS,EAAE;YAC3B,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC,KAAK,YAAY,EAAE;gBAC9C,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC,KAAK,cAAc,EAAE;gBACtD,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC,KAAK,aAAa,EAAE;gBACrD,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM;gBACL,OAAO,KAAK,CAAC;aACd;SACF;KACF;IAED,OAAO,CAAC,YAAY,CAAC;AACvB,CAAC;AA7BD,oCA6BC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/package.json b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/package.json deleted file mode 100644 index 1e83c0f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/package.json +++ /dev/null @@ -1,115 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "files": [ - "lib", - "src", - "dist", - "bson.d.ts", - "etc/prepare.js", - "bower.json" - ], - "types": "bson.d.ts", - "version": "4.6.0", - "author": { - "name": "The MongoDB NodeJS Team", - "email": "dbx-node@mongodb.com" - }, - "license": "Apache-2.0", - "contributors": [], - "repository": "mongodb/js-bson", - "bugs": { - "url": "https://jira.mongodb.org/projects/NODE/issues/" - }, - "devDependencies": { - "@babel/plugin-external-helpers": "^7.10.4", - "@babel/preset-env": "^7.11.0", - "@istanbuljs/nyc-config-typescript": "^1.0.1", - "@microsoft/api-extractor": "^7.11.2", - "@rollup/plugin-babel": "^5.2.0", - "@rollup/plugin-commonjs": "^15.0.0", - "@rollup/plugin-json": "^4.1.0", - "@rollup/plugin-node-resolve": "^9.0.0", - "@rollup/plugin-typescript": "^6.0.0", - "@typescript-eslint/eslint-plugin": "^3.10.1", - "@typescript-eslint/parser": "^3.10.1", - "array-includes": "^3.1.3", - "benchmark": "^2.1.4", - "chai": "^4.2.0", - "downlevel-dts": "^0.7.0", - "eslint": "^7.7.0", - "eslint-config-prettier": "^6.11.0", - "eslint-plugin-prettier": "^3.1.4", - "eslint-plugin-tsdoc": "^0.2.6", - "karma": "^6.3.4", - "karma-chai": "^0.1.0", - "karma-chrome-launcher": "^3.1.0", - "karma-mocha": "^2.0.1", - "karma-mocha-reporter": "^2.2.5", - "karma-rollup-preprocessor": "^7.0.5", - "mocha": "5.2.0", - "node-fetch": "^2.6.1", - "nyc": "^15.1.0", - "object.entries": "^1.1.4", - "prettier": "^2.1.1", - "rimraf": "^3.0.2", - "rollup": "^2.26.5", - "rollup-plugin-commonjs": "^10.1.0", - "rollup-plugin-node-globals": "^1.4.0", - "rollup-plugin-node-polyfills": "^0.2.1", - "rollup-plugin-polyfill-node": "^0.7.0", - "standard-version": "^9.3.0", - "ts-node": "^9.0.0", - "tsd": "^0.17.0", - "typedoc": "^0.21.2", - "typescript": "^4.0.2", - "typescript-cached-transpile": "0.0.6", - "uuid": "^8.3.2" - }, - "tsd": { - "directory": "test/types", - "compilerOptions": { - "strict": true, - "target": "esnext", - "module": "commonjs", - "moduleResolution": "node" - } - }, - "config": { - "native": false - }, - "main": "lib/bson.js", - "module": "dist/bson.esm.js", - "browser": { - "./lib/bson.js": "./dist/bson.browser.umd.js", - "./dist/bson.esm.js": "./dist/bson.browser.esm.js" - }, - "engines": { - "node": ">=6.9.0" - }, - "scripts": { - "docs": "typedoc", - "test": "npm run build && npm run test-node && npm run test-browser", - "test-node": "mocha test/node test/*_tests.js", - "test-tsd": "npm run build:dts && tsd", - "test-browser": "node --max-old-space-size=4096 ./node_modules/.bin/karma start karma.conf.js", - "build:ts": "tsc", - "build:dts": "npm run build:ts && api-extractor run --typescript-compiler-folder node_modules/typescript --local && rimraf 'lib/**/*.d.ts*' && downlevel-dts bson.d.ts bson.d.ts", - "build:bundle": "rollup -c rollup.config.js", - "build": "npm run build:dts && npm run build:bundle", - "lint": "eslint -v && eslint --ext '.js,.ts' --max-warnings=0 src test && tsc -v && tsc --noEmit && npm run test-tsd", - "format": "eslint --ext '.js,.ts' src test --fix", - "coverage": "nyc npm run test-node", - "coverage:html": "npm run coverage && open ./coverage/index.html", - "prepare": "node etc/prepare.js", - "release": "standard-version -i HISTORY.md" - }, - "dependencies": { - "buffer": "^5.6.0" - } -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/binary.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/binary.ts deleted file mode 100644 index 2b82893..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/binary.ts +++ /dev/null @@ -1,286 +0,0 @@ -import { Buffer } from 'buffer'; -import { ensureBuffer } from './ensure_buffer'; -import { uuidHexStringToBuffer } from './uuid_utils'; -import { UUID, UUIDExtended } from './uuid'; -import type { EJSONOptions } from './extended_json'; -import { BSONError, BSONTypeError } from './error'; - -/** @public */ -export type BinarySequence = Uint8Array | Buffer | number[]; - -/** @public */ -export interface BinaryExtendedLegacy { - $type: string; - $binary: string; -} - -/** @public */ -export interface BinaryExtended { - $binary: { - subType: string; - base64: string; - }; -} - -/** - * A class representation of the BSON Binary type. - * @public - */ -export class Binary { - _bsontype!: 'Binary'; - - /** - * Binary default subtype - * @internal - */ - private static readonly BSON_BINARY_SUBTYPE_DEFAULT = 0; - - /** Initial buffer default size */ - static readonly BUFFER_SIZE = 256; - /** Default BSON type */ - static readonly SUBTYPE_DEFAULT = 0; - /** Function BSON type */ - static readonly SUBTYPE_FUNCTION = 1; - /** Byte Array BSON type */ - static readonly SUBTYPE_BYTE_ARRAY = 2; - /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ - static readonly SUBTYPE_UUID_OLD = 3; - /** UUID BSON type */ - static readonly SUBTYPE_UUID = 4; - /** MD5 BSON type */ - static readonly SUBTYPE_MD5 = 5; - /** Encrypted BSON type */ - static readonly SUBTYPE_ENCRYPTED = 6; - /** Column BSON type */ - static readonly SUBTYPE_COLUMN = 7; - /** User BSON type */ - static readonly SUBTYPE_USER_DEFINED = 128; - - buffer!: Buffer; - sub_type!: number; - position!: number; - - /** - * @param buffer - a buffer object containing the binary data. - * @param subType - the option binary type. - */ - constructor(buffer?: string | BinarySequence, subType?: number) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if ( - !(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer) - ) { - throw new BSONTypeError( - 'Binary can only be constructed from string, Buffer, TypedArray, or Array' - ); - } - - this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; - - if (buffer == null) { - // create an empty binary buffer - this.buffer = Buffer.alloc(Binary.BUFFER_SIZE); - this.position = 0; - } else { - if (typeof buffer === 'string') { - // string - this.buffer = Buffer.from(buffer, 'binary'); - } else if (Array.isArray(buffer)) { - // number[] - this.buffer = Buffer.from(buffer); - } else { - // Buffer | TypedArray | ArrayBuffer - this.buffer = ensureBuffer(buffer); - } - - this.position = this.buffer.byteLength; - } - } - - /** - * Updates this binary with byte_value. - * - * @param byteValue - a single byte we wish to write. - */ - put(byteValue: string | number | Uint8Array | Buffer | number[]): void { - // If it's a string and a has more than one character throw an error - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new BSONTypeError('only accepts single character String'); - } else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new BSONTypeError('only accepts single character Uint8Array or Array'); - - // Decode the byte value once - let decodedByte: number; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } else { - decodedByte = byteValue[0]; - } - - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decodedByte; - } else { - const buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decodedByte; - } - } - - /** - * Writes a buffer or string to the binary. - * - * @param sequence - a string or buffer to be written to the Binary BSON object. - * @param offset - specify the binary of where to write the content. - */ - write(sequence: string | BinarySequence, offset: number): void { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + sequence.length) { - const buffer = Buffer.alloc(this.buffer.length + sequence.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - - // Assign the new buffer - this.buffer = buffer; - } - - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ensureBuffer(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } else if (typeof sequence === 'string') { - this.buffer.write(sequence, offset, sequence.length, 'binary'); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - } - - /** - * Reads **length** bytes starting at **position**. - * - * @param position - read from the given position in the Binary. - * @param length - the number of bytes to read. - */ - read(position: number, length: number): BinarySequence { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - return this.buffer.slice(position, position + length); - } - - /** - * Returns the value of this binary as a string. - * @param asRaw - Will skip converting to a string - * @remarks - * This is handy when calling this function conditionally for some key value pairs and not others - */ - value(asRaw?: boolean): string | BinarySequence { - asRaw = !!asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - - // If it's a node.js buffer object - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return this.buffer.toString('binary', 0, this.position); - } - - /** the length of the binary sequence */ - length(): number { - return this.position; - } - - toJSON(): string { - return this.buffer.toString('base64'); - } - - toString(format?: string): string { - return this.buffer.toString(format); - } - - /** @internal */ - toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended { - options = options || {}; - const base64String = this.buffer.toString('base64'); - - const subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - } - - toUUID(): UUID { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID(this.buffer.slice(0, this.position)); - } - - throw new BSONError( - `Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.` - ); - } - - /** @internal */ - static fromExtendedJSON( - doc: BinaryExtendedLegacy | BinaryExtended | UUIDExtended, - options?: EJSONOptions - ): Binary { - options = options || {}; - let data: Buffer | undefined; - let type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = Buffer.from(doc.$binary, 'base64'); - } else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = Buffer.from(doc.$binary.base64, 'base64'); - } - } - } else if ('$uuid' in doc) { - type = 4; - data = uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new BSONTypeError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); - } - return new Binary(data, type); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - const asBuffer = this.value(true); - return `new Binary(Buffer.from("${asBuffer.toString('hex')}", "hex"), ${this.sub_type})`; - } -} - -Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/bson.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/bson.ts deleted file mode 100644 index 924235a..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/bson.ts +++ /dev/null @@ -1,335 +0,0 @@ -import { Buffer } from 'buffer'; -import { Binary } from './binary'; -import { Code } from './code'; -import { DBRef } from './db_ref'; -import { Decimal128 } from './decimal128'; -import { Double } from './double'; -import { ensureBuffer } from './ensure_buffer'; -import { EJSON } from './extended_json'; -import { Int32 } from './int_32'; -import { Long } from './long'; -import { Map } from './map'; -import { MaxKey } from './max_key'; -import { MinKey } from './min_key'; -import { ObjectId } from './objectid'; -import { BSONError, BSONTypeError } from './error'; -import { calculateObjectSize as internalCalculateObjectSize } from './parser/calculate_size'; -// Parts of the parser -import { deserialize as internalDeserialize, DeserializeOptions } from './parser/deserializer'; -import { serializeInto as internalSerialize, SerializeOptions } from './parser/serializer'; -import { BSONRegExp } from './regexp'; -import { BSONSymbol } from './symbol'; -import { Timestamp } from './timestamp'; -import { UUID } from './uuid'; -export { BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary'; -export { CodeExtended } from './code'; -export { - BSON_BINARY_SUBTYPE_BYTE_ARRAY, - BSON_BINARY_SUBTYPE_DEFAULT, - BSON_BINARY_SUBTYPE_FUNCTION, - BSON_BINARY_SUBTYPE_MD5, - BSON_BINARY_SUBTYPE_USER_DEFINED, - BSON_BINARY_SUBTYPE_UUID, - BSON_BINARY_SUBTYPE_UUID_NEW, - BSON_BINARY_SUBTYPE_ENCRYPTED, - BSON_BINARY_SUBTYPE_COLUMN, - BSON_DATA_ARRAY, - BSON_DATA_BINARY, - BSON_DATA_BOOLEAN, - BSON_DATA_CODE, - BSON_DATA_CODE_W_SCOPE, - BSON_DATA_DATE, - BSON_DATA_DBPOINTER, - BSON_DATA_DECIMAL128, - BSON_DATA_INT, - BSON_DATA_LONG, - BSON_DATA_MAX_KEY, - BSON_DATA_MIN_KEY, - BSON_DATA_NULL, - BSON_DATA_NUMBER, - BSON_DATA_OBJECT, - BSON_DATA_OID, - BSON_DATA_REGEXP, - BSON_DATA_STRING, - BSON_DATA_SYMBOL, - BSON_DATA_TIMESTAMP, - BSON_DATA_UNDEFINED, - BSON_INT32_MAX, - BSON_INT32_MIN, - BSON_INT64_MAX, - BSON_INT64_MIN -} from './constants'; -export { DBRefLike } from './db_ref'; -export { Decimal128Extended } from './decimal128'; -export { DoubleExtended } from './double'; -export { EJSON, EJSONOptions } from './extended_json'; -export { Int32Extended } from './int_32'; -export { LongExtended } from './long'; -export { MaxKeyExtended } from './max_key'; -export { MinKeyExtended } from './min_key'; -export { ObjectIdExtended, ObjectIdLike } from './objectid'; -export { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp'; -export { BSONSymbolExtended } from './symbol'; -export { - LongWithoutOverrides, - LongWithoutOverridesClass, - TimestampExtended, - TimestampOverrides -} from './timestamp'; -export { UUIDExtended } from './uuid'; -export { SerializeOptions, DeserializeOptions }; -export { - Code, - Map, - BSONSymbol, - DBRef, - Binary, - ObjectId, - UUID, - Long, - Timestamp, - Double, - Int32, - MinKey, - MaxKey, - BSONRegExp, - Decimal128, - // In 4.0.0 and 4.0.1, this property name was changed to ObjectId to match the class name. - // This caused interoperability problems with previous versions of the library, so in - // later builds we changed it back to ObjectID (capital D) to match legacy implementations. - ObjectId as ObjectID -}; -export { BSONError, BSONTypeError } from './error'; - -/** @public */ -export interface Document { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [key: string]: any; -} - -/** @internal */ -// Default Max Size -const MAXSIZE = 1024 * 1024 * 17; - -// Current Internal Temporary Serialization Buffer -let buffer = Buffer.alloc(MAXSIZE); - -/** - * Sets the size of the internal serialization buffer. - * - * @param size - The desired size for the internal serialization buffer - * @public - */ -export function setInternalBufferSize(size: number): void { - // Resize the internal serialization buffer if needed - if (buffer.length < size) { - buffer = Buffer.alloc(size); - } -} - -/** - * Serialize a Javascript object. - * - * @param object - the Javascript object to serialize. - * @returns Buffer object containing the serialized object. - * @public - */ -export function serialize(object: Document, options: SerializeOptions = {}): Buffer { - // Unpack the options - const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - const minInternalBufferSize = - typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = Buffer.alloc(minInternalBufferSize); - } - - // Attempt to serialize - const serializationIndex = internalSerialize( - buffer, - object, - checkKeys, - 0, - 0, - serializeFunctions, - ignoreUndefined, - [] - ); - - // Create the final buffer - const finishedBuffer = Buffer.alloc(serializationIndex); - - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - - // Return the buffer - return finishedBuffer; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, - * useful when pre-allocating the space for serialization. - * - * @param object - the Javascript object to serialize. - * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. - * @returns the index pointing to the last written byte in the buffer. - * @public - */ -export function serializeWithBufferAndIndex( - object: Document, - finalBuffer: Buffer, - options: SerializeOptions = {} -): number { - // Unpack the options - const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - const startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - const serializationIndex = internalSerialize( - buffer, - object, - checkKeys, - 0, - 0, - serializeFunctions, - ignoreUndefined - ); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - - // Return the index - return startIndex + serializationIndex - 1; -} - -/** - * Deserialize data as BSON. - * - * @param buffer - the buffer containing the serialized set of BSON documents. - * @returns returns the deserialized Javascript Object. - * @public - */ -export function deserialize( - buffer: Buffer | ArrayBufferView | ArrayBuffer, - options: DeserializeOptions = {} -): Document { - return internalDeserialize(buffer instanceof Buffer ? buffer : ensureBuffer(buffer), options); -} - -/** @public */ -export type CalculateObjectSizeOptions = Pick< - SerializeOptions, - 'serializeFunctions' | 'ignoreUndefined' ->; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param object - the Javascript object to calculate the BSON byte size for - * @returns size of BSON object in bytes - * @public - */ -export function calculateObjectSize( - object: Document, - options: CalculateObjectSizeOptions = {} -): number { - options = options || {}; - - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); -} - -/** - * Deserialize stream data as BSON documents. - * - * @param data - the buffer containing the serialized set of BSON documents. - * @param startIndex - the start index in the data Buffer where the deserialization is to start. - * @param numberOfDocuments - number of documents to deserialize. - * @param documents - an array where to store the deserialized documents. - * @param docStartIndex - the index in the documents array from where to start inserting documents. - * @param options - additional options used for the deserialization. - * @returns next index in the buffer after deserialization **x** numbers of documents. - * @public - */ -export function deserializeStream( - data: Buffer | ArrayBufferView | ArrayBuffer, - startIndex: number, - numberOfDocuments: number, - documents: Document[], - docStartIndex: number, - options: DeserializeOptions -): number { - const internalOptions = Object.assign( - { allowObjectSmallerThanBufferSize: true, index: 0 }, - options - ); - const bufferData = ensureBuffer(data); - - let index = startIndex; - // Loop over all documents - for (let i = 0; i < numberOfDocuments; i++) { - // Find size of the document - const size = - bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - // Update options with index - internalOptions.index = index; - // Parse the document at this point - documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * BSON default export - * @deprecated Please use named exports - * @privateRemarks - * We want to someday deprecate the default export, - * so none of the new TS types are being exported on the default - * @public - */ -const BSON = { - Binary, - Code, - DBRef, - Decimal128, - Double, - Int32, - Long, - UUID, - Map, - MaxKey, - MinKey, - ObjectId, - ObjectID: ObjectId, - BSONRegExp, - BSONSymbol, - Timestamp, - EJSON, - setInternalBufferSize, - serialize, - serializeWithBufferAndIndex, - deserialize, - calculateObjectSize, - deserializeStream, - BSONError, - BSONTypeError -}; -export default BSON; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/code.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/code.ts deleted file mode 100644 index 1307d88..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/code.ts +++ /dev/null @@ -1,60 +0,0 @@ -import type { Document } from './bson'; - -/** @public */ -export interface CodeExtended { - $code: string | Function; - $scope?: Document; -} - -/** - * A class representation of the BSON Code type. - * @public - */ -export class Code { - _bsontype!: 'Code'; - - code!: string | Function; - scope?: Document; - /** - * @param code - a string or function. - * @param scope - an optional scope for the function. - */ - constructor(code: string | Function, scope?: Document) { - if (!(this instanceof Code)) return new Code(code, scope); - - this.code = code; - this.scope = scope; - } - - toJSON(): { code: string | Function; scope?: Document } { - return { code: this.code, scope: this.scope }; - } - - /** @internal */ - toExtendedJSON(): CodeExtended { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - - return { $code: this.code }; - } - - /** @internal */ - static fromExtendedJSON(doc: CodeExtended): Code { - return new Code(doc.$code, doc.$scope); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - const codeJson = this.toJSON(); - return `new Code("${codeJson.code}"${ - codeJson.scope ? `, ${JSON.stringify(codeJson.scope)}` : '' - })`; - } -} - -Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/constants.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/constants.ts deleted file mode 100644 index 6af63e6..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/constants.ts +++ /dev/null @@ -1,110 +0,0 @@ -/** @internal */ -export const BSON_INT32_MAX = 0x7fffffff; -/** @internal */ -export const BSON_INT32_MIN = -0x80000000; -/** @internal */ -export const BSON_INT64_MAX = Math.pow(2, 63) - 1; -/** @internal */ -export const BSON_INT64_MIN = -Math.pow(2, 63); - -/** - * Any integer up to 2^53 can be precisely represented by a double. - * @internal - */ -export const JS_INT_MAX = Math.pow(2, 53); - -/** - * Any integer down to -2^53 can be precisely represented by a double. - * @internal - */ -export const JS_INT_MIN = -Math.pow(2, 53); - -/** Number BSON Type @internal */ -export const BSON_DATA_NUMBER = 1; - -/** String BSON Type @internal */ -export const BSON_DATA_STRING = 2; - -/** Object BSON Type @internal */ -export const BSON_DATA_OBJECT = 3; - -/** Array BSON Type @internal */ -export const BSON_DATA_ARRAY = 4; - -/** Binary BSON Type @internal */ -export const BSON_DATA_BINARY = 5; - -/** Binary BSON Type @internal */ -export const BSON_DATA_UNDEFINED = 6; - -/** ObjectId BSON Type @internal */ -export const BSON_DATA_OID = 7; - -/** Boolean BSON Type @internal */ -export const BSON_DATA_BOOLEAN = 8; - -/** Date BSON Type @internal */ -export const BSON_DATA_DATE = 9; - -/** null BSON Type @internal */ -export const BSON_DATA_NULL = 10; - -/** RegExp BSON Type @internal */ -export const BSON_DATA_REGEXP = 11; - -/** Code BSON Type @internal */ -export const BSON_DATA_DBPOINTER = 12; - -/** Code BSON Type @internal */ -export const BSON_DATA_CODE = 13; - -/** Symbol BSON Type @internal */ -export const BSON_DATA_SYMBOL = 14; - -/** Code with Scope BSON Type @internal */ -export const BSON_DATA_CODE_W_SCOPE = 15; - -/** 32 bit Integer BSON Type @internal */ -export const BSON_DATA_INT = 16; - -/** Timestamp BSON Type @internal */ -export const BSON_DATA_TIMESTAMP = 17; - -/** Long BSON Type @internal */ -export const BSON_DATA_LONG = 18; - -/** Decimal128 BSON Type @internal */ -export const BSON_DATA_DECIMAL128 = 19; - -/** MinKey BSON Type @internal */ -export const BSON_DATA_MIN_KEY = 0xff; - -/** MaxKey BSON Type @internal */ -export const BSON_DATA_MAX_KEY = 0x7f; - -/** Binary Default Type @internal */ -export const BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** Binary Function Type @internal */ -export const BSON_BINARY_SUBTYPE_FUNCTION = 1; - -/** Binary Byte Array Type @internal */ -export const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - -/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ -export const BSON_BINARY_SUBTYPE_UUID = 3; - -/** Binary UUID Type @internal */ -export const BSON_BINARY_SUBTYPE_UUID_NEW = 4; - -/** Binary MD5 Type @internal */ -export const BSON_BINARY_SUBTYPE_MD5 = 5; - -/** Encrypted BSON type @internal */ -export const BSON_BINARY_SUBTYPE_ENCRYPTED = 6; - -/** Column BSON type @internal */ -export const BSON_BINARY_SUBTYPE_COLUMN = 7; - -/** Binary User Defined Type @internal */ -export const BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/db_ref.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/db_ref.ts deleted file mode 100644 index 4097eec..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/db_ref.ts +++ /dev/null @@ -1,123 +0,0 @@ -import type { Document } from './bson'; -import type { EJSONOptions } from './extended_json'; -import type { ObjectId } from './objectid'; -import { isObjectLike } from './parser/utils'; - -/** @public */ -export interface DBRefLike { - $ref: string; - $id: ObjectId; - $db?: string; -} - -/** @internal */ -export function isDBRefLike(value: unknown): value is DBRefLike { - return ( - isObjectLike(value) && - value.$id != null && - typeof value.$ref === 'string' && - (value.$db == null || typeof value.$db === 'string') - ); -} - -/** - * A class representation of the BSON DBRef type. - * @public - */ -export class DBRef { - _bsontype!: 'DBRef'; - - collection!: string; - oid!: ObjectId; - db?: string; - fields!: Document; - - /** - * @param collection - the collection name. - * @param oid - the reference ObjectId. - * @param db - optional db name, if omitted the reference is local to the current db. - */ - constructor(collection: string, oid: ObjectId, db?: string, fields?: Document) { - if (!(this instanceof DBRef)) return new DBRef(collection, oid, db, fields); - - // check if namespace has been provided - const parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - collection = parts.shift()!; - } - - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - - // Property provided for compatibility with the 1.x parser - // the 1.x parser used a "namespace" property, while 4.x uses "collection" - - /** @internal */ - get namespace(): string { - return this.collection; - } - - set namespace(value: string) { - this.collection = value; - } - - toJSON(): DBRefLike & Document { - const o = Object.assign( - { - $ref: this.collection, - $id: this.oid - }, - this.fields - ); - - if (this.db != null) o.$db = this.db; - return o; - } - - /** @internal */ - toExtendedJSON(options?: EJSONOptions): DBRefLike { - options = options || {}; - let o: DBRefLike = { - $ref: this.collection, - $id: this.oid - }; - - if (options.legacy) { - return o; - } - - if (this.db) o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - } - - /** @internal */ - static fromExtendedJSON(doc: DBRefLike): DBRef { - const copy = Object.assign({}, doc) as Partial; - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - // NOTE: if OID is an ObjectId class it will just print the oid string. - const oid = - this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return `new DBRef("${this.namespace}", new ObjectId("${oid}")${ - this.db ? `, "${this.db}"` : '' - })`; - } -} - -Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/decimal128.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/decimal128.ts deleted file mode 100644 index 0427dad..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/decimal128.ts +++ /dev/null @@ -1,766 +0,0 @@ -import { Buffer } from 'buffer'; -import { BSONTypeError } from './error'; -import { Long } from './long'; - -const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - -const EXPONENT_MAX = 6111; -const EXPONENT_MIN = -6176; -const EXPONENT_BIAS = 6176; -const MAX_DIGITS = 34; - -// Nan value bits as 32 bit values (due to lack of longs) -const NAN_BUFFER = [ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -const INF_NEGATIVE_BUFFER = [ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); -const INF_POSITIVE_BUFFER = [ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse(); - -const EXPONENT_REGEX = /^([-+])?(\d+)?$/; - -// Extract least significant 5 bits -const COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -const EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -const COMBINATION_INFINITY = 30; -// Value of combination field for NaN -const COMBINATION_NAN = 31; - -// Detect if the value is a digit -function isDigit(value: string): boolean { - return !isNaN(parseInt(value, 10)); -} - -// Divide two uint128 values -function divideu128(value: { parts: [number, number, number, number] }) { - const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - let _rem = Long.fromNumber(0); - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (let i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; -} - -// Multiply two Long values and return the 128 bit value -function multiply64x2(left: Long, right: Long): { high: Long; low: Long } { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - const leftHigh = left.shiftRightUnsigned(32); - const leftLow = new Long(left.getLowBits(), 0); - const rightHigh = right.shiftRightUnsigned(32); - const rightLow = new Long(right.getLowBits(), 0); - - let productHigh = leftHigh.multiply(rightHigh); - let productMid = leftHigh.multiply(rightLow); - const productMid2 = leftLow.multiply(rightHigh); - let productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; -} - -function lessThan(left: Long, right: Long): boolean { - // Make values unsigned - const uhleft = left.high >>> 0; - const uhright = right.high >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - const ulleft = left.low >>> 0; - const ulright = right.low >>> 0; - if (ulleft < ulright) return true; - } - - return false; -} - -function invalidErr(string: string, message: string) { - throw new BSONTypeError(`"${string}" is not a valid Decimal128 string - ${message}`); -} - -/** @public */ -export interface Decimal128Extended { - $numberDecimal: string; -} - -/** - * A class representation of the BSON Decimal128 type. - * @public - */ -export class Decimal128 { - _bsontype!: 'Decimal128'; - - readonly bytes!: Buffer; - - /** - * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, - * or a string representation as returned by .toString() - */ - constructor(bytes: Buffer | string) { - if (!(this instanceof Decimal128)) return new Decimal128(bytes); - - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } else { - this.bytes = bytes; - } - } - - /** - * Create a Decimal128 instance from a string representation - * - * @param representation - a numeric string representation. - */ - static fromString(representation: string): Decimal128 { - // Parse state tracking - let isNegative = false; - let sawRadix = false; - let foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - let significantDigits = 0; - // Total number of significand digits read - let nDigitsRead = 0; - // Total number of digits (no leading zeros) - let nDigits = 0; - // The number of the digits after radix - let radixPosition = 0; - // The index of the first non-zero in *str* - let firstNonZero = 0; - - // Digits Array - const digits = [0]; - // The number of digits in digits - let nDigitsStored = 0; - // Insertion pointer for digits - let digitsInsert = 0; - // The index of the first non-zero digit - let firstDigit = 0; - // The index of the last digit - let lastDigit = 0; - - // Exponent - let exponent = 0; - // loop index over array - let i = 0; - // The high 17 digits of the significand - let significandHigh = new Long(0, 0); - // The low 17 digits of the significand - let significandLow = new Long(0, 0); - // The biased exponent - let biasedExponent = 0; - - // Read index - let index = 0; - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (representation.length >= 7000) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - - // Results - const stringMatch = representation.match(PARSE_STRING_REGEXP); - const infMatch = representation.match(PARSE_INF_REGEXP); - const nanMatch = representation.match(PARSE_NAN_REGEXP); - - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - } - - if (stringMatch) { - // full_match = stringMatch[0] - // sign = stringMatch[1] - - const unsignedNumber = stringMatch[2]; - // stringMatch[3] is undefined if a whole number (ex "1", 12") - // but defined if a number w/ decimal in it (ex "1.0, 12.2") - - const e = stringMatch[4]; - const expSign = stringMatch[5]; - const expNumber = stringMatch[6]; - - // they provided e, but didn't give an exponent number. for ex "1e" - if (e && expNumber === undefined) invalidErr(representation, 'missing exponent power'); - - // they provided e, but didn't give a number before it. for ex "e1" - if (e && unsignedNumber === undefined) invalidErr(representation, 'missing exponent base'); - - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - - // Get the negative or positive sign - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (representation[index] === 'N') { - return new Decimal128(Buffer.from(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) invalidErr(representation, 'contains multiple periods'); - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) nDigits = nDigits + 1; - if (sawRadix) radixPosition = radixPosition + 1; - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) - throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); - - // Read exponent if exists - if (representation[index] === 'e' || representation[index] === 'E') { - // Read exponent digits - const match = representation.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) return new Decimal128(Buffer.from(NAN_BUFFER)); - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (representation[index]) return new Decimal128(Buffer.from(NAN_BUFFER)); - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - const digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit. can only do this if < significant digits than # stored. - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - const digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits) { - let endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - // if negative, we need to increment again to account for - sign at start. - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - let roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - let dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128( - Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) - ); - } - } - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - let dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - let dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if ( - significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1)) - ) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or( - Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) - ); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - const buffer = Buffer.alloc(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); - } - - /** Create a string representation of the raw Decimal128 value */ - toString(): string { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // decoded biased exponent (14 bits) - let biased_exponent; - // the number of significand digits - let significand_digits = 0; - // the base-10 digits in the significand - const significand = new Array(36); - for (let i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - let index = 0; - - // true if the number is zero - let is_zero = false; - - // the most significant significand bits (50-46) - let significand_msb; - // temporary storage for significand decoding - let significand128: { parts: [number, number, number, number] } = { parts: [0, 0, 0, 0] }; - // indexing variables - let j, k; - - // Output string - const string: string[] = []; - - // Unpack index - index = 0; - - // Buffer reference - const buffer = this.bytes; - - // Unpack the low 64bits into a long - // bits 96 - 127 - const low = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 64 - 95 - const midl = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack the high 64bits into a long - // bits 32 - 63 - const midh = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - // bits 0 - 31 - const high = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack index - index = 0; - - // Create the state of the decimal - const dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - // bits 1 - 5 - const combination = (high >> 26) & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - - // unbiased exponent - const exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if ( - significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0 - ) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - let least_digits = 0; - // Perform the divide - const result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - // the exponent if scientific notation is used - const scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - - // if there are too many significant digits, we should just be treating numbers - // as + or - 0 and using the non-scientific exponent (this is for the "invalid - // representation should be treated as 0/-0" spec cases in decimal128-1.json) - if (significand_digits > 34) { - string.push(`${0}`); - if (exponent > 0) string.push('E+' + exponent); - else if (exponent < 0) string.push('E' + exponent); - return string.join(''); - } - - string.push(`${significand[index++]}`); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (let i = 0; i < significand_digits; i++) { - string.push(`${significand[index++]}`); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(`${scientific_exponent}`); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (let i = 0; i < significand_digits; i++) { - string.push(`${significand[index++]}`); - } - } else { - let radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (let i = 0; i < radix_position; i++) { - string.push(`${significand[index++]}`); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(`${significand[index++]}`); - } - } - } - - return string.join(''); - } - - toJSON(): Decimal128Extended { - return { $numberDecimal: this.toString() }; - } - - /** @internal */ - toExtendedJSON(): Decimal128Extended { - return { $numberDecimal: this.toString() }; - } - - /** @internal */ - static fromExtendedJSON(doc: Decimal128Extended): Decimal128 { - return Decimal128.fromString(doc.$numberDecimal); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return `new Decimal128("${this.toString()}")`; - } -} - -Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/double.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/double.ts deleted file mode 100644 index d792064..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/double.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { EJSONOptions } from './extended_json'; - -/** @public */ -export interface DoubleExtended { - $numberDouble: string; -} - -/** - * A class representation of the BSON Double type. - * @public - */ -export class Double { - _bsontype!: 'Double'; - - value!: number; - /** - * Create a Double type - * - * @param value - the number we want to represent as a double. - */ - constructor(value: number) { - if (!(this instanceof Double)) return new Double(value); - - if ((value as unknown) instanceof Number) { - value = value.valueOf(); - } - - this.value = +value; - } - - /** - * Access the number value. - * - * @returns returns the wrapped double number. - */ - valueOf(): number { - return this.value; - } - - toJSON(): number { - return this.value; - } - - toString(radix?: number): string { - return this.value.toString(radix); - } - - /** @internal */ - toExtendedJSON(options?: EJSONOptions): number | DoubleExtended { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - - // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user - // explicitly provided `-0` then we need to ensure the sign makes it into the output - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: `-${this.value.toFixed(1)}` }; - } - - let $numberDouble: string; - if (Number.isInteger(this.value)) { - $numberDouble = this.value.toFixed(1); - if ($numberDouble.length >= 13) { - $numberDouble = this.value.toExponential(13).toUpperCase(); - } - } else { - $numberDouble = this.value.toString(); - } - - return { $numberDouble }; - } - - /** @internal */ - static fromExtendedJSON(doc: DoubleExtended, options?: EJSONOptions): number | Double { - const doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - const eJSON = this.toExtendedJSON() as DoubleExtended; - return `new Double(${eJSON.$numberDouble})`; - } -} - -Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/ensure_buffer.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/ensure_buffer.ts deleted file mode 100644 index 8b82a08..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/ensure_buffer.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Buffer } from 'buffer'; -import { BSONTypeError } from './error'; -import { isAnyArrayBuffer } from './parser/utils'; - -/** - * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. - * - * @param potentialBuffer - The potential buffer - * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that - * wraps a passed in Uint8Array - * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in - */ -export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBuffer): Buffer { - if (ArrayBuffer.isView(potentialBuffer)) { - return Buffer.from( - potentialBuffer.buffer, - potentialBuffer.byteOffset, - potentialBuffer.byteLength - ); - } - - if (isAnyArrayBuffer(potentialBuffer)) { - return Buffer.from(potentialBuffer); - } - - throw new BSONTypeError('Must use either Buffer or TypedArray'); -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/error.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/error.ts deleted file mode 100644 index 8f1a417..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/error.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** @public */ -export class BSONError extends Error { - constructor(message: string) { - super(message); - Object.setPrototypeOf(this, BSONError.prototype); - } - - get name(): string { - return 'BSONError'; - } -} - -/** @public */ -export class BSONTypeError extends TypeError { - constructor(message: string) { - super(message); - Object.setPrototypeOf(this, BSONTypeError.prototype); - } - - get name(): string { - return 'BSONTypeError'; - } -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/extended_json.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/extended_json.ts deleted file mode 100644 index e904643..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/extended_json.ts +++ /dev/null @@ -1,451 +0,0 @@ -import { Binary } from './binary'; -import type { Document } from './bson'; -import { Code } from './code'; -import { DBRef, isDBRefLike } from './db_ref'; -import { Decimal128 } from './decimal128'; -import { Double } from './double'; -import { BSONError, BSONTypeError } from './error'; -import { Int32 } from './int_32'; -import { Long } from './long'; -import { MaxKey } from './max_key'; -import { MinKey } from './min_key'; -import { ObjectId } from './objectid'; -import { isDate, isObjectLike, isRegExp } from './parser/utils'; -import { BSONRegExp } from './regexp'; -import { BSONSymbol } from './symbol'; -import { Timestamp } from './timestamp'; - -/** @public */ -export type EJSONOptions = EJSON.Options; - -/** @internal */ -type BSONType = - | Binary - | Code - | DBRef - | Decimal128 - | Double - | Int32 - | Long - | MaxKey - | MinKey - | ObjectId - | BSONRegExp - | BSONSymbol - | Timestamp; - -export function isBSONType(value: unknown): value is BSONType { - return ( - isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string' - ); -} - -// INT32 boundaries -const BSON_INT32_MAX = 0x7fffffff; -const BSON_INT32_MIN = -0x80000000; -// INT64 boundaries -const BSON_INT64_MAX = 0x7fffffffffffffff; -const BSON_INT64_MIN = -0x8000000000000000; - -// all the types where we don't need to do any special processing and can just pass the EJSON -//straight to type.fromExtendedJSON -const keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp -} as const; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function deserializeValue(value: any, options: EJSON.Options = {}) { - if (typeof value === 'number') { - if (options.relaxed || options.legacy) { - return value; - } - - // if it's an integer, should interpret as smallest BSON integer - // that can represent it exactly. (if out of range, interpret as double.) - if (Math.floor(value) === value) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new Int32(value); - if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return Long.fromNumber(value); - } - - // If the number is a non-integer or out of integer range, should interpret as BSON Double. - return new Double(value); - } - - // from here on out we're looking for bson types, so bail if its not an object - if (value == null || typeof value !== 'object') return value; - - // upgrade deprecated undefined to null - if (value.$undefined) return null; - - const keys = Object.keys(value).filter( - k => k.startsWith('$') && value[k] != null - ) as (keyof typeof keysToCodecs)[]; - for (let i = 0; i < keys.length; i++) { - const c = keysToCodecs[keys[i]]; - if (c) return c.fromExtendedJSON(value, options); - } - - if (value.$date != null) { - const d = value.$date; - const date = new Date(); - - if (options.legacy) { - if (typeof d === 'number') date.setTime(d); - else if (typeof d === 'string') date.setTime(Date.parse(d)); - } else { - if (typeof d === 'string') date.setTime(Date.parse(d)); - else if (Long.isLong(d)) date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) date.setTime(d); - } - return date; - } - - if (value.$code != null) { - const copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - - return Code.fromExtendedJSON(value); - } - - if (isDBRefLike(value) || value.$dbPointer) { - const v = value.$ref ? value : value.$dbPointer; - - // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) - // because of the order JSON.parse goes through the document - if (v instanceof DBRef) return v; - - const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); - let valid = true; - dollarKeys.forEach(k => { - if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false; - }); - - // only make DBRef if $ keys are all valid - if (valid) return DBRef.fromExtendedJSON(v); - } - - return value; -} - -type EJSONSerializeOptions = EJSON.Options & { - seenObjects: { obj: unknown; propertyName: string }[]; -}; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeArray(array: any[], options: EJSONSerializeOptions): any[] { - return array.map((v: unknown, index: number) => { - options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); - try { - return serializeValue(v, options); - } finally { - options.seenObjects.pop(); - } - }); -} - -function getISOString(date: Date) { - const isoStr = date.toISOString(); - // we should only show milliseconds in timestamp if they're non-zero - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeValue(value: any, options: EJSONSerializeOptions): any { - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - const index = options.seenObjects.findIndex(entry => entry.obj === value); - if (index !== -1) { - const props = options.seenObjects.map(entry => entry.propertyName); - const leadingPart = props - .slice(0, index) - .map(prop => `${prop} -> `) - .join(''); - const alreadySeen = props[index]; - const circularPart = - ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(prop => `${prop} -> `) - .join(''); - const current = props[props.length - 1]; - const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - const dashes = '-'.repeat( - circularPart.length + (alreadySeen.length + current.length) / 2 - 1 - ); - - throw new BSONTypeError( - 'Converting circular structure to EJSON:\n' + - ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + - ` ${leadingSpace}\\${dashes}/` - ); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - - if (Array.isArray(value)) return serializeArray(value, options); - - if (value === undefined) return null; - - if (value instanceof Date || isDate(value)) { - const dateNum = value.getTime(), - // is it in year range 1970-9999? - inRange = dateNum > -1 && dateNum < 253402318800000; - - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - // it's an integer - if (Math.floor(value) === value) { - const int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, - int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; - - // interpret as being of the smallest BSON integer type that can represent the number exactly - if (int32Range) return { $numberInt: value.toString() }; - if (int64Range) return { $numberLong: value.toString() }; - } - return { $numberDouble: value.toString() }; - } - - if (value instanceof RegExp || isRegExp(value)) { - let flags = value.flags; - if (flags === undefined) { - const match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - - const rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - - if (value != null && typeof value === 'object') return serializeDocument(value, options); - return value; -} - -const BSON_TYPE_MAPPINGS = { - Binary: (o: Binary) => new Binary(o.value(), o.sub_type), - Code: (o: Code) => new Code(o.code, o.scope), - DBRef: (o: DBRef) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), // "namespace" for 1.x library backwards compat - Decimal128: (o: Decimal128) => new Decimal128(o.bytes), - Double: (o: Double) => new Double(o.value), - Int32: (o: Int32) => new Int32(o.value), - Long: ( - o: Long & { - low_: number; - high_: number; - unsigned_: boolean | undefined; - } - ) => - Long.fromBits( - // underscore variants for 1.x backwards compatibility - o.low != null ? o.low : o.low_, - o.low != null ? o.high : o.high_, - o.low != null ? o.unsigned : o.unsigned_ - ), - MaxKey: () => new MaxKey(), - MinKey: () => new MinKey(), - ObjectID: (o: ObjectId) => new ObjectId(o), - ObjectId: (o: ObjectId) => new ObjectId(o), // support 4.0.0/4.0.1 before _bsontype was reverted back to ObjectID - BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options), - Symbol: (o: BSONSymbol) => new BSONSymbol(o.value), - Timestamp: (o: Timestamp) => Timestamp.fromBits(o.low, o.high) -} as const; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function serializeDocument(doc: any, options: EJSONSerializeOptions) { - if (doc == null || typeof doc !== 'object') throw new BSONError('not an object instance'); - - const bsontype: BSONType['_bsontype'] = doc._bsontype; - if (typeof bsontype === 'undefined') { - // It's a regular object. Recursively serialize its property values. - const _doc: Document = {}; - for (const name in doc) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - _doc[name] = serializeValue(doc[name], options); - } finally { - options.seenObjects.pop(); - } - } - return _doc; - } else if (isBSONType(doc)) { - // the "document" is really just a BSON type object - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let outDoc: any = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - // There's no EJSON serialization function on the object. It's probably an - // object created by a previous version of this library (or another library) - // that's duck-typing objects to look like they were generated by this library). - // Copy the object into this library's version of that type. - const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - - // Two BSON types may have nested objects that may need to be serialized too - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new DBRef( - serializeValue(outDoc.collection, options), - serializeValue(outDoc.oid, options), - serializeValue(outDoc.db, options), - serializeValue(outDoc.fields, options) - ); - } - - return outDoc.toExtendedJSON(options); - } else { - throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } -} - -/** - * EJSON parse / stringify API - * @public - */ -// the namespace here is used to emulate `export * as EJSON from '...'` -// which as of now (sept 2020) api-extractor does not support -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace EJSON { - export interface Options { - /** Output using the Extended JSON v1 spec */ - legacy?: boolean; - /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */ - relaxed?: boolean; - /** - * Disable Extended JSON's `relaxed` mode, which attempts to return BSON types where possible, rather than native JS types - * @deprecated Please use the relaxed property instead - */ - strict?: boolean; - } - - /** - * Parse an Extended JSON string, constructing the JavaScript value or object described by that - * string. - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const text = '{ "int32": { "$numberInt": "10" } }'; - * - * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } - * console.log(EJSON.parse(text, { relaxed: false })); - * - * // prints { int32: 10 } - * console.log(EJSON.parse(text)); - * ``` - */ - export function parse(text: string, options?: EJSON.Options): SerializableTypes { - const finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); - - // relaxed implies not strict - if (typeof finalOptions.relaxed === 'boolean') finalOptions.strict = !finalOptions.relaxed; - if (typeof finalOptions.strict === 'boolean') finalOptions.relaxed = !finalOptions.strict; - - return JSON.parse(text, (key, value) => { - if (key.indexOf('\x00') !== -1) { - throw new BSONError( - `BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}` - ); - } - return deserializeValue(value, finalOptions); - }); - } - - export type JSONPrimitive = string | number | boolean | null; - export type SerializableTypes = Document | Array | JSONPrimitive; - - /** - * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer - * function is specified or optionally including only the specified properties if a replacer array - * is specified. - * - * @param value - The value to convert to extended JSON - * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string - * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. - * @param options - Optional settings - * - * @example - * ```js - * const { EJSON } = require('bson'); - * const Int32 = require('mongodb').Int32; - * const doc = { int32: new Int32(10) }; - * - * // prints '{"int32":{"$numberInt":"10"}}' - * console.log(EJSON.stringify(doc, { relaxed: false })); - * - * // prints '{"int32":10}' - * console.log(EJSON.stringify(doc)); - * ``` - */ - export function stringify( - value: SerializableTypes, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSON.Options, - space?: string | number, - options?: EJSON.Options - ): string { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - - const doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer as Parameters[1], space); - } - - /** - * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. - * - * @param value - The object to serialize - * @param options - Optional settings passed to the `stringify` function - */ - export function serialize(value: SerializableTypes, options?: EJSON.Options): Document { - options = options || {}; - return JSON.parse(stringify(value, options)); - } - - /** - * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types - * - * @param ejson - The Extended JSON object to deserialize - * @param options - Optional settings passed to the parse method - */ - export function deserialize(ejson: Document, options?: EJSON.Options): SerializableTypes { - options = options || {}; - return parse(JSON.stringify(ejson), options); - } -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/float_parser.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/float_parser.ts deleted file mode 100644 index c881f4c..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/float_parser.ts +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -type NumericalSequence = { [index: number]: number }; - -export function readIEEE754( - buffer: NumericalSequence, - offset: number, - endian: 'big' | 'little', - mLen: number, - nBytes: number -): number { - let e: number; - let m: number; - const bBE = endian === 'big'; - const eLen = nBytes * 8 - mLen - 1; - const eMax = (1 << eLen) - 1; - const eBias = eMax >> 1; - let nBits = -7; - let i = bBE ? 0 : nBytes - 1; - const d = bBE ? 1 : -1; - let 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); -} - -export function writeIEEE754( - buffer: NumericalSequence, - value: number, - offset: number, - endian: 'big' | 'little', - mLen: number, - nBytes: number -): void { - let e: number; - let m: number; - let c: number; - const bBE = endian === 'big'; - let eLen = nBytes * 8 - mLen - 1; - const eMax = (1 << eLen) - 1; - const eBias = eMax >> 1; - const rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - let i = bBE ? nBytes - 1 : 0; - const d = bBE ? -1 : 1; - const 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; - } - } - - if (isNaN(value)) m = 0; - - while (mLen >= 8) { - buffer[offset + i] = m & 0xff; - i += d; - m /= 256; - mLen -= 8; - } - - e = (e << mLen) | m; - - if (isNaN(value)) e += 8; - - eLen += mLen; - - while (eLen > 0) { - buffer[offset + i] = e & 0xff; - i += d; - e /= 256; - eLen -= 8; - } - - buffer[offset + i - d] |= s * 128; -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/int_32.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/int_32.ts deleted file mode 100644 index d64f444..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/int_32.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { EJSONOptions } from './extended_json'; - -/** @public */ -export interface Int32Extended { - $numberInt: string; -} - -/** - * A class representation of a BSON Int32 type. - * @public - */ -export class Int32 { - _bsontype!: 'Int32'; - - value!: number; - /** - * Create an Int32 type - * - * @param value - the number we want to represent as an int32. - */ - constructor(value: number | string) { - if (!(this instanceof Int32)) return new Int32(value); - - if ((value as unknown) instanceof Number) { - value = value.valueOf(); - } - - this.value = +value | 0; - } - - /** - * Access the number value. - * - * @returns returns the wrapped int32 number. - */ - valueOf(): number { - return this.value; - } - - toString(radix?: number): string { - return this.value.toString(radix); - } - - toJSON(): number { - return this.value; - } - - /** @internal */ - toExtendedJSON(options?: EJSONOptions): number | Int32Extended { - if (options && (options.relaxed || options.legacy)) return this.value; - return { $numberInt: this.value.toString() }; - } - - /** @internal */ - static fromExtendedJSON(doc: Int32Extended, options?: EJSONOptions): number | Int32 { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return `new Int32(${this.valueOf()})`; - } -} - -Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/long.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/long.ts deleted file mode 100644 index 6f79fae..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/long.ts +++ /dev/null @@ -1,1014 +0,0 @@ -import type { EJSONOptions } from './extended_json'; -import { isObjectLike } from './parser/utils'; -import type { Timestamp } from './timestamp'; - -interface LongWASMHelpers { - /** Gets the high bits of the last operation performed */ - get_high(): number; - div_u(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; - div_s(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; - rem_u(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; - rem_s(lowBits: number, highBits: number, lowBitsDivisor: number, highBitsDivisor: number): number; - mul( - lowBits: number, - highBits: number, - lowBitsMultiplier: number, - highBitsMultiplier: number - ): number; -} - -/** - * wasm optimizations, to do native i64 multiplication and divide - */ -let wasm: LongWASMHelpers | undefined = undefined; - -/* We do not want to have to include DOM types just for this check */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -declare const WebAssembly: any; - -try { - wasm = new WebAssembly.Instance( - new WebAssembly.Module( - // prettier-ignore - new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11]) - ), - {} - ).exports as unknown as LongWASMHelpers; -} catch { - // no wasm support -} - -const TWO_PWR_16_DBL = 1 << 16; -const TWO_PWR_24_DBL = 1 << 24; -const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; -const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; -const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - -/** A cache of the Long representations of small integer values. */ -const INT_CACHE: { [key: number]: Long } = {}; - -/** A cache of the Long representations of small unsigned integer values. */ -const UINT_CACHE: { [key: number]: Long } = {}; - -/** @public */ -export interface LongExtended { - $numberLong: string; -} - -/** - * A class representing a 64-bit integer - * @public - * @remarks - * The internal representation of a long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16 bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. - */ -export class Long { - _bsontype!: 'Long'; - - /** An indicator used to reliably determine if an object is a Long or not. */ - __isLong__!: true; - - /** - * The high 32 bits as a signed value. - */ - high!: number; - - /** - * The low 32 bits as a signed value. - */ - low!: number; - - /** - * Whether unsigned or not. - */ - unsigned!: boolean; - - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * - * Acceptable signatures are: - * - Long(low, high, unsigned?) - * - Long(bigint, unsigned?) - * - Long(string, unsigned?) - * - * @param low - The low (signed) 32 bits of the long - * @param high - The high (signed) 32 bits of the long - * @param unsigned - Whether unsigned or not, defaults to signed - */ - constructor(low: number | bigint | string = 0, high?: number | boolean, unsigned?: boolean) { - if (!(this instanceof Long)) return new Long(low, high, unsigned); - - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } else { - this.low = low | 0; - this.high = (high as number) | 0; - this.unsigned = !!unsigned; - } - - Object.defineProperty(this, '__isLong__', { - value: true, - configurable: false, - writable: false, - enumerable: false - }); - } - - static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); - - /** Maximum unsigned value. */ - static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); - /** Signed zero */ - static ZERO = Long.fromInt(0); - /** Unsigned zero. */ - static UZERO = Long.fromInt(0, true); - /** Signed one. */ - static ONE = Long.fromInt(1); - /** Unsigned one. */ - static UONE = Long.fromInt(1, true); - /** Signed negative one. */ - static NEG_ONE = Long.fromInt(-1); - /** Maximum signed value. */ - static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - /** Minimum signed value. */ - static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. - * Each is assumed to use 32 bits. - * @param lowBits - The low 32 bits - * @param highBits - The high 32 bits - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long { - return new Long(lowBits, highBits, unsigned); - } - - /** - * Returns a Long representing the given 32 bit integer value. - * @param value - The 32 bit integer in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromInt(value: number, unsigned?: boolean): Long { - let obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) INT_CACHE[value] = obj; - return obj; - } - } - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromNumber(value: number, unsigned?: boolean): Long { - if (isNaN(value)) return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) return Long.UZERO; - if (value >= TWO_PWR_64_DBL) return Long.MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) return Long.MAX_VALUE; - } - if (value < 0) return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - } - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @param value - The number in question - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBigInt(value: bigint, unsigned?: boolean): Long { - return Long.fromString(value.toString(), unsigned); - } - - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param str - The textual representation of the Long - * @param unsigned - Whether unsigned or not, defaults to signed - * @param radix - The radix in which the text is written (2-36), defaults to 10 - * @returns The corresponding Long value - */ - static fromString(str: string, unsigned?: boolean, radix?: number): Long { - if (str.length === 0) throw Error('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - (radix = unsigned), (unsigned = false); - } else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError('radix'); - - let p; - if ((p = str.indexOf('-')) > 0) throw Error('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - const radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - let result = Long.ZERO; - for (let i = 0; i < str.length; i += 8) { - const size = Math.min(8, str.length - i), - value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - const power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - - /** - * Creates a Long from its byte representation. - * @param bytes - Byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @param le - Whether little or big endian, defaults to big endian - * @returns The corresponding Long value - */ - static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - } - - /** - * Creates a Long from its little endian byte representation. - * @param bytes - Little endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBytesLE(bytes: number[], unsigned?: boolean): Long { - return new Long( - bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), - bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), - unsigned - ); - } - - /** - * Creates a Long from its big endian byte representation. - * @param bytes - Big endian byte representation - * @param unsigned - Whether unsigned or not, defaults to signed - * @returns The corresponding Long value - */ - static fromBytesBE(bytes: number[], unsigned?: boolean): Long { - return new Long( - (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], - (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], - unsigned - ); - } - - /** - * Tests if the specified object is a Long. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - static isLong(value: any): value is Long { - return isObjectLike(value) && value['__isLong__'] === true; - } - - /** - * Converts the specified value to a Long. - * @param unsigned - Whether unsigned or not, defaults to signed - */ - static fromValue( - val: number | string | { low: number; high: number; unsigned?: boolean }, - unsigned?: boolean - ): Long { - if (typeof val === 'number') return Long.fromNumber(val, unsigned); - if (typeof val === 'string') return Long.fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return Long.fromBits( - val.low, - val.high, - typeof unsigned === 'boolean' ? unsigned : val.unsigned - ); - } - - /** Returns the sum of this and the specified Long. */ - add(addend: string | number | Long | Timestamp): Long { - if (!Long.isLong(addend)) addend = Long.fromValue(addend); - - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - const a48 = this.high >>> 16; - const a32 = this.high & 0xffff; - const a16 = this.low >>> 16; - const a00 = this.low & 0xffff; - - const b48 = addend.high >>> 16; - const b32 = addend.high & 0xffff; - const b16 = addend.low >>> 16; - const b00 = addend.low & 0xffff; - - let c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - } - - /** - * Returns the sum of this and the specified Long. - * @returns Sum - */ - and(other: string | number | Long | Timestamp): Long { - if (!Long.isLong(other)) other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - } - - /** - * Compares this Long's value with the specified's. - * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater - */ - compare(other: string | number | Long | Timestamp): 0 | 1 | -1 { - if (!Long.isLong(other)) other = Long.fromValue(other); - if (this.eq(other)) return 0; - const thisNeg = this.isNegative(), - otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) return -1; - if (!thisNeg && otherNeg) return 1; - // At this point the sign bits are the same - if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - } - - /** This is an alias of {@link Long.compare} */ - comp(other: string | number | Long | Timestamp): 0 | 1 | -1 { - return this.compare(other); - } - - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. - * @returns Quotient - */ - divide(divisor: string | number | Long | Timestamp): Long { - if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); - if (divisor.isZero()) throw Error('division by zero'); - - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if ( - !this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1 - ) { - // be consistent with non-wasm code path - return this; - } - const low = (this.unsigned ? wasm.div_u : wasm.div_s)( - this.low, - this.high, - divisor.low, - divisor.high - ); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - - if (this.isZero()) return this.unsigned ? Long.UZERO : Long.ZERO; - let approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) return Long.MIN_VALUE; - // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(Long.MIN_VALUE)) return Long.ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - const halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(Long.MIN_VALUE)) return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) divisor = divisor.toUnsigned(); - if (divisor.gt(this)) return Long.UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return Long.UONE; - res = Long.UZERO; - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - const log2 = Math.ceil(Math.log(approx) / Math.LN2); - const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - let approxRes = Long.fromNumber(approx); - let approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) approxRes = Long.ONE; - - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - } - - /**This is an alias of {@link Long.divide} */ - div(divisor: string | number | Long | Timestamp): Long { - return this.divide(divisor); - } - - /** - * Tests if this Long's value equals the specified's. - * @param other - Other value - */ - equals(other: string | number | Long | Timestamp): boolean { - if (!Long.isLong(other)) other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - } - - /** This is an alias of {@link Long.equals} */ - eq(other: string | number | Long | Timestamp): boolean { - return this.equals(other); - } - - /** Gets the high 32 bits as a signed integer. */ - getHighBits(): number { - return this.high; - } - - /** Gets the high 32 bits as an unsigned integer. */ - getHighBitsUnsigned(): number { - return this.high >>> 0; - } - - /** Gets the low 32 bits as a signed integer. */ - getLowBits(): number { - return this.low; - } - - /** Gets the low 32 bits as an unsigned integer. */ - getLowBitsUnsigned(): number { - return this.low >>> 0; - } - - /** Gets the number of bits needed to represent the absolute value of this Long. */ - getNumBitsAbs(): number { - if (this.isNegative()) { - // Unsigned Longs are never negative - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - const val = this.high !== 0 ? this.high : this.low; - let bit: number; - for (bit = 31; bit > 0; bit--) if ((val & (1 << bit)) !== 0) break; - return this.high !== 0 ? bit + 33 : bit + 1; - } - - /** Tests if this Long's value is greater than the specified's. */ - greaterThan(other: string | number | Long | Timestamp): boolean { - return this.comp(other) > 0; - } - - /** This is an alias of {@link Long.greaterThan} */ - gt(other: string | number | Long | Timestamp): boolean { - return this.greaterThan(other); - } - - /** Tests if this Long's value is greater than or equal the specified's. */ - greaterThanOrEqual(other: string | number | Long | Timestamp): boolean { - return this.comp(other) >= 0; - } - - /** This is an alias of {@link Long.greaterThanOrEqual} */ - gte(other: string | number | Long | Timestamp): boolean { - return this.greaterThanOrEqual(other); - } - /** This is an alias of {@link Long.greaterThanOrEqual} */ - ge(other: string | number | Long | Timestamp): boolean { - return this.greaterThanOrEqual(other); - } - - /** Tests if this Long's value is even. */ - isEven(): boolean { - return (this.low & 1) === 0; - } - - /** Tests if this Long's value is negative. */ - isNegative(): boolean { - return !this.unsigned && this.high < 0; - } - - /** Tests if this Long's value is odd. */ - isOdd(): boolean { - return (this.low & 1) === 1; - } - - /** Tests if this Long's value is positive. */ - isPositive(): boolean { - return this.unsigned || this.high >= 0; - } - - /** Tests if this Long's value equals zero. */ - isZero(): boolean { - return this.high === 0 && this.low === 0; - } - - /** Tests if this Long's value is less than the specified's. */ - lessThan(other: string | number | Long | Timestamp): boolean { - return this.comp(other) < 0; - } - - /** This is an alias of {@link Long#lessThan}. */ - lt(other: string | number | Long | Timestamp): boolean { - return this.lessThan(other); - } - - /** Tests if this Long's value is less than or equal the specified's. */ - lessThanOrEqual(other: string | number | Long | Timestamp): boolean { - return this.comp(other) <= 0; - } - - /** This is an alias of {@link Long.lessThanOrEqual} */ - lte(other: string | number | Long | Timestamp): boolean { - return this.lessThanOrEqual(other); - } - - /** Returns this Long modulo the specified. */ - modulo(divisor: string | number | Long | Timestamp): Long { - if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); - - // use wasm support if present - if (wasm) { - const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)( - this.low, - this.high, - divisor.low, - divisor.high - ); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - - return this.sub(this.div(divisor).mul(divisor)); - } - - /** This is an alias of {@link Long.modulo} */ - mod(divisor: string | number | Long | Timestamp): Long { - return this.modulo(divisor); - } - /** This is an alias of {@link Long.modulo} */ - rem(divisor: string | number | Long | Timestamp): Long { - return this.modulo(divisor); - } - - /** - * Returns the product of this and the specified Long. - * @param multiplier - Multiplier - * @returns Product - */ - multiply(multiplier: string | number | Long | Timestamp): Long { - if (this.isZero()) return Long.ZERO; - if (!Long.isLong(multiplier)) multiplier = Long.fromValue(multiplier); - - // use wasm support if present - if (wasm) { - const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - - if (multiplier.isZero()) return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - - if (this.isNegative()) { - if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); - else return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); - - // If both longs are small, use float multiplication - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - const a48 = this.high >>> 16; - const a32 = this.high & 0xffff; - const a16 = this.low >>> 16; - const a00 = this.low & 0xffff; - - const b48 = multiplier.high >>> 16; - const b32 = multiplier.high & 0xffff; - const b16 = multiplier.low >>> 16; - const b00 = multiplier.low & 0xffff; - - let c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - } - - /** This is an alias of {@link Long.multiply} */ - mul(multiplier: string | number | Long | Timestamp): Long { - return this.multiply(multiplier); - } - - /** Returns the Negation of this Long's value. */ - negate(): Long { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) return Long.MIN_VALUE; - return this.not().add(Long.ONE); - } - - /** This is an alias of {@link Long.negate} */ - neg(): Long { - return this.negate(); - } - - /** Returns the bitwise NOT of this Long. */ - not(): Long { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - } - - /** Tests if this Long's value differs from the specified's. */ - notEquals(other: string | number | Long | Timestamp): boolean { - return !this.equals(other); - } - - /** This is an alias of {@link Long.notEquals} */ - neq(other: string | number | Long | Timestamp): boolean { - return this.notEquals(other); - } - /** This is an alias of {@link Long.notEquals} */ - ne(other: string | number | Long | Timestamp): boolean { - return this.notEquals(other); - } - - /** - * Returns the bitwise OR of this Long and the specified. - */ - or(other: number | string | Long): Long { - if (!Long.isLong(other)) other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - } - - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - shiftLeft(numBits: number | Long): Long { - if (Long.isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return Long.fromBits( - this.low << numBits, - (this.high << numBits) | (this.low >>> (32 - numBits)), - this.unsigned - ); - else return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - } - - /** This is an alias of {@link Long.shiftLeft} */ - shl(numBits: number | Long): Long { - return this.shiftLeft(numBits); - } - - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - shiftRight(numBits: number | Long): Long { - if (Long.isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return Long.fromBits( - (this.low >>> numBits) | (this.high << (32 - numBits)), - this.high >> numBits, - this.unsigned - ); - else return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - } - - /** This is an alias of {@link Long.shiftRight} */ - shr(numBits: number | Long): Long { - return this.shiftRight(numBits); - } - - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param numBits - Number of bits - * @returns Shifted Long - */ - shiftRightUnsigned(numBits: Long | number): Long { - if (Long.isLong(numBits)) numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) return this; - else { - const high = this.high; - if (numBits < 32) { - const low = this.low; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits, - this.unsigned - ); - } else if (numBits === 32) return Long.fromBits(high, 0, this.unsigned); - else return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - } - - /** This is an alias of {@link Long.shiftRightUnsigned} */ - shr_u(numBits: number | Long): Long { - return this.shiftRightUnsigned(numBits); - } - /** This is an alias of {@link Long.shiftRightUnsigned} */ - shru(numBits: number | Long): Long { - return this.shiftRightUnsigned(numBits); - } - - /** - * Returns the difference of this and the specified Long. - * @param subtrahend - Subtrahend - * @returns Difference - */ - subtract(subtrahend: string | number | Long | Timestamp): Long { - if (!Long.isLong(subtrahend)) subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - } - - /** This is an alias of {@link Long.subtract} */ - sub(subtrahend: string | number | Long | Timestamp): Long { - return this.subtract(subtrahend); - } - - /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ - toInt(): number { - return this.unsigned ? this.low >>> 0 : this.low; - } - - /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ - toNumber(): number { - if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - } - - /** Converts the Long to a BigInt (arbitrary precision). */ - toBigInt(): bigint { - return BigInt(this.toString()); - } - - /** - * Converts this Long to its byte representation. - * @param le - Whether little or big endian, defaults to big endian - * @returns Byte representation - */ - toBytes(le?: boolean): number[] { - return le ? this.toBytesLE() : this.toBytesBE(); - } - - /** - * Converts this Long to its little endian byte representation. - * @returns Little endian byte representation - */ - toBytesLE(): number[] { - const hi = this.high, - lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - } - - /** - * Converts this Long to its big endian byte representation. - * @returns Big endian byte representation - */ - toBytesBE(): number[] { - const hi = this.high, - lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - } - - /** - * Converts this Long to signed. - */ - toSigned(): Long { - if (!this.unsigned) return this; - return Long.fromBits(this.low, this.high, false); - } - - /** - * Converts the Long to a string written in the specified radix. - * @param radix - Radix (2-36), defaults to 10 - * @throws RangeError If `radix` is out of range - */ - toString(radix?: number): string { - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError('radix'); - if (this.isZero()) return '0'; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - const radixLong = Long.fromNumber(radix), - div = this.div(radixLong), - rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else return '-' + this.neg().toString(radix); - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - // eslint-disable-next-line @typescript-eslint/no-this-alias - let rem: Long = this; - let result = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - const remDiv = rem.div(radixToPower); - const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - let digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) digits = '0' + digits; - result = '' + digits + result; - } - } - } - - /** Converts this Long to unsigned. */ - toUnsigned(): Long { - if (this.unsigned) return this; - return Long.fromBits(this.low, this.high, true); - } - - /** Returns the bitwise XOR of this Long and the given one. */ - xor(other: Long | number | string): Long { - if (!Long.isLong(other)) other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - } - - /** This is an alias of {@link Long.isZero} */ - eqz(): boolean { - return this.isZero(); - } - - /** This is an alias of {@link Long.lessThanOrEqual} */ - le(other: string | number | Long | Timestamp): boolean { - return this.lessThanOrEqual(other); - } - - /* - **************************************************************** - * BSON SPECIFIC ADDITIONS * - **************************************************************** - */ - toExtendedJSON(options?: EJSONOptions): number | LongExtended { - if (options && options.relaxed) return this.toNumber(); - return { $numberLong: this.toString() }; - } - static fromExtendedJSON(doc: { $numberLong: string }, options?: EJSONOptions): number | Long { - const result = Long.fromString(doc.$numberLong); - return options && options.relaxed ? result.toNumber() : result; - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; - } -} - -Object.defineProperty(Long.prototype, '__isLong__', { value: true }); -Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/map.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/map.ts deleted file mode 100644 index ba00329..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/map.ts +++ /dev/null @@ -1,119 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -// We have an ES6 Map available, return the native instance - -import { getGlobal } from './utils/global'; - -/** @public */ -let bsonMap: MapConstructor; - -const bsonGlobal = getGlobal<{ Map?: MapConstructor }>(); -if (bsonGlobal.Map) { - bsonMap = bsonGlobal.Map; -} else { - // We will return a polyfill - bsonMap = class Map { - private _keys: string[]; - private _values: Record; - constructor(array: [string, any][] = []) { - this._keys = []; - this._values = {}; - - for (let i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - const entry = array[i]; - const key = entry[0]; - const value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - } - clear() { - this._keys = []; - this._values = {}; - } - delete(key: string) { - const value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - } - entries() { - let index = 0; - - return { - next: () => { - const key = this._keys[index++]; - return { - value: key !== undefined ? [key, this._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - } - forEach(callback: (this: this, value: any, key: string, self: this) => void, self?: this) { - self = self || this; - - for (let i = 0; i < this._keys.length; i++) { - const key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - } - get(key: string) { - return this._values[key] ? this._values[key].v : undefined; - } - has(key: string) { - return this._values[key] != null; - } - keys() { - let index = 0; - - return { - next: () => { - const key = this._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - } - set(key: string, value: any) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - } - values() { - let index = 0; - - return { - next: () => { - const key = this._keys[index++]; - return { - value: key !== undefined ? this._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - } - get size() { - return this._keys.length; - } - } as unknown as MapConstructor; -} - -export { bsonMap as Map }; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/max_key.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/max_key.ts deleted file mode 100644 index fcfc5be..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/max_key.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** @public */ -export interface MaxKeyExtended { - $maxKey: 1; -} - -/** - * A class representation of the BSON MaxKey type. - * @public - */ -export class MaxKey { - _bsontype!: 'MaxKey'; - - constructor() { - if (!(this instanceof MaxKey)) return new MaxKey(); - } - - /** @internal */ - toExtendedJSON(): MaxKeyExtended { - return { $maxKey: 1 }; - } - - /** @internal */ - static fromExtendedJSON(): MaxKey { - return new MaxKey(); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return 'new MaxKey()'; - } -} - -Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/min_key.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/min_key.ts deleted file mode 100644 index f1647fc..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/min_key.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** @public */ -export interface MinKeyExtended { - $minKey: 1; -} - -/** - * A class representation of the BSON MinKey type. - * @public - */ -export class MinKey { - _bsontype!: 'MinKey'; - - constructor() { - if (!(this instanceof MinKey)) return new MinKey(); - } - - /** @internal */ - toExtendedJSON(): MinKeyExtended { - return { $minKey: 1 }; - } - - /** @internal */ - static fromExtendedJSON(): MinKey { - return new MinKey(); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return 'new MinKey()'; - } -} - -Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/objectid.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/objectid.ts deleted file mode 100644 index dcd8cd6..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/objectid.ts +++ /dev/null @@ -1,369 +0,0 @@ -import { Buffer } from 'buffer'; -import { ensureBuffer } from './ensure_buffer'; -import { BSONTypeError } from './error'; -import { deprecate, isUint8Array, randomBytes } from './parser/utils'; - -// Regular expression that checks for hex value -const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - -// Unique sequence for the current process (initialized on first use) -let PROCESS_UNIQUE: Uint8Array | null = null; - -/** @public */ -export interface ObjectIdLike { - id: string | Buffer; - __id?: string; - toHexString(): string; -} - -/** @public */ -export interface ObjectIdExtended { - $oid: string; -} - -const kId = Symbol('id'); - -/** - * A class representation of the BSON ObjectId type. - * @public - */ -export class ObjectId { - _bsontype!: 'ObjectId'; - - /** @internal */ - static index = Math.floor(Math.random() * 0xffffff); - - static cacheHexString: boolean; - - /** ObjectId Bytes @internal */ - private [kId]: Buffer; - /** ObjectId hexString cache @internal */ - private __id?: string; - - /** - * Create an ObjectId type - * - * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. - */ - constructor(inputId?: string | Buffer | number | ObjectIdLike | ObjectId) { - if (!(this instanceof ObjectId)) return new ObjectId(inputId); - - // workingId is set based on type of input and whether valid id exists for the input - let workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new BSONTypeError( - 'Argument passed in must have an id that is of type string or Buffer' - ); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = Buffer.from(inputId.toHexString(), 'hex'); - } else { - workingId = inputId.id; - } - } else { - workingId = inputId; - } - - // the following cases use workingId to construct an ObjectId - if (workingId == null || typeof workingId === 'number') { - // The most common use case (blank id, new objectId instance) - // Generate a new id - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ensureBuffer(workingId); - } else if (typeof workingId === 'string') { - if (workingId.length === 12) { - const bytes = Buffer.from(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } else { - throw new BSONTypeError('Argument passed in must be a string of 12 bytes'); - } - } else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = Buffer.from(workingId, 'hex'); - } else { - throw new BSONTypeError( - 'Argument passed in must be a string of 12 bytes or a string of 24 hex characters' - ); - } - } else { - throw new BSONTypeError('Argument passed in does not match the accepted types'); - } - // If we are caching the hex string - if (ObjectId.cacheHexString) { - this.__id = this.id.toString('hex'); - } - } - - /** - * The ObjectId bytes - * @readonly - */ - get id(): Buffer { - return this[kId]; - } - - set id(value: Buffer) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = value.toString('hex'); - } - } - - /** - * The generation time of this ObjectId instance - * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch - */ - get generationTime(): number { - return this.id.readInt32BE(0); - } - - set generationTime(value: number) { - // Encode time into first 4 bytes - this.id.writeUInt32BE(value, 0); - } - - /** Returns the ObjectId id as a 24 character hex string representation */ - toHexString(): string { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - - const hexString = this.id.toString('hex'); - - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - - return hexString; - } - - /** - * Update the ObjectId index - * @privateRemarks - * Used in generating new ObjectId's on the driver - * @internal - */ - static getInc(): number { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - } - - /** - * Generate a 12 byte id buffer used in ObjectId's - * - * @param time - pass in a second based timestamp. - */ - static generate(time?: number): Buffer { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - - const inc = ObjectId.getInc(); - const buffer = Buffer.alloc(12); - - // 4-byte timestamp - buffer.writeUInt32BE(time, 0); - - // set PROCESS_UNIQUE if yet not initialized - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = randomBytes(5); - } - - // 5-byte process unique - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - - // 3-byte counter - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - - return buffer; - } - - /** - * Converts the id into a 24 character hex string for printing - * - * @param format - The Buffer toString format parameter. - */ - toString(format?: string): string { - // Is the id a buffer then use the buffer toString method to return the format - if (format) return this.id.toString(format); - return this.toHexString(); - } - - /** Converts to its JSON the 24 character hex string representation. */ - toJSON(): string { - return this.toHexString(); - } - - /** - * Compares the equality of this ObjectId with `otherID`. - * - * @param otherId - ObjectId instance to compare against. - */ - equals(otherId: string | ObjectId | ObjectIdLike): boolean { - if (otherId === undefined || otherId === null) { - return false; - } - - if (otherId instanceof ObjectId) { - return this.toString() === otherId.toString(); - } - - if ( - typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - isUint8Array(this.id) - ) { - return otherId === Buffer.prototype.toString.call(this.id, 'latin1'); - } - - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return Buffer.from(otherId).equals(this.id); - } - - if ( - typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function' - ) { - return otherId.toHexString() === this.toHexString(); - } - - return false; - } - - /** Returns the generation date (accurate up to the second) that this ID was generated. */ - getTimestamp(): Date { - const timestamp = new Date(); - const time = this.id.readUInt32BE(0); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - } - - /** @internal */ - static createPk(): ObjectId { - return new ObjectId(); - } - - /** - * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. - * - * @param time - an integer number representing a number of seconds. - */ - static createFromTime(time: number): ObjectId { - const buffer = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer.writeUInt32BE(time, 0); - // Return the new objectId - return new ObjectId(buffer); - } - - /** - * Creates an ObjectId from a hex string representation of an ObjectId. - * - * @param hexString - create a ObjectId from a passed in 24 character hexstring. - */ - static createFromHexString(hexString: string): ObjectId { - // Throw an error if it's not a valid setup - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new BSONTypeError( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - return new ObjectId(Buffer.from(hexString, 'hex')); - } - - /** - * Checks if a value is a valid bson ObjectId - * - * @param id - ObjectId instance to validate. - */ - static isValid(id: number | string | ObjectId | Uint8Array | ObjectIdLike): boolean { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - - if (id instanceof ObjectId) { - return true; - } - - if (isUint8Array(id) && id.length === 12) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { - if (typeof id.id === 'string') { - return id.id.length === 12; - } - return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); - } - - return false; - } - - /** @internal */ - toExtendedJSON(): ObjectIdExtended { - if (this.toHexString) return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - } - - /** @internal */ - static fromExtendedJSON(doc: ObjectIdExtended): ObjectId { - return new ObjectId(doc.$oid); - } - - /** - * Converts to a string representation of this Id. - * - * @returns return the 24 character hex string representation. - * @internal - */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return `new ObjectId("${this.toHexString()}")`; - } -} - -// Deprecated methods -Object.defineProperty(ObjectId.prototype, 'generate', { - value: deprecate( - (time: number) => ObjectId.generate(time), - 'Please use the static `ObjectId.generate(time)` instead' - ) -}); - -Object.defineProperty(ObjectId.prototype, 'getInc', { - value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') -}); - -Object.defineProperty(ObjectId.prototype, 'get_inc', { - value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') -}); - -Object.defineProperty(ObjectId, 'get_inc', { - value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') -}); - -Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/calculate_size.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/calculate_size.ts deleted file mode 100644 index 6a67d44..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/calculate_size.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { Buffer } from 'buffer'; -import { Binary } from '../binary'; -import type { Document } from '../bson'; -import * as constants from '../constants'; -import { isAnyArrayBuffer, isDate, isRegExp, normalizedFunctionString } from './utils'; - -export function calculateObjectSize( - object: Document, - serializeFunctions?: boolean, - ignoreUndefined?: boolean -): number { - let totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (let i = 0; i < object.length; i++) { - totalLength += calculateElement( - i.toString(), - object[i], - serializeFunctions, - true, - ignoreUndefined - ); - } - } else { - // If we have toBSON defined, override the current object - - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (const key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; -} - -/** @internal */ -function calculateElement( - name: string, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - value: any, - serializeFunctions = false, - isArray = false, - ignoreUndefined = false -) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if ( - Math.floor(value) === value && - value >= constants.JS_INT_MIN && - value <= constants.JS_INT_MAX - ) { - if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if ( - ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - isAnyArrayBuffer(value) - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength - ); - } else if ( - value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 - ); - } - } else if (value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) - ); - } - } else if (value['_bsontype'] === 'Symbol') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - Buffer.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1 - ); - } else if (value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - const ordered_values = Object.assign( - { - $ref: value.collection, - $id: value.oid - }, - value.fields - ); - - // Add db reference if it exists - if (value.db != null) { - ordered_values['$db'] = value.db; - } - - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) - ); - } else if (value instanceof RegExp || isRegExp(value)) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else if (value['_bsontype'] === 'BSONRegExp') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.pattern, 'utf8') + - 1 + - Buffer.byteLength(value.options, 'utf8') + - 1 - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1 - ); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else if (serializeFunctions) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 - ); - } - } - } - - return 0; -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/deserializer.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/deserializer.ts deleted file mode 100644 index 411731e..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/deserializer.ts +++ /dev/null @@ -1,774 +0,0 @@ -import { Buffer } from 'buffer'; -import { Binary } from '../binary'; -import type { Document } from '../bson'; -import { Code } from '../code'; -import * as constants from '../constants'; -import { DBRef, DBRefLike, isDBRefLike } from '../db_ref'; -import { Decimal128 } from '../decimal128'; -import { Double } from '../double'; -import { BSONError } from '../error'; -import { Int32 } from '../int_32'; -import { Long } from '../long'; -import { MaxKey } from '../max_key'; -import { MinKey } from '../min_key'; -import { ObjectId } from '../objectid'; -import { BSONRegExp } from '../regexp'; -import { BSONSymbol } from '../symbol'; -import { Timestamp } from '../timestamp'; -import { validateUtf8 } from '../validate_utf8'; - -/** @public */ -export interface DeserializeOptions { - /** evaluate functions in the BSON document scoped to the object deserialized. */ - evalFunctions?: boolean; - /** cache evaluated functions for reuse. */ - cacheFunctions?: boolean; - /** - * use a crc32 code for caching, otherwise use the string of the function. - * @deprecated this option to use the crc32 function never worked as intended - * due to the fact that the crc32 function itself was never implemented. - * */ - cacheFunctionsCrc32?: boolean; - /** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */ - promoteLongs?: boolean; - /** when deserializing a Binary will return it as a node.js Buffer instance. */ - promoteBuffers?: boolean; - /** when deserializing will promote BSON values to their Node.js closest equivalent types. */ - promoteValues?: boolean; - /** allow to specify if there what fields we wish to return as unserialized raw buffer. */ - fieldsAsRaw?: Document; - /** return BSON regular expressions as BSONRegExp instances. */ - bsonRegExp?: boolean; - /** allows the buffer to be larger than the parsed BSON object */ - allowObjectSmallerThanBufferSize?: boolean; - /** Offset into buffer to begin reading document from */ - index?: number; - - raw?: boolean; - /** Allows for opt-out utf-8 validation for all keys or - * specified keys. Must be all true or all false. - * - * @example - * ```js - * // disables validation on all keys - * validation: { utf8: false } - * - * // enables validation only on specified keys a, b, and c - * validation: { utf8: { a: true, b: true, c: true } } - * - * // disables validation only on specified keys a, b - * validation: { utf8: { a: false, b: false } } - * ``` - */ - validation?: { utf8: boolean | Record | Record }; -} - -// Internal long versions -const JS_INT_MAX_LONG = Long.fromNumber(constants.JS_INT_MAX); -const JS_INT_MIN_LONG = Long.fromNumber(constants.JS_INT_MIN); - -const functionCache: { [hash: string]: Function } = {}; - -export function deserialize( - buffer: Buffer, - options: DeserializeOptions, - isArray?: boolean -): Document { - options = options == null ? {} : options; - const index = options && options.index ? options.index : 0; - // Read the document size - const size = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - - if (size < 5) { - throw new BSONError(`bson size must be >= 5, is ${size}`); - } - - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); - } - - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); - } - - if (size + index > buffer.byteLength) { - throw new BSONError( - `(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})` - ); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new BSONError( - "One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00" - ); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -} - -const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; - -function deserializeObject( - buffer: Buffer, - index: number, - options: DeserializeOptions, - isArray = false -) { - const evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - const cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - - const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - const raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - const promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - const promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - const promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Ensures default validation option if none given - const validation = options.validation == null ? { utf8: true } : options.validation; - - // Shows if global utf-8 validation is enabled or disabled - let globalUTFValidation = true; - // Reflects utf-8 validation setting regardless of global or specific key validation - let validationSetting: boolean; - // Set of keys either to enable or disable validation on - const utf8KeysSet = new Set(); - - // Check for boolean uniformity and empty validation option - const utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } else { - globalUTFValidation = false; - const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - // Ensures boolean uniformity in utf-8 validation (all true or all false) - if (!utf8ValidationValues.every(item => item === validationSetting)) { - throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - - // Add keys to set that will either be validated or not based on validationSetting - if (!globalUTFValidation) { - for (const key of Object.keys(utf8ValidatedKeys)) { - utf8KeysSet.add(key); - } - } - - // Set the start index - const startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new BSONError('corrupt bson message < 5 bytes long'); - - // Read the document size - const size = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new BSONError('corrupt bson message'); - - // Create holding object - const object: Document = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - let arrayIndex = 0; - const done = false; - - let isPossibleDBRef = isArray ? false : null; - - // While we have more left data left keep parsing - while (!done) { - // Read the type - const elementType = buffer[index++]; - - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - let i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.byteLength) throw new BSONError('Bad BSON Document: illegal CString'); - - // Represents the key - const name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - // shouldValidateKey is true if the key should be validated, false otherwise - let shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } else { - shouldValidateKey = !validationSetting; - } - - if (isPossibleDBRef !== false && (name as string)[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name as string); - } - let value; - - index = i + 1; - - if (elementType === constants.BSON_DATA_STRING) { - const stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) { - throw new BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } else if (elementType === constants.BSON_DATA_OID) { - const oid = Buffer.alloc(12); - buffer.copy(oid, 0, index, index + 12); - value = new ObjectId(oid); - index = index + 12; - } else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { - value = new Int32( - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) - ); - } else if (elementType === constants.BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) { - value = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === constants.BSON_DATA_NUMBER) { - value = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === constants.BSON_DATA_DATE) { - const lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === constants.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } else if (elementType === constants.BSON_DATA_OBJECT) { - const _index = index; - const objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new BSONError('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - value = buffer.slice(index, index + objectSize); - } else { - let objectOptions = options; - if (!globalUTFValidation) { - objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - - index = index + objectSize; - } else if (elementType === constants.BSON_DATA_ARRAY) { - const _index = index; - const objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - let arrayOptions = options; - - // Stop index - const stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (const n in options) { - ( - arrayOptions as { - [key: string]: DeserializeOptions[keyof DeserializeOptions]; - } - )[n] = options[n as keyof DeserializeOptions]; - } - arrayOptions['raw'] = true; - } - if (!globalUTFValidation) { - arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new BSONError('invalid array terminator byte'); - if (index !== stopIndex) throw new BSONError('corrupted array bson'); - } else if (elementType === constants.BSON_DATA_UNDEFINED) { - value = undefined; - } else if (elementType === constants.BSON_DATA_NULL) { - value = null; - } else if (elementType === constants.BSON_DATA_LONG) { - // Unpack the low and high bits - const lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } else { - value = long; - } - } else if (elementType === constants.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - const bytes = Buffer.alloc(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - const decimal128 = new Decimal128(bytes) as Decimal128 | { toObject(): unknown }; - // If we have an alternative mapper use that - if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { - value = decimal128.toObject(); - } else { - value = decimal128; - } - } else if (elementType === constants.BSON_DATA_BINARY) { - let binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const totalBinarySize = binarySize; - const subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new BSONError('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.byteLength) - throw new BSONError('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - - if (promoteBuffers && promoteValues) { - value = buffer.slice(index, index + binarySize); - } else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - const _buffer = Buffer.alloc(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - value = _buffer; - } else { - value = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - const source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - const regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - const optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - value = new RegExp(source, optionsArray.join('')); - } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - const source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); - // Return the C string - const regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - value = new BSONRegExp(source, regExpOptions); - } else if (elementType === constants.BSON_DATA_SYMBOL) { - const stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) { - throw new BSONError('bad string length in bson'); - } - const symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new BSONSymbol(symbol); - index = index + stringSize; - } else if (elementType === constants.BSON_DATA_TIMESTAMP) { - const lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - - value = new Timestamp(lowBits, highBits); - } else if (elementType === constants.BSON_DATA_MIN_KEY) { - value = new MinKey(); - } else if (elementType === constants.BSON_DATA_MAX_KEY) { - value = new MaxKey(); - } else if (elementType === constants.BSON_DATA_CODE) { - const stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) { - throw new BSONError('bad string length in bson'); - } - const functionString = getValidatedString( - buffer, - index, - index + stringSize - 1, - shouldValidateKey - ); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } else { - value = isolateEval(functionString); - } - } else { - value = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) { - const totalSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - const stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) { - throw new BSONError('bad string length in bson'); - } - - // Javascript function - const functionString = getValidatedString( - buffer, - index, - index + stringSize - 1, - shouldValidateKey - ); - // Update parse index position - index = index + stringSize; - // Parse the element - const _index = index; - // Decode the size of the object document - const objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - const scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is too short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too short, truncating scope'); - } - - // Check if totalSize field is too long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - // Got to do this to avoid V8 deoptimizing the call due to finding eval - value = isolateEval(functionString, functionCache, object); - } else { - value = isolateEval(functionString); - } - - value.scope = scopeObject; - } else { - value = new Code(functionString, scopeObject); - } - } else if (elementType === constants.BSON_DATA_DBPOINTER) { - // Get the code string size - const stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new BSONError('bad string length in bson'); - // Namespace - if (validation != null && validation.utf8) { - if (!validateUtf8(buffer, index, index + stringSize - 1)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - } - const namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - const oidBuffer = Buffer.alloc(12); - buffer.copy(oidBuffer, 0, index, index + 12); - const oid = new ObjectId(oidBuffer); - - // Update the index - index = index + 12; - - // Upgrade to DBRef type - value = new DBRef(namespace, oid); - } else { - throw new BSONError( - 'Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"' - ); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } else { - object[name] = value; - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new BSONError('corrupt array bson'); - throw new BSONError('corrupt object bson'); - } - - // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef - if (!isPossibleDBRef) return object; - - if (isDBRefLike(object)) { - const copy = Object.assign({}, object) as Partial; - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object.$ref, object.$id, object.$db, copy); - } - - return object; -} - -/** - * Ensure eval is isolated, store the result in functionCache. - * - * @internal - */ -function isolateEval( - functionString: string, - functionCache?: { [hash: string]: Function }, - object?: Document -) { - if (!functionCache) return new Function(functionString); - // Check for cache hit, eval if missing and return cached function - if (functionCache[functionString] == null) { - functionCache[functionString] = new Function(functionString); - } - - // Set the object - return functionCache[functionString].bind(object); -} - -function getValidatedString( - buffer: Buffer, - start: number, - end: number, - shouldValidateUtf8: boolean -) { - const value = buffer.toString('utf8', start, end); - // if utf8 validation is on, do the check - if (shouldValidateUtf8) { - for (let i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validateUtf8(buffer, start, end)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/serializer.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/serializer.ts deleted file mode 100644 index db9e015..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/serializer.ts +++ /dev/null @@ -1,1071 +0,0 @@ -import type { Buffer } from 'buffer'; -import { Binary } from '../binary'; -import type { BSONSymbol, DBRef, Document, MaxKey } from '../bson'; -import type { Code } from '../code'; -import * as constants from '../constants'; -import type { DBRefLike } from '../db_ref'; -import type { Decimal128 } from '../decimal128'; -import type { Double } from '../double'; -import { ensureBuffer } from '../ensure_buffer'; -import { BSONError, BSONTypeError } from '../error'; -import { isBSONType } from '../extended_json'; -import { writeIEEE754 } from '../float_parser'; -import type { Int32 } from '../int_32'; -import { Long } from '../long'; -import { Map } from '../map'; -import type { MinKey } from '../min_key'; -import type { ObjectId } from '../objectid'; -import type { BSONRegExp } from '../regexp'; -import { - isBigInt64Array, - isBigUInt64Array, - isDate, - isMap, - isRegExp, - isUint8Array, - normalizedFunctionString -} from './utils'; - -/** @public */ -export interface SerializeOptions { - /** the serializer will check if keys are valid. */ - checkKeys?: boolean; - /** serialize the javascript functions **(default:false)**. */ - serializeFunctions?: boolean; - /** serialize will not emit undefined fields **(default:true)** */ - ignoreUndefined?: boolean; - /** @internal Resize internal buffer */ - minInternalBufferSize?: number; - /** the index in the buffer where we wish to start serializing into */ - index?: number; -} - -const regexp = /\x00/; // eslint-disable-line no-control-regex -const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); - -/* - * isArray indicates if we are writing to a BSON array (type 0x04) - * which forces the "key" which really an array index as a string to be written as ascii - * This will catch any errors in index as a string generation - */ - -function serializeString( - buffer: Buffer, - key: string, - value: string, - index: number, - isArray?: boolean -) { - // Encode String type - buffer[index++] = constants.BSON_DATA_STRING; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - const size = buffer.write(value, index + 4, undefined, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -} - -function serializeNumber( - buffer: Buffer, - key: string, - value: number, - index: number, - isArray?: boolean -) { - // We have an integer value - // TODO(NODE-2529): Add support for big int - if ( - Number.isInteger(value) && - value >= constants.BSON_INT32_MIN && - value <= constants.BSON_INT32_MAX - ) { - // If the value fits in 32 bits encode as int32 - // Set int type 32 bits or less - buffer[index++] = constants.BSON_DATA_INT; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else { - // Encode as double - buffer[index++] = constants.BSON_DATA_NUMBER; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Adjust index - index = index + 8; - } - - return index; -} - -function serializeNull(buffer: Buffer, key: string, _: unknown, index: number, isArray?: boolean) { - // Set long type - buffer[index++] = constants.BSON_DATA_NULL; - - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -function serializeBoolean( - buffer: Buffer, - key: string, - value: boolean, - index: number, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_BOOLEAN; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} - -function serializeDate(buffer: Buffer, key: string, value: Date, index: number, isArray?: boolean) { - // Write the type - buffer[index++] = constants.BSON_DATA_DATE; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - const dateInMilis = Long.fromNumber(value.getTime()); - const lowBits = dateInMilis.getLowBits(); - const highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -function serializeRegExp( - buffer: Buffer, - key: string, - value: RegExp, - index: number, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_REGEXP; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.global) buffer[index++] = 0x73; // s - if (value.multiline) buffer[index++] = 0x6d; // m - - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -function serializeBSONRegExp( - buffer: Buffer, - key: string, - value: BSONRegExp, - index: number, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_REGEXP; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, undefined, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -function serializeMinMax( - buffer: Buffer, - key: string, - value: MinKey | MaxKey, - index: number, - isArray?: boolean -) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = constants.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = constants.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = constants.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -function serializeObjectId( - buffer: Buffer, - key: string, - value: ObjectId, - index: number, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_OID; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, undefined, 'binary'); - } else if (isUint8Array(value.id)) { - // Use the standard JS methods here because buffer.copy() is buggy with the - // browser polyfill - buffer.set(value.id.subarray(0, 12), index); - } else { - throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Adjust index - return index + 12; -} - -function serializeBuffer( - buffer: Buffer, - key: string, - value: Buffer | Uint8Array, - index: number, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_BINARY; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - const size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - buffer.set(ensureBuffer(value), index); - // Adjust the index - index = index + size; - return index; -} - -function serializeObject( - buffer: Buffer, - key: string, - value: Document, - index: number, - checkKeys = false, - depth = 0, - serializeFunctions = false, - ignoreUndefined = true, - isArray = false, - path: Document[] = [] -) { - for (let i = 0; i < path.length; i++) { - if (path[i] === value) throw new BSONError('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const endIndex = serializeInto( - buffer, - value, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined, - path - ); - // Pop stack - path.pop(); - return endIndex; -} - -function serializeDecimal128( - buffer: Buffer, - key: string, - value: Decimal128, - index: number, - isArray?: boolean -) { - buffer[index++] = constants.BSON_DATA_DECIMAL128; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - // Prefer the standard JS methods because their typechecking is not buggy, - // unlike the `buffer` polyfill's. - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; -} - -function serializeLong(buffer: Buffer, key: string, value: Long, index: number, isArray?: boolean) { - // Write the type - buffer[index++] = - value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - const lowBits = value.getLowBits(); - const highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -function serializeInt32( - buffer: Buffer, - key: string, - value: Int32 | number, - index: number, - isArray?: boolean -) { - value = value.valueOf(); - // Set int type 32 bits or less - buffer[index++] = constants.BSON_DATA_INT; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -} - -function serializeDouble( - buffer: Buffer, - key: string, - value: Double, - index: number, - isArray?: boolean -) { - // Encode as double - buffer[index++] = constants.BSON_DATA_NUMBER; - - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write float - writeIEEE754(buffer, value.value, index, 'little', 52, 8); - - // Adjust index - index = index + 8; - return index; -} - -function serializeFunction( - buffer: Buffer, - key: string, - value: Function, - index: number, - _checkKeys = false, - _depth = 0, - isArray?: boolean -) { - buffer[index++] = constants.BSON_DATA_CODE; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - const functionString = normalizedFunctionString(value); - - // Write the string - const size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} - -function serializeCode( - buffer: Buffer, - key: string, - value: Code, - index: number, - checkKeys = false, - depth = 0, - serializeFunctions = false, - ignoreUndefined = true, - isArray = false -) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - let startIndex = index; - - // Serialize the function - // Get the function string - const functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - const codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - const endIndex = serializeInto( - buffer, - value.scope, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined - ); - index = endIndex - 1; - - // Writ the total - const totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = constants.BSON_DATA_CODE; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - const functionString = value.code.toString(); - // Write the string - const size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -} - -function serializeBinary( - buffer: Buffer, - key: string, - value: Binary, - index: number, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_BINARY; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - const data = value.value(true) as Buffer | Uint8Array; - // Calculate size - let size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - buffer.set(data, index); - // Adjust the index - index = index + value.position; - return index; -} - -function serializeSymbol( - buffer: Buffer, - key: string, - value: BSONSymbol, - index: number, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_SYMBOL; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - const size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} - -function serializeDBRef( - buffer: Buffer, - key: string, - value: DBRef, - index: number, - depth: number, - serializeFunctions: boolean, - isArray?: boolean -) { - // Write the type - buffer[index++] = constants.BSON_DATA_OBJECT; - // Number of written bytes - const numberOfWrittenBytes = !isArray - ? buffer.write(key, index, undefined, 'utf8') - : buffer.write(key, index, undefined, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - let startIndex = index; - let output: DBRefLike = { - $ref: value.collection || value.namespace, // "namespace" was what library 1.x called "collection" - $id: value.oid - }; - - if (value.db != null) { - output.$db = value.db; - } - - output = Object.assign(output, value.fields); - const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); - - // Calculate object size - const size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} - -export function serializeInto( - buffer: Buffer, - object: Document, - checkKeys = false, - startingIndex = 0, - depth = 0, - serializeFunctions = false, - ignoreUndefined = true, - path: Document[] = [] -): number { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - let index = startingIndex + 4; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (let i = 0; i < object.length; i++) { - const key = '' + i; - let value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (typeof value === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (typeof value === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true, - path - ); - } else if ( - typeof value === 'object' && - isBSONType(value) && - value._bsontype === 'Decimal128' - ) { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true - ); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else if (object instanceof Map || isMap(object)) { - const iterator = object.entries(); - let done = false; - - while (!done) { - // Unpack the next entry - const entry = iterator.next(); - done = !!entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - const key = entry.value[0]; - const value = entry.value[1]; - - // Check the type of the value - const type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new BSONTypeError('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new BSONTypeError('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (const key in object) { - let value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new BSONTypeError('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - const type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'bigint') { - throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - const size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/utils.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/utils.ts deleted file mode 100644 index 2cd128a..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/parser/utils.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { Buffer } from 'buffer'; -import { getGlobal } from '../utils/global'; - -type RandomBytesFunction = (size: number) => Uint8Array; - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param fn - The function to stringify - */ -export function normalizedFunctionString(fn: Function): string { - return fn.toString().replace('function(', 'function ('); -} - -function isReactNative() { - const g = getGlobal<{ navigator?: { product?: string } }>(); - return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; -} - -const insecureRandomBytes: RandomBytesFunction = function insecureRandomBytes(size: number) { - const insecureWarning = isReactNative() - ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' - : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; - console.warn(insecureWarning); - - const result = Buffer.alloc(size); - for (let i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256); - return result; -}; - -/* We do not want to have to include DOM types just for this check */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -declare let window: any; -declare let require: Function; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -declare let global: any; -declare const self: unknown; - -const detectRandomBytes = (): RandomBytesFunction => { - if (typeof window !== 'undefined') { - // browser crypto implementation(s) - const target = window.crypto || window.msCrypto; // allow for IE11 - if (target && target.getRandomValues) { - return size => target.getRandomValues(Buffer.alloc(size)); - } - } - - if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { - // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global - return size => global.crypto.getRandomValues(Buffer.alloc(size)); - } - - let requiredRandomBytes: RandomBytesFunction | null | undefined; - try { - // eslint-disable-next-line @typescript-eslint/no-var-requires - requiredRandomBytes = require('crypto').randomBytes; - } catch (e) { - // keep the fallback - } - - // NOTE: in transpiled cases the above require might return null/undefined - - return requiredRandomBytes || insecureRandomBytes; -}; - -export const randomBytes = detectRandomBytes(); - -export function isAnyArrayBuffer(value: unknown): value is ArrayBuffer { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes( - Object.prototype.toString.call(value) - ); -} - -export function isUint8Array(value: unknown): value is Uint8Array { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; -} - -export function isBigInt64Array(value: unknown): value is BigInt64Array { - return Object.prototype.toString.call(value) === '[object BigInt64Array]'; -} - -export function isBigUInt64Array(value: unknown): value is BigUint64Array { - return Object.prototype.toString.call(value) === '[object BigUint64Array]'; -} - -export function isRegExp(d: unknown): d is RegExp { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} - -export function isMap(d: unknown): d is Map { - return Object.prototype.toString.call(d) === '[object Map]'; -} - -/** Call to check if your environment has `Buffer` */ -export function haveBuffer(): boolean { - return typeof global !== 'undefined' && typeof global.Buffer !== 'undefined'; -} - -// To ensure that 0.4 of node works correctly -export function isDate(d: unknown): d is Date { - return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * @internal - * this is to solve the `'someKey' in x` problem where x is unknown. - * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 - */ -export function isObjectLike(candidate: unknown): candidate is Record { - return typeof candidate === 'object' && candidate !== null; -} - -declare let console: { warn(...message: unknown[]): void }; -export function deprecate(fn: T, message: string): T { - let warned = false; - function deprecated(this: unknown, ...args: unknown[]) { - if (!warned) { - console.warn(message); - warned = true; - } - return fn.apply(this, args); - } - return deprecated as unknown as T; -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/regexp.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/regexp.ts deleted file mode 100644 index 7151bec..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/regexp.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { BSONError, BSONTypeError } from './error'; -import type { EJSONOptions } from './extended_json'; - -function alphabetize(str: string): string { - return str.split('').sort().join(''); -} - -/** @public */ -export interface BSONRegExpExtendedLegacy { - $regex: string | BSONRegExp; - $options: string; -} - -/** @public */ -export interface BSONRegExpExtended { - $regularExpression: { - pattern: string; - options: string; - }; -} - -/** - * A class representation of the BSON RegExp type. - * @public - */ -export class BSONRegExp { - _bsontype!: 'BSONRegExp'; - - pattern!: string; - options!: string; - /** - * @param pattern - The regular expression pattern to match - * @param options - The regular expression options - */ - constructor(pattern: string, options?: string) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(pattern, options); - - this.pattern = pattern; - this.options = alphabetize(options ?? ''); - - if (this.pattern.indexOf('\x00') !== -1) { - throw new BSONError( - `BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}` - ); - } - if (this.options.indexOf('\x00') !== -1) { - throw new BSONError( - `BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}` - ); - } - - // Validate options - for (let i = 0; i < this.options.length; i++) { - if ( - !( - this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u' - ) - ) { - throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); - } - } - } - - static parseOptions(options?: string): string { - return options ? options.split('').sort().join('') : ''; - } - - /** @internal */ - toExtendedJSON(options?: EJSONOptions): BSONRegExpExtendedLegacy | BSONRegExpExtended { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - } - - /** @internal */ - static fromExtendedJSON(doc: BSONRegExpExtendedLegacy | BSONRegExpExtended): BSONRegExp { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - // This is for $regex query operators that have extended json values. - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc as unknown as BSONRegExp; - } - } else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp( - doc.$regularExpression.pattern, - BSONRegExp.parseOptions(doc.$regularExpression.options) - ); - } - throw new BSONTypeError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); - } -} - -Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/symbol.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/symbol.ts deleted file mode 100644 index 10601b0..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/symbol.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** @public */ -export interface BSONSymbolExtended { - $symbol: string; -} - -/** - * A class representation of the BSON Symbol type. - * @public - */ -export class BSONSymbol { - _bsontype!: 'Symbol'; - - value!: string; - /** - * @param value - the string representing the symbol. - */ - constructor(value: string) { - if (!(this instanceof BSONSymbol)) return new BSONSymbol(value); - - this.value = value; - } - - /** Access the wrapped string value. */ - valueOf(): string { - return this.value; - } - - toString(): string { - return this.value; - } - - /** @internal */ - inspect(): string { - return `new BSONSymbol("${this.value}")`; - } - - toJSON(): string { - return this.value; - } - - /** @internal */ - toExtendedJSON(): BSONSymbolExtended { - return { $symbol: this.value }; - } - - /** @internal */ - static fromExtendedJSON(doc: BSONSymbolExtended): BSONSymbol { - return new BSONSymbol(doc.$symbol); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } -} - -Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/timestamp.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/timestamp.ts deleted file mode 100644 index e6eb470..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/timestamp.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { Long } from './long'; -import { isObjectLike } from './parser/utils'; - -/** @public */ -export type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; -/** @public */ -export type LongWithoutOverrides = new (low: unknown, high?: number, unsigned?: boolean) => { - [P in Exclude]: Long[P]; -}; -/** @public */ -export const LongWithoutOverridesClass: LongWithoutOverrides = - Long as unknown as LongWithoutOverrides; - -/** @public */ -export interface TimestampExtended { - $timestamp: { - t: number; - i: number; - }; -} - -/** @public */ -export class Timestamp extends LongWithoutOverridesClass { - _bsontype!: 'Timestamp'; - - static readonly MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - - /** - * @param low - A 64-bit Long representing the Timestamp. - */ - constructor(long: Long); - /** - * @param value - A pair of two values indicating timestamp and increment. - */ - constructor(value: { t: number; i: number }); - /** - * @param low - the low (signed) 32 bits of the Timestamp. - * @param high - the high (signed) 32 bits of the Timestamp. - * @deprecated Please use `Timestamp({ t: high, i: low })` or `Timestamp(Long(low, high))` instead. - */ - constructor(low: number, high: number); - constructor(low: number | Long | { t: number; i: number }, high?: number) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - ///@ts-expect-error - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - - if (Long.isLong(low)) { - super(low.low, low.high, true); - } else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { - super(low.i, low.t, true); - } else { - super(low, high, true); - } - Object.defineProperty(this, '_bsontype', { - value: 'Timestamp', - writable: false, - configurable: false, - enumerable: false - }); - } - - toJSON(): { $timestamp: string } { - return { - $timestamp: this.toString() - }; - } - - /** Returns a Timestamp represented by the given (32-bit) integer value. */ - static fromInt(value: number): Timestamp { - return new Timestamp(Long.fromInt(value, true)); - } - - /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ - static fromNumber(value: number): Timestamp { - return new Timestamp(Long.fromNumber(value, true)); - } - - /** - * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. - * - * @param lowBits - the low 32-bits. - * @param highBits - the high 32-bits. - */ - static fromBits(lowBits: number, highBits: number): Timestamp { - return new Timestamp(lowBits, highBits); - } - - /** - * Returns a Timestamp from the given string, optionally using the given radix. - * - * @param str - the textual representation of the Timestamp. - * @param optRadix - the radix in which the text is written. - */ - static fromString(str: string, optRadix: number): Timestamp { - return new Timestamp(Long.fromString(str, true, optRadix)); - } - - /** @internal */ - toExtendedJSON(): TimestampExtended { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - } - - /** @internal */ - static fromExtendedJSON(doc: TimestampExtended): Timestamp { - return new Timestamp(doc.$timestamp); - } - - /** @internal */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; - } -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/utils/global.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/utils/global.ts deleted file mode 100644 index 8b18e85..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/utils/global.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* We do not want to have to include DOM types just for this check */ -declare const window: unknown; -declare const self: unknown; -declare const global: unknown; - -function checkForMath(potentialGlobal: any) { - // eslint-disable-next-line eqeqeq - return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; -} - -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -export function getGlobal>(): T { - // eslint-disable-next-line no-undef - return ( - checkForMath(typeof globalThis === 'object' && globalThis) || - checkForMath(typeof window === 'object' && window) || - checkForMath(typeof self === 'object' && self) || - checkForMath(typeof global === 'object' && global) || - Function('return this')() - ); -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/uuid.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/uuid.ts deleted file mode 100644 index 596baf3..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/uuid.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { Buffer } from 'buffer'; -import { ensureBuffer } from './ensure_buffer'; -import { Binary } from './binary'; -import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils'; -import { isUint8Array, randomBytes } from './parser/utils'; -import { BSONTypeError } from './error'; - -/** @public */ -export type UUIDExtended = { - $uuid: string; -}; - -const BYTE_LENGTH = 16; - -const kId = Symbol('id'); - -/** - * A class representation of the BSON UUID type. - * @public - */ -export class UUID { - // This property is not meant for direct serialization, but simply an indication that this type originates from this package. - _bsontype!: 'UUID'; - - static cacheHexString: boolean; - - /** UUID Bytes @internal */ - private [kId]: Buffer; - /** UUID hexString cache @internal */ - private __id?: string; - - /** - * Create an UUID type - * - * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. - */ - constructor(input?: string | Buffer | UUID) { - if (typeof input === 'undefined') { - // The most common use case (blank id, new UUID() instance) - this.id = UUID.generate(); - } else if (input instanceof UUID) { - this[kId] = Buffer.from(input.id); - this.__id = input.__id; - } else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { - this.id = ensureBuffer(input); - } else if (typeof input === 'string') { - this.id = uuidHexStringToBuffer(input); - } else { - throw new BSONTypeError( - 'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).' - ); - } - } - - /** - * The UUID bytes - * @readonly - */ - get id(): Buffer { - return this[kId]; - } - - set id(value: Buffer) { - this[kId] = value; - - if (UUID.cacheHexString) { - this.__id = bufferToUuidHexString(value); - } - } - - /** - * Generate a 16 byte uuid v4 buffer used in UUIDs - */ - - /** - * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) - * @param includeDashes - should the string exclude dash-separators. - * */ - toHexString(includeDashes = true): string { - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - - const uuidHexString = bufferToUuidHexString(this.id, includeDashes); - - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - - return uuidHexString; - } - - /** - * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. - */ - toString(encoding?: string): string { - return encoding ? this.id.toString(encoding) : this.toHexString(); - } - - /** - * Converts the id into its JSON string representation. - * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - */ - toJSON(): string { - return this.toHexString(); - } - - /** - * Compares the equality of this UUID with `otherID`. - * - * @param otherId - UUID instance to compare against. - */ - equals(otherId: string | Buffer | UUID): boolean { - if (!otherId) { - return false; - } - - if (otherId instanceof UUID) { - return otherId.id.equals(this.id); - } - - try { - return new UUID(otherId).id.equals(this.id); - } catch { - return false; - } - } - - /** - * Creates a Binary instance from the current UUID. - */ - toBinary(): Binary { - return new Binary(this.id, Binary.SUBTYPE_UUID); - } - - /** - * Generates a populated buffer containing a v4 uuid - */ - static generate(): Buffer { - const bytes = randomBytes(BYTE_LENGTH); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - - return Buffer.from(bytes); - } - - /** - * Checks if a value is a valid bson UUID - * @param input - UUID, string or Buffer to validate. - */ - static isValid(input: string | Buffer | UUID): boolean { - if (!input) { - return false; - } - - if (input instanceof UUID) { - return true; - } - - if (typeof input === 'string') { - return uuidValidateString(input); - } - - if (isUint8Array(input)) { - // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) - if (input.length !== BYTE_LENGTH) { - return false; - } - - try { - // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx - // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx - return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; - } catch { - return false; - } - } - - return false; - } - - /** - * Creates an UUID from a hex string representation of an UUID. - * @param hexString - 32 or 36 character hex string (dashes excluded/included). - */ - static createFromHexString(hexString: string): UUID { - const buffer = uuidHexStringToBuffer(hexString); - return new UUID(buffer); - } - - /** - * Converts to a string representation of this Id. - * - * @returns return the 36 character hex string representation. - * @internal - */ - [Symbol.for('nodejs.util.inspect.custom')](): string { - return this.inspect(); - } - - inspect(): string { - return `new UUID("${this.toHexString()}")`; - } -} - -Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/uuid_utils.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/uuid_utils.ts deleted file mode 100644 index f37b065..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/uuid_utils.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Buffer } from 'buffer'; -import { BSONTypeError } from './error'; - -// Validation regex for v4 uuid (validates with or without dashes) -const VALIDATION_REGEX = - /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; - -export const uuidValidateString = (str: string): boolean => - typeof str === 'string' && VALIDATION_REGEX.test(str); - -export const uuidHexStringToBuffer = (hexString: string): Buffer => { - if (!uuidValidateString(hexString)) { - throw new BSONTypeError( - 'UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".' - ); - } - - const sanitizedHexString = hexString.replace(/-/g, ''); - return Buffer.from(sanitizedHexString, 'hex'); -}; - -export const bufferToUuidHexString = (buffer: Buffer, includeDashes = true): string => - includeDashes - ? buffer.toString('hex', 0, 4) + - '-' + - buffer.toString('hex', 4, 6) + - '-' + - buffer.toString('hex', 6, 8) + - '-' + - buffer.toString('hex', 8, 10) + - '-' + - buffer.toString('hex', 10, 16) - : buffer.toString('hex'); diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/validate_utf8.ts b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/validate_utf8.ts deleted file mode 100644 index e1da934..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/bson/src/validate_utf8.ts +++ /dev/null @@ -1,47 +0,0 @@ -const FIRST_BIT = 0x80; -const FIRST_TWO_BITS = 0xc0; -const FIRST_THREE_BITS = 0xe0; -const FIRST_FOUR_BITS = 0xf0; -const FIRST_FIVE_BITS = 0xf8; - -const TWO_BIT_CHAR = 0xc0; -const THREE_BIT_CHAR = 0xe0; -const FOUR_BIT_CHAR = 0xf0; -const CONTINUING_CHAR = 0x80; - -/** - * Determines if the passed in bytes are valid utf8 - * @param bytes - An array of 8-bit bytes. Must be indexable and have length property - * @param start - The index to start validating - * @param end - The index to end validating - */ -export function validateUtf8( - bytes: { [index: number]: number }, - start: number, - end: number -): boolean { - let continuation = 0; - - for (let i = start; i < end; i += 1) { - const byte = bytes[i]; - - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } else { - return false; - } - } - } - - return !continuation; -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/LICENSE b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/LICENSE deleted file mode 100644 index 658c933..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software -and associated documentation files (the 'Software'), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial -portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/README.md b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/README.md deleted file mode 100644 index 88dae35..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/README.md +++ /dev/null @@ -1,455 +0,0 @@ -# debug -[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) -[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) - - - -A tiny JavaScript debugging utility modelled after Node.js core's debugging -technique. Works in Node.js and web browsers. - -## Installation - -```bash -$ npm install debug -``` - -## Usage - -`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. - -Example [_app.js_](./examples/node/app.js): - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %o', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example [_worker.js_](./examples/node/worker.js): - -```js -var a = require('debug')('worker:a') - , b = require('debug')('worker:b'); - -function work() { - a('doing lots of uninteresting work'); - setTimeout(work, Math.random() * 1000); -} - -work(); - -function workb() { - b('doing some work'); - setTimeout(workb, Math.random() * 2000); -} - -workb(); -``` - -The `DEBUG` environment variable is then used to enable these based on space or -comma-delimited names. - -Here are some examples: - -screen shot 2017-08-08 at 12 53 04 pm -screen shot 2017-08-08 at 12 53 38 pm -screen shot 2017-08-08 at 12 53 25 pm - -#### Windows command prompt notes - -##### CMD - -On Windows the environment variable is set using the `set` command. - -```cmd -set DEBUG=*,-not_this -``` - -Example: - -```cmd -set DEBUG=* & node app.js -``` - -##### PowerShell (VS Code default) - -PowerShell uses different syntax to set environment variables. - -```cmd -$env:DEBUG = "*,-not_this" -``` - -Example: - -```cmd -$env:DEBUG='app';node app.js -``` - -Then, run the program to be debugged as usual. - -npm script example: -```js - "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", -``` - -## Namespace Colors - -Every debug instance has a color generated for it based on its namespace name. -This helps when visually parsing the debug output to identify which debug instance -a debug line belongs to. - -#### Node.js - -In Node.js, colors are enabled when stderr is a TTY. You also _should_ install -the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, -otherwise debug will only use a small handful of basic colors. - - - -#### Web Browser - -Colors are also enabled on "Web Inspectors" that understand the `%c` formatting -option. These are WebKit web inspectors, Firefox ([since version -31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) -and the Firebug plugin for Firefox (any version). - - - - -## Millisecond diff - -When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - - -When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: - - - - -## Conventions - -If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. - -## Wildcards - -The `*` character may be used as a wildcard. Suppose for example your library has -debuggers named "connect:bodyParser", "connect:compress", "connect:session", -instead of listing all three with -`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do -`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - -You can also exclude specific debuggers by prefixing them with a "-" character. -For example, `DEBUG=*,-connect:*` would include all debuggers except those -starting with "connect:". - -## Environment Variables - -When running through Node.js, you can set a few environment variables that will -change the behavior of the debug logging: - -| Name | Purpose | -|-----------|-------------------------------------------------| -| `DEBUG` | Enables/disables specific debugging namespaces. | -| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | -| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | -| `DEBUG_DEPTH` | Object inspection depth. | -| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | - - -__Note:__ The environment variables beginning with `DEBUG_` end up being -converted into an Options object that gets used with `%o`/`%O` formatters. -See the Node.js documentation for -[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) -for the complete list. - -## Formatters - -Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. -Below are the officially supported formatters: - -| Formatter | Representation | -|-----------|----------------| -| `%O` | Pretty-print an Object on multiple lines. | -| `%o` | Pretty-print an Object all on a single line. | -| `%s` | String. | -| `%d` | Number (both integer and float). | -| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | -| `%%` | Single percent sign ('%'). This does not consume an argument. | - - -### Custom formatters - -You can add custom formatters by extending the `debug.formatters` object. -For example, if you wanted to add support for rendering a Buffer as hex with -`%h`, you could do something like: - -```js -const createDebug = require('debug') -createDebug.formatters.h = (v) => { - return v.toString('hex') -} - -// …elsewhere -const debug = createDebug('foo') -debug('this is hex: %h', new Buffer('hello world')) -// foo this is hex: 68656c6c6f20776f726c6421 +0ms -``` - - -## Browser Support - -You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), -or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), -if you don't want to build it yourself. - -Debug's enable state is currently persisted by `localStorage`. -Consider the situation shown below where you have `worker:a` and `worker:b`, -and wish to debug both. You can enable this using `localStorage.debug`: - -```js -localStorage.debug = 'worker:*' -``` - -And then refresh the page. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - b('doing some work'); -}, 1200); -``` - - -## Output streams - - By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: - -Example [_stdout.js_](./examples/node/stdout.js): - -```js -var debug = require('debug'); -var error = debug('app:error'); - -// by default stderr is used -error('goes to stderr!'); - -var log = debug('app:log'); -// set this namespace to log via console.log -log.log = console.log.bind(console); // don't forget to bind to console! -log('goes to stdout'); -error('still goes to stderr!'); - -// set all output to go via console.info -// overrides all per-namespace log settings -debug.log = console.info.bind(console); -error('now goes to stdout via console.info'); -log('still goes to stdout, but via console.info now'); -``` - -## Extend -You can simply extend debugger -```js -const log = require('debug')('auth'); - -//creates new debug instance with extended namespace -const logSign = log.extend('sign'); -const logLogin = log.extend('login'); - -log('hello'); // auth hello -logSign('hello'); //auth:sign hello -logLogin('hello'); //auth:login hello -``` - -## Set dynamically - -You can also enable debug dynamically by calling the `enable()` method : - -```js -let debug = require('debug'); - -console.log(1, debug.enabled('test')); - -debug.enable('test'); -console.log(2, debug.enabled('test')); - -debug.disable(); -console.log(3, debug.enabled('test')); - -``` - -print : -``` -1 false -2 true -3 false -``` - -Usage : -`enable(namespaces)` -`namespaces` can include modes separated by a colon and wildcards. - -Note that calling `enable()` completely overrides previously set DEBUG variable : - -``` -$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' -=> false -``` - -`disable()` - -Will disable all namespaces. The functions returns the namespaces currently -enabled (and skipped). This can be useful if you want to disable debugging -temporarily without knowing what was enabled to begin with. - -For example: - -```js -let debug = require('debug'); -debug.enable('foo:*,-foo:bar'); -let namespaces = debug.disable(); -debug.enable(namespaces); -``` - -Note: There is no guarantee that the string will be identical to the initial -enable string, but semantically they will be identical. - -## Checking whether a debug target is enabled - -After you've created a debug instance, you can determine whether or not it is -enabled by checking the `enabled` property: - -```javascript -const debug = require('debug')('http'); - -if (debug.enabled) { - // do stuff... -} -``` - -You can also manually toggle this property to force the debug instance to be -enabled or disabled. - - -## Authors - - - TJ Holowaychuk - - Nathan Rajlich - - Andrew Rhyne - -## Backers - -Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Sponsors - -Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## License - -(The MIT License) - -Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/package.json b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/package.json deleted file mode 100644 index b7d70ac..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "debug", - "version": "4.3.2", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "files": [ - "src", - "LICENSE", - "README.md" - ], - "author": "TJ Holowaychuk ", - "contributors": [ - "Nathan Rajlich (http://n8.io)", - "Andrew Rhyne ", - "Josh Junon " - ], - "license": "MIT", - "scripts": { - "lint": "xo", - "test": "npm run test:node && npm run test:browser && npm run lint", - "test:node": "istanbul cover _mocha -- test.js", - "test:browser": "karma start --single-run", - "test:coverage": "cat ./coverage/lcov.info | coveralls" - }, - "dependencies": { - "ms": "2.1.2" - }, - "devDependencies": { - "brfs": "^2.0.1", - "browserify": "^16.2.3", - "coveralls": "^3.0.2", - "istanbul": "^0.4.5", - "karma": "^3.1.4", - "karma-browserify": "^6.0.0", - "karma-chrome-launcher": "^2.2.0", - "karma-mocha": "^1.3.0", - "mocha": "^5.2.0", - "mocha-lcov-reporter": "^1.2.0", - "xo": "^0.23.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - }, - "main": "./src/index.js", - "browser": "./src/browser.js", - "engines": { - "node": ">=6.0" - } -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/browser.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/browser.js deleted file mode 100644 index cd0fc35..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/browser.js +++ /dev/null @@ -1,269 +0,0 @@ -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = require('./common')(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/common.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/common.js deleted file mode 100644 index 50ce292..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/common.js +++ /dev/null @@ -1,274 +0,0 @@ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require('ms'); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/index.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/index.js deleted file mode 100644 index bf4c57f..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = require('./browser.js'); -} else { - module.exports = require('./node.js'); -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/node.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/node.js deleted file mode 100644 index 79bc085..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/debug/src/node.js +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Module dependencies. - */ - -const tty = require('tty'); -const util = require('util'); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = require('supports-color'); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = require('./common')(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/index.js b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/index.js deleted file mode 100644 index c4498bc..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/index.js +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/license.md b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Zeit, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/package.json b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/package.json deleted file mode 100644 index eea666e..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "ms", - "version": "2.1.2", - "description": "Tiny millisecond conversion utility", - "repository": "zeit/ms", - "main": "./index", - "files": [ - "index.js" - ], - "scripts": { - "precommit": "lint-staged", - "lint": "eslint lib/* bin/*", - "test": "mocha tests.js" - }, - "eslintConfig": { - "extends": "eslint:recommended", - "env": { - "node": true, - "es6": true - } - }, - "lint-staged": { - "*.js": [ - "npm run lint", - "prettier --single-quote --write", - "git add" - ] - }, - "license": "MIT", - "devDependencies": { - "eslint": "4.12.1", - "expect.js": "0.3.1", - "husky": "0.14.3", - "lint-staged": "5.0.0", - "mocha": "4.0.1" - } -} diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/readme.md b/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/readme.md deleted file mode 100644 index 9a1996b..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/node_modules/ms/readme.md +++ /dev/null @@ -1,60 +0,0 @@ -# ms - -[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) -[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) - -Use this package to easily convert various time formats to milliseconds. - -## Examples - -```js -ms('2 days') // 172800000 -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2.5 hrs') // 9000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5s') // 5000 -ms('1y') // 31557600000 -ms('100') // 100 -ms('-3 days') // -259200000 -ms('-1h') // -3600000 -ms('-200') // -200 -``` - -### Convert from Milliseconds - -```js -ms(60000) // "1m" -ms(2 * 60000) // "2m" -ms(-3 * 60000) // "-3m" -ms(ms('10 hours')) // "10h" -``` - -### Time Format Written-Out - -```js -ms(60000, { long: true }) // "1 minute" -ms(2 * 60000, { long: true }) // "2 minutes" -ms(-3 * 60000, { long: true }) // "-3 minutes" -ms(ms('10 hours'), { long: true }) // "10 hours" -``` - -## Features - -- Works both in [Node.js](https://nodejs.org) and in the browser -- If a number is supplied to `ms`, a string with a unit is returned -- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) -- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned - -## Related Packages - -- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. - -## Caught a Bug? - -1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device -2. Link the package to the global module directory: `npm link` -3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! - -As always, you can run the tests using: `npm test` diff --git a/reverse_engineering/node_modules/mongodb-collection-sample/package.json b/reverse_engineering/node_modules/mongodb-collection-sample/package.json deleted file mode 100644 index 69d5839..0000000 --- a/reverse_engineering/node_modules/mongodb-collection-sample/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "mongodb-collection-sample", - "description": "Sample documents from MongoDB collections.", - "version": "4.5.1", - "scripts": { - "check": "mongodb-js-precommit", - "pretest": "mongodb-runner start --port=27018", - "posttest": "mongodb-runner stop --port=27018", - "test": "mocha --exit" - }, - "homepage": "https://github.com/mongodb-js/mongodb-collection-sample", - "repository": { - "type": "git", - "url": "git://github.com/mongodb-js/mongodb-collection-sample.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/mongodb-js/mongodb-collection-sample/issues" - }, - "bin": { - "mongodb-collection-sample": "bin/mongodb-collection-sample.js" - }, - "dependencies": { - "bson": "^4.0.3", - "debug": "^4.1.1", - "event-stream": "^4.0.1", - "lodash.chunk": "^4.2.0", - "lodash.defaults": "^4.2.0", - "reservoir": "^0.1.2", - "semver": "^5.7.1" - }, - "devDependencies": { - "backoff": "^2.5.0", - "chai": "^4.2.0", - "eslint-config-mongodb-js": "^5.0.3", - "lodash.range": "^3.2.0", - "mocha": "^7.0.0", - "mongodb": "^3.4.1", - "mongodb-js-precommit": "^2.0.0", - "mongodb-runner": "^4.8.0", - "proxyquire": "^2.1.3" - }, - "optionalDependencies": { - "mongodb-ns": "^2.2.0", - "yargs": "^15.1.0" - } -} diff --git a/reverse_engineering/node_modules/mongodb-ns/LICENSE b/reverse_engineering/node_modules/mongodb-ns/LICENSE deleted file mode 100644 index af170a6..0000000 --- a/reverse_engineering/node_modules/mongodb-ns/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Lucas Hrabovsky - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/mongodb-ns/README.md b/reverse_engineering/node_modules/mongodb-ns/README.md deleted file mode 100644 index fcfc088..0000000 --- a/reverse_engineering/node_modules/mongodb-ns/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# mongodb-ns - -[![build status](https://secure.travis-ci.org/mongodb-js/ns.svg)](http://travis-ci.org/mongodb-js/ns) - -Handle dem namespaces like the kernel do. - -``` -var ns = require('mongodb-ns'); - -var bacon = ns('canadian-things.songs-aboot-bacon'); -console.log(bacon.toString() + '\n', bacon); -``` - -will output - -``` -canadian-things.songs-aboot-bacon - NS { - ns: 'canadian-things.songs-aboot-bacon', - dotIndex: 15, - database: 'canadian-things', - collection: 'songs-aboot-bacon', - system: false, - oplog: false, - command: false, - special: false, - specialish: false, - normal: true, - validDatabaseName: true, - validCollectionName: true, - databaseHash: 23620443216 } -``` - - -## license - -MIT diff --git a/reverse_engineering/node_modules/mongodb-ns/index.js b/reverse_engineering/node_modules/mongodb-ns/index.js deleted file mode 100644 index 5dd4e20..0000000 --- a/reverse_engineering/node_modules/mongodb-ns/index.js +++ /dev/null @@ -1,96 +0,0 @@ -var types = ['Command', 'Special', 'System', 'Oplog', 'Normal', 'Conf']; - -// eslint-disable-next-line complexity -function NS(ns) { - if (!(this instanceof NS)) { - return new NS(ns); - } - - this.ns = ns; - this.dotIndex = ns.indexOf('.'); - if (this.dotIndex === -1) { - this.database = ns; - this.collection = ''; - } else { - this.database = ns.slice(0, this.dotIndex); - this.collection = ns.slice(this.dotIndex + 1); - } - - this.system = /^system\./.test(this.collection); - this.oplog = /local\.oplog\.(\$main|rs)/.test(ns); - - this.command = - this.collection === '$cmd' || this.collection.indexOf('$cmd.sys') === 0; - this.special = - this.oplog || this.command || this.system || this.database === 'config'; - - this.specialish = - this.special || ['local', 'admin'].indexOf(this.database) > -1; - - this.normal = this.oplog || this.ns.indexOf('$') === -1; - - /** - * @note (imlucas) The following are not valid on windows: - * `*<>:|?` - */ - this.validDatabaseName = - new RegExp('^[^\\\\/". ]*$').test(this.database) && - this.database.length <= NS.MAX_DATABASE_NAME_LENGTH; - this.validCollectionName = - this.collection.length > 0 && - (this.oplog || /^[^\0\$]*$/.test(this.collection)); - - this.databaseHash = 7; - this.ns.split('').every( - function(c, i) { - if (c === '.') { - return false; - } - this.databaseHash += 11 * this.ns.charCodeAt(i); - this.databaseHash *= 3; - return true; - }.bind(this) - ); -} - -NS.prototype.database = ''; -NS.prototype.databaseHash = 0; -NS.prototype.collection = ''; - -NS.prototype.command = false; -NS.prototype.special = false; -NS.prototype.system = false; -NS.prototype.oplog = false; -NS.prototype.normal = false; -NS.prototype.specialish = false; - -types.forEach(function(type) { - NS.prototype['is' + type] = function() { - return this[type.toLowerCase()]; - }; -}); - -NS.prototype.toString = function() { - return this.ns; -}; - -NS.MAX_DATABASE_NAME_LENGTH = 128; - -module.exports = NS; - -var ns = NS; -module.exports.sort = function(namespaces) { - namespaces.sort(function(a, b) { - if (ns(a).specialish && ns(b).specialish) { - return 0; - } - if (ns(a).specialish && !ns(b).specialish) { - return 1; - } - if (!ns(a).specialish && ns(b).specialish) { - return -1; - } - return a > b ? 1 : -1; - }); - return namespaces; -}; diff --git a/reverse_engineering/node_modules/mongodb-ns/package.json b/reverse_engineering/node_modules/mongodb-ns/package.json deleted file mode 100644 index 225e82a..0000000 --- a/reverse_engineering/node_modules/mongodb-ns/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "mongodb-ns", - "version": "2.2.0", - "author": "Lucas Hrabovsky (http://imlucas.com)", - "description": "MongoDB namespace parsing and validation", - "scripts": { - "test": "mocha", - "check": "mongodb-js-precommit" - }, - "homepage": "http://github.com/mongodb-js/ns", - "repository": { - "type": "git", - "url": "git://github.com/mongodb-js/ns.git" - }, - "keywords": [ - "mongodb", - "mongodb.js" - ], - "license": "MIT", - "dependencies": {}, - "devDependencies": { - "eslint-config-mongodb-js": "^5.0.3", - "mocha": "^7.0.0", - "mongodb-js-precommit": "^2.0.0" - } -} diff --git a/reverse_engineering/node_modules/mongodb/LICENSE.md b/reverse_engineering/node_modules/mongodb/LICENSE.md deleted file mode 100644 index ad410e1..0000000 --- a/reverse_engineering/node_modules/mongodb/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/reverse_engineering/node_modules/mongodb/README.md b/reverse_engineering/node_modules/mongodb/README.md deleted file mode 100644 index cce85e2..0000000 --- a/reverse_engineering/node_modules/mongodb/README.md +++ /dev/null @@ -1,493 +0,0 @@ -# MongoDB NodeJS Driver - -[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) - -The official [MongoDB](https://www.mongodb.com/) driver for Node.js. - -**NOTE: v3.x released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** - -## Version 4.0 - -**Looking for the latest?** We're working on the next major version of the driver, now in beta. -Check out our [beta version 4.0 here](https://github.com/mongodb/node-mongodb-native/tree/4.0), which includes a full migration of the driver to TypeScript. - -## Quick Links - -| what | where | -| ------------- | ---------------------------------------------------- | -| documentation | https://mongodb.github.io/node-mongodb-native | -| api-doc | https://mongodb.github.io/node-mongodb-native/3.6/api | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | https://www.mongodb.org | - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a -case in our issue management tool, JIRA: - -- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). -- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Support / Feedback - -For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver). - -### Change Log - -Change history can be found in [`HISTORY.md`](HISTORY.md). - -### Compatibility - -For version compatibility matrices, please refer to the following links: - -- [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node) -- [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node) - -## Installation - -The recommended way to get started using the Node.js driver is by using `npm` (Node Package Manager) to install the dependency in your project. - -## MongoDB Driver - -Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. - -```bash -npm install mongodb --save -``` - -This will download the MongoDB driver and add a dependency entry in your `package.json` file. - -You can also use the [Yarn](https://yarnpkg.com/en) package manager. - -## Troubleshooting - -The MongoDB driver depends on several other packages. These are: - -- [bson](https://github.com/mongodb/js-bson) -- [bson-ext](https://github.com/mongodb-js/bson-ext) -- [kerberos](https://github.com/mongodb-js/kerberos) -- [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme) - -The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. - -**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** - -### Diagnosing on UNIX - -If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. - -```bash -git clone https://github.com/mongodb-js/kerberos -cd kerberos -npm install -``` - -If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: - -```bash -npm install -g node-gyp -``` - -If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. - -```bash -cd yourproject -npm install mongodb --save -``` - -If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. - -```bash -npm --loglevel verbose install mongodb -``` - -This will print out all the steps npm is performing while trying to install the module. - -### Diagnosing on Windows - -A compiler tool chain known to work for compiling `kerberos` on Windows is the following. - -- Visual Studio C++ 2010 (do not use higher versions) -- Windows 7 64bit SDK -- Python 2.7 or higher - -Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. - -```bash -npm install -g node-gyp -``` - -Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: - -```bash -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -node-gyp rebuild -``` - -This should rebuild the driver successfully if you have everything set up correctly. - -### Other possible issues - -Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). - -Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. - -## Quick Start - -This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). - -### Create the `package.json` file - -First, create a directory where your application will live. - -```bash -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project: - -```bash -npm init -``` - -Next, install the driver dependency. - -```bash -npm install mongodb --save -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -### Start a MongoDB Server - -For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). - -1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) -2. Create a database directory (in this case under **/data**). -3. Install and start a `mongod` process. - -```bash -mongod --dbpath=/data -``` - -You should see the **mongod** process start up and print some status information. - -### Connect to MongoDB - -Create a new **app.js** file and add the following code to try out some basic CRUD -operations using the MongoDB driver. - -Add code to connect to the server and the database **myproject**: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; -const client = new MongoClient(url); -// Use connect method to connect to the server -client.connect(function(err) { - assert.equal(null, err); - console.log('Connected successfully to server'); - - const db = client.db(dbName); - - client.close(); -}); -``` - -Run your app from the command line with: - -```bash -node app.js -``` - -The application should print **Connected successfully to server** to the console. - -### Insert a Document - -Add to **app.js** the following function which uses the **insertMany** -method to add three documents to the **documents** collection. - -```js -const insertDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Insert some documents - collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log('Inserted 3 documents into the collection'); - callback(result); - }); -}; -``` - -The **insert** command returns an object with the following fields: - -- **result** Contains the result document from MongoDB -- **ops** Contains the documents inserted with added **\_id** fields -- **connection** Contains the connection used to perform the insert - -Add the following code to call the **insertDocuments** function: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log('Connected successfully to server'); - - const db = client.db(dbName); - - insertDocuments(db, function() { - client.close(); - }); -}); -``` - -Run the updated **app.js** file: - -```bash -node app.js -``` - -The operation returns the following output: - -```bash -Connected successfully to server -Inserted 3 documents into the collection -``` - -### Find All Documents - -Add a query that returns all the documents. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - console.log('Found the following records'); - console.log(docs); - callback(docs); - }); -}; -``` - -This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log('Connected correctly to server'); - - const db = client.db(dbName); - - insertDocuments(db, function() { - findDocuments(db, function() { - client.close(); - }); - }); -}); -``` - -### Find Documents with a Query Filter - -Add a query filter to find only documents which meet the query criteria. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({ a: 3 }).toArray(function(err, docs) { - assert.equal(err, null); - console.log('Found the following records'); - console.log(docs); - callback(docs); - }); -}; -``` - -Only the documents which match `'a' : 3` should be returned. - -### Update a document - -The following operation updates a document in the **documents** collection. - -```js -const updateDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.updateOne({ a: 2 }, { $set: { b: 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log('Updated the document with the field a equal to 2'); - callback(result); - }); -}; -``` - -The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log('Connected successfully to server'); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - client.close(); - }); - }); -}); -``` - -### Remove a document - -Remove the document where the field **a** is equal to **3**. - -```js -const removeDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Delete document where a is 3 - collection.deleteOne({ a: 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log('Removed the document with the field a equal to 3'); - callback(result); - }); -}; -``` - -Add the new method to the **MongoClient.connect** callback function. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log('Connected successfully to server'); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - client.close(); - }); - }); - }); -}); -``` - -### Index a Collection - -[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's -performance. The following function creates an index on the **a** field in the -**documents** collection. - -```js -const indexCollection = function(db, callback) { - db.collection('documents').createIndex({ a: 1 }, null, function(err, results) { - console.log(results); - callback(); - }); -}; -``` - -Add the `indexCollection` method to your app: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log('Connected successfully to server'); - - const db = client.db(dbName); - - insertDocuments(db, function() { - indexCollection(db, function() { - client.close(); - }); - }); -}); -``` - -For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). - -## Next Steps - -- [MongoDB Documentation](https://mongodb.org) -- [Read about Schemas](http://learnmongodbthehardway.com) -- [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) - -## License - -[Apache 2.0](LICENSE.md) - -© 2009-2012 Christian Amor Kvalheim -© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/reverse_engineering/node_modules/mongodb/index.js b/reverse_engineering/node_modules/mongodb/index.js deleted file mode 100644 index efb16d3..0000000 --- a/reverse_engineering/node_modules/mongodb/index.js +++ /dev/null @@ -1,77 +0,0 @@ -'use strict'; - -// Core module -const core = require('./lib/core'); -const Instrumentation = require('./lib/apm'); - -// Set up the connect function -const connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; -connect.MongoNetworkError = core.MongoNetworkError; -connect.MongoTimeoutError = core.MongoTimeoutError; -connect.MongoServerSelectionError = core.MongoServerSelectionError; -connect.MongoParseError = core.MongoParseError; -connect.MongoWriteConcernError = core.MongoWriteConcernError; -connect.MongoBulkWriteError = require('./lib/bulk/common').BulkWriteError; -connect.BulkWriteError = connect.MongoBulkWriteError; - -// Expose server versions -connect.ServerApiVersion = core.ServerApiVersion; - -// Actual driver classes exported -connect.Admin = require('./lib/admin'); -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/topologies/server'); -connect.ReplSet = require('./lib/topologies/replset'); -connect.Mongos = require('./lib/topologies/mongos'); -connect.ReadPreference = core.ReadPreference; -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.AggregationCursor = require('./lib/aggregation_cursor'); -connect.CommandCursor = require('./lib/command_cursor'); -connect.Cursor = require('./lib/cursor'); -connect.GridFSBucket = require('./lib/gridfs-stream'); -// Exported to be used in tests not to be used anywhere else -connect.CoreServer = core.Server; -connect.CoreConnection = core.Connection; - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.Map = core.BSON.Map; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Int32 = core.BSON.Int32; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -/** @deprecated Please use `ObjectId` */ -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; -connect.BSONRegExp = core.BSON.BSONRegExp; -connect.Decimal128 = core.BSON.Decimal128; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - const instrumentation = new Instrumentation(); - instrumentation.instrument(connect.MongoClient, callback); - return instrumentation; -}; - -// Set our exports to be the connect function -module.exports = connect; diff --git a/reverse_engineering/node_modules/mongodb/lib/admin.js b/reverse_engineering/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 3c8164f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,296 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('./utils').applyWriteConcern; - -const AddUserOperation = require('./operations/add_user'); -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const RemoveUserOperation = require('./operations/remove_user'); -const ValidateCollectionOperation = require('./operations/validate_collection'); -const ListDatabasesOperation = require('./operations/list_databases'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to - * the admin functionality and commands for MongoDB. - * - * **ADMIN Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Use the admin database for the operation - * const adminDb = client.db(dbName).admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * client.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -function Admin(db, topology, promiseLibrary) { - if (!(this instanceof Admin)) return new Admin(db, topology); - - // Internal state - this.s = { - db: db, - topology: topology, - promiseLibrary: promiseLibrary - }; -} - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - - const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); - - return executeOperation(this.s.db.s.topology, commandOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); -}; - -/** - * Retrieve this db's server status. - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const serverStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { serverStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { ping: 1 }; - - const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, pingOperation, callback); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name to admin - options.dbName = 'admin'; - - const addUserOperation = new AddUserOperation(this.s.db, username, password, options); - - return executeOperation(this.s.db.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name - options.dbName = 'admin'; - - const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); - - return executeOperation(this.s.db.s.topology, removeUserOperation, callback); -}; - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options] Optional settings. - * @param {boolean} [options.background] Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const validateCollectionOperation = new ValidateCollectionOperation( - this, - collectionName, - options - ); - - return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); -}; - -/** - * List the available databases - * - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.db.s.topology, - new ListDatabasesOperation(this.s.db, options), - callback - ); -}; - -/** - * Get ReplicaSet status - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { replSetGetStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); -}; - -module.exports = Admin; diff --git a/reverse_engineering/node_modules/mongodb/lib/aggregation_cursor.js b/reverse_engineering/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index 9289733..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,369 +0,0 @@ -'use strict'; - -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -class AggregationCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @throws {MongoError} - * @return {AggregationCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.operation.options.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ - geoNear(document) { - this.operation.addToPipeline({ $geoNear: document }); - return this; - } - - /** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ - group(document) { - this.operation.addToPipeline({ $group: document }); - return this; - } - - /** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ - limit(value) { - this.operation.addToPipeline({ $limit: value }); - return this; - } - - /** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ - match(document) { - this.operation.addToPipeline({ $match: document }); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ - maxTimeMS(value) { - this.operation.options.maxTimeMS = value; - return this; - } - - /** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ - out(destination) { - this.operation.addToPipeline({ $out: destination }); - return this; - } - - /** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ - project(document) { - this.operation.addToPipeline({ $project: document }); - return this; - } - - /** - * Add a lookup stage to the aggregation pipeline - * @method - * @param {object} document The lookup stage document. - * @return {AggregationCursor} - */ - lookup(document) { - this.operation.addToPipeline({ $lookup: document }); - return this; - } - - /** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ - redact(document) { - this.operation.addToPipeline({ $redact: document }); - return this; - } - - /** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ - skip(value) { - this.operation.addToPipeline({ $skip: value }); - return this; - } - - /** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ - sort(document) { - this.operation.addToPipeline({ $sort: document }); - return this; - } - - /** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {(string|object)} field The unwind field name or stage document. - * @return {AggregationCursor} - */ - unwind(field) { - this.operation.addToPipeline({ $unwind: field }); - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function AggregationCursor.prototype.hasNext - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @deprecated - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * - * For backwards compatibility, a verbosity of true is interpreted as "allPlansExecution" - * and false as "queryPlanner". Prior to server version 3.6, aggregate() - * ignores the verbosity parameter and executes in "queryPlanner". - * - * @method AggregationCursor.prototype.explain - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [verbosity=true] - An optional mode in which to run the explain. - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = AggregationCursor; diff --git a/reverse_engineering/node_modules/mongodb/lib/apm.js b/reverse_engineering/node_modules/mongodb/lib/apm.js deleted file mode 100644 index f78e4aa..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -const EventEmitter = require('events').EventEmitter; - -class Instrumentation extends EventEmitter { - constructor() { - super(); - } - - instrument(MongoClient, callback) { - // store a reference to the original functions - this.$MongoClient = MongoClient; - const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); - - const instrumentation = this; - MongoClient.prototype.connect = function(callback) { - this.s.options.monitorCommands = true; - this.on('commandStarted', event => instrumentation.emit('started', event)); - this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); - this.on('commandFailed', event => instrumentation.emit('failed', event)); - return $prototypeConnect.call(this, callback); - }; - - if (typeof callback === 'function') callback(null, this); - } - - uninstrument() { - this.$MongoClient.prototype.connect = this.$prototypeConnect; - } -} - -module.exports = Instrumentation; diff --git a/reverse_engineering/node_modules/mongodb/lib/async/.eslintrc b/reverse_engineering/node_modules/mongodb/lib/async/.eslintrc deleted file mode 100644 index 93b2f64..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/async/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "parserOptions": { - "ecmaVersion": 2018 - } -} diff --git a/reverse_engineering/node_modules/mongodb/lib/async/async_iterator.js b/reverse_engineering/node_modules/mongodb/lib/async/async_iterator.js deleted file mode 100644 index 6021aad..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/async/async_iterator.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -// async function* asyncIterator() { -// while (true) { -// const value = await this.next(); -// if (!value) { -// await this.close(); -// return; -// } - -// yield value; -// } -// } - -// TODO: change this to the async generator function above -function asyncIterator() { - const cursor = this; - - return { - next: function() { - return Promise.resolve() - .then(() => cursor.next()) - .then(value => { - if (!value) { - return cursor.close().then(() => ({ value, done: true })); - } - return { value, done: false }; - }); - } - }; -} - -exports.asyncIterator = asyncIterator; diff --git a/reverse_engineering/node_modules/mongodb/lib/bulk/common.js b/reverse_engineering/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index 9d69401..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,1401 +0,0 @@ -'use strict'; - -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ObjectID = require('../core').BSON.ObjectID; -const BSON = require('../core').BSON; -const MongoWriteConcernError = require('../core').MongoWriteConcernError; -const emitWarningOnce = require('../utils').emitWarningOnce; -const toError = require('../utils').toError; -const handleCallback = require('../utils').handleCallback; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const isPromiseLike = require('../utils').isPromiseLike; -const hasAtomicOperators = require('../utils').hasAtomicOperators; -const maxWireVersion = require('../core/utils').maxWireVersion; - -// Error codes -const WRITE_CONCERN_ERROR = 64; - -// Insert types -const INSERT = 1; -const UPDATE = 2; -const REMOVE = 3; - -const bson = new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp -]); - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -class Batch { - constructor(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; - } -} - -const kUpsertedIds = Symbol('upsertedIds'); -const kInsertedIds = Symbol('insertedIds'); - -/** - * @classdesc - * The result of a bulk write. - */ -class BulkWriteResult { - /** - * Create a new BulkWriteResult instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(bulkResult) { - this.result = bulkResult; - this[kUpsertedIds] = undefined; - this[kInsertedIds] = undefined; - } - - /** Number of documents inserted. */ - get insertedCount() { - return typeof this.result.nInserted !== 'number' ? 0 : this.result.nInserted; - } - /** Number of documents matched for update. */ - get matchedCount() { - return typeof this.result.nMatched !== 'number' ? 0 : this.result.nMatched; - } - /** Number of documents modified. */ - get modifiedCount() { - return typeof this.result.nModified !== 'number' ? 0 : this.result.nModified; - } - /** Number of documents deleted. */ - get deletedCount() { - return typeof this.result.nRemoved !== 'number' ? 0 : this.result.nRemoved; - } - /** Number of documents upserted. */ - get upsertedCount() { - return !this.result.upserted ? 0 : this.result.upserted.length; - } - - /** Upserted document generated Id's, hash key is the index of the originating operation */ - get upsertedIds() { - if (this[kUpsertedIds]) { - return this[kUpsertedIds]; - } - - this[kUpsertedIds] = {}; - for (const doc of this.result.upserted || []) { - this[kUpsertedIds][doc.index] = doc._id; - } - return this[kUpsertedIds]; - } - - /** Inserted document generated Id's, hash key is the index of the originating operation */ - get insertedIds() { - if (this[kInsertedIds]) { - return this[kInsertedIds]; - } - - this[kInsertedIds] = {}; - for (const doc of this.result.insertedIds || []) { - this[kInsertedIds][doc.index] = doc._id; - } - return this[kInsertedIds]; - } - - /** The number of inserted documents @type {number} */ - get n() { - return this.result.insertedCount; - } - - /** - * Evaluates to true if the bulk operation correctly executes - * @type {boolean} - */ - get ok() { - return this.result.ok; - } - - /** - * The number of inserted documents - * @type {number} - */ - get nInserted() { - return this.result.nInserted; - } - - /** - * Number of upserted documents - * @type {number} - */ - get nUpserted() { - return this.result.nUpserted; - } - - /** - * Number of matched documents - * @type {number} - */ - get nMatched() { - return this.result.nMatched; - } - - /** - * Number of documents updated physically on disk - * @type {number} - */ - get nModified() { - return this.result.nModified; - } - - /** - * Number of removed documents - * @type {number} - */ - get nRemoved() { - return this.result.nRemoved; - } - - /** - * Returns an array of all inserted ids - * - * @return {object[]} - */ - getInsertedIds() { - return this.result.insertedIds; - } - - /** - * Returns an array of all upserted ids - * - * @return {object[]} - */ - getUpsertedIds() { - return this.result.upserted; - } - - /** - * Returns the upserted id at the given index - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - getUpsertedIdAt(index) { - return this.result.upserted[index]; - } - - /** - * Returns raw internal result - * - * @return {object} - */ - getRawResponse() { - return this.result; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - hasWriteErrors() { - return this.result.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - getWriteErrorCount() { - return this.result.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @param {number} index of the write error to return, returns null if there is no result for passed in index - * @return {WriteError} - */ - getWriteErrorAt(index) { - if (index < this.result.writeErrors.length) { - return this.result.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {WriteError[]} - */ - getWriteErrors() { - return this.result.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - getLastOp() { - return this.result.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - getWriteConcernError() { - if (this.result.writeConcernErrors.length === 0) { - return null; - } else if (this.result.writeConcernErrors.length === 1) { - // Return the error - return this.result.writeConcernErrors[0]; - } else { - // Combine the errors - let errmsg = ''; - for (let i = 0; i < this.result.writeConcernErrors.length; i++) { - const err = this.result.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if (i === 0) errmsg = errmsg + ' and '; - } - - return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); - } - } - - /** - * @return {object} - */ - toJSON() { - return this.result; - } - - /** - * @return {string} - */ - toString() { - return `BulkWriteResult(${this.toJSON(this.result)})`; - } - - /** - * @return {boolean} - */ - isOk() { - return this.result.ok === 1; - } -} - -/** - * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. - */ -class WriteConcernError { - /** - * Create a new WriteConcernError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * Write concern error code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * Write concern error message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, errmsg: this.err.errmsg }; - } - - /** - * @return {string} - */ - toString() { - return `WriteConcernError(${this.err.errmsg})`; - } -} - -/** - * @classdesc An error that occurred during a BulkWrite on the server. - */ -class WriteError { - /** - * Create a new WriteError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * WriteError code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * WriteError original bulk operation index. - * @type {number} - */ - get index() { - return this.err.index; - } - - /** - * WriteError message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * Returns the underlying operation that caused the error - * @return {object} - */ - getOperation() { - return this.err.op; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; - } - - /** - * @return {string} - */ - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; - } -} - -/** - * Converts the number to a Long or returns it. - * - * @ignore - */ -function longOrConvert(value) { - return typeof value === 'number' ? Long.fromNumber(value) : value; -} - -/** - * Merges results into shared data structure - * @ignore - */ -function mergeBatchResults(batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if (err) { - result = err; - } else if (result && result.result) { - result = result.result; - } else if (result == null) { - return; - } - - // Do we have a top level error stop processing and return - if (result.ok === 0 && bulkResult.ok === 1) { - bulkResult.ok = 0; - - const writeError = { - index: 0, - code: result.code || 0, - errmsg: result.message, - op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if (result.ok === 0 && bulkResult.ok === 0) { - return; - } - - // The server write command specification states that lastOp is an optional - // mongod only field that has a type of timestamp. Across various scarce specs - // where opTime is mentioned, it is an "opaque" object that can have a "ts" and - // "t" field with Timestamp and Long as their types respectively. - // The "lastOp" field of the bulk write result is never mentioned in the driver - // specifications or the bulk write spec, so we should probably just keep its - // value consistent since it seems to vary. - // See: https://github.com/mongodb/specifications/blob/master/source/driver-bulk-update.rst#results-object - if (result.opTime || result.lastOp) { - let opTime = result.lastOp || result.opTime; - - // If the opTime is a Timestamp, convert it to a consistent format to be - // able to compare easily. Converting to the object from a timestamp is - // much more straightforward than the other direction. - if (opTime._bsontype === 'Timestamp') { - opTime = { ts: opTime, t: Long.ZERO }; - } - - // If there's no lastOp, just set it. - if (!bulkResult.lastOp) { - bulkResult.lastOp = opTime; - } else { - // First compare the ts values and set if the opTimeTS value is greater. - const lastOpTS = longOrConvert(bulkResult.lastOp.ts); - const opTimeTS = longOrConvert(opTime.ts); - if (opTimeTS.greaterThan(lastOpTS)) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.equals(lastOpTS)) { - // If the ts values are equal, then compare using the t values. - const lastOpT = longOrConvert(bulkResult.lastOp.t); - const opTimeT = longOrConvert(opTime.t); - if (opTimeT.greaterThan(lastOpT)) { - bulkResult.lastOp = opTime; - } - } - } - } - - // If we have an insert Batch type - if (batch.batchType === INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if (batch.batchType === REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - let nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if (Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for (let i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex, - _id: result.upserted[i]._id - }); - } - } else if (result.upserted) { - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex, - _id: result.upserted - }); - } - - // If we have an update Batch type - if (batch.batchType === UPDATE && result.n) { - const nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if (typeof nModified === 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if (Array.isArray(result.writeErrors)) { - for (let i = 0; i < result.writeErrors.length; i++) { - const writeError = { - index: batch.originalIndexes[result.writeErrors[i].index], - code: result.writeErrors[i].code, - errmsg: result.writeErrors[i].errmsg, - op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if (result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -function executeCommands(bulkOperation, options, callback) { - if (bulkOperation.s.batches.length === 0) { - return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); - } - - const batch = bulkOperation.s.batches.shift(); - - function resultHandler(err, result) { - // Error is a driver related error not a bulk op error, terminate - if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { - return handleCallback(callback, err); - } - - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); - } - - // Merge the results together - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); - const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); - if (mergeResult != null) { - return handleCallback(callback, null, writeResult); - } - - if (bulkOperation.handleWriteError(callback, writeResult)) return; - - // Execute the next command in line - executeCommands(bulkOperation, options, callback); - } - - bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); -} - -/** - * handles write concern error - * - * @ignore - * @param {object} batch - * @param {object} bulkResult - * @param {boolean} ordered - * @param {WriteConcernError} err - * @param {function} callback - */ -function handleMongoWriteConcernError(batch, bulkResult, err, callback) { - mergeBatchResults(batch, bulkResult, null, err.result); - - const wrappedWriteConcernError = new WriteConcernError({ - errmsg: err.result.writeConcernError.errmsg, - code: err.result.writeConcernError.result - }); - return handleCallback( - callback, - new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), - null - ); -} - -/** - * @classdesc An error indicating an unsuccessful Bulk Write - */ -class BulkWriteError extends MongoError { - /** - * Creates a new BulkWriteError - * - * @param {Error|string|object} message The error message - * @param {BulkWriteResult} result The result of the bulk write operation - * @extends {MongoError} - */ - constructor(error, result) { - const message = error.err || error.errmsg || error.errMessage || error; - super(message); - - Object.assign(this, error); - - this.name = 'BulkWriteError'; - this.result = result; - } - - /** Number of documents inserted. */ - get insertedCount() { - return this.result.insertedCount; - } - /** Number of documents matched for update. */ - get matchedCount() { - return this.result.matchedCount; - } - /** Number of documents modified. */ - get modifiedCount() { - return this.result.modifiedCount; - } - /** Number of documents deleted. */ - get deletedCount() { - return this.result.deletedCount; - } - /** Number of documents upserted. */ - get upsertedCount() { - return this.result.upsertedCount; - } - /** Inserted document generated Id's, hash key is the index of the originating operation */ - get insertedIds() { - return this.result.insertedIds; - } - /** Upserted document generated Id's, hash key is the index of the originating operation */ - get upsertedIds() { - return this.result.upsertedIds; - } -} - -/** - * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. - * Is used to build a write operation that involves a query filter. - */ -class FindOperators { - /** - * Creates a new FindOperators object. - * - * **NOTE:** Internal Type, do not instantiate directly - * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation - */ - constructor(bulkOperation) { - this.s = bulkOperation.s; - } - - /** - * Add a multiple update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - update(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: true, - upsert: upsert - }; - - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a single update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - updateOne(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: false, - upsert: upsert - }; - - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } - - if (!hasAtomicOperators(updateDocument)) { - throw new TypeError('Update document requires atomic operators'); - } - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} replacement the new document to replace the existing one with - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - replaceOne(replacement) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: replacement, - multi: false, - upsert: upsert - }; - - if (replacement.hint) { - document.hint = replacement.hint; - } - - if (hasAtomicOperators(replacement)) { - throw new TypeError('Replacement document must not use atomic operators'); - } - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Upsert modifier for update bulk operation, noting that this operation is an upsert. - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {FindOperators} reference to self - */ - upsert() { - this.s.currentOp.upsert = true; - return this; - } - - /** - * Add a delete one operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - deleteOne() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 1 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * Add a delete many operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - delete() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 0 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * backwards compatability for deleteOne - * @deprecated - */ - removeOne() { - emitWarningOnce('bulk operation `removeOne` has been deprecated, please use `deleteOne`'); - return this.deleteOne(); - } - - /** - * backwards compatability for delete - * @deprecated - */ - remove() { - emitWarningOnce('bulk operation `remove` has been deprecated, please use `delete`'); - return this.delete(); - } -} - -/** - * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation - * - * **NOTE:** Internal Type, do not instantiate directly - */ -class BulkOperationBase { - /** - * Create a new OrderedBulkOperation or UnorderedBulkOperation instance - * @property {number} length Get the number of operations in the bulk. - */ - constructor(topology, collection, options, isOrdered) { - // determine whether bulkOperation is ordered or unordered - this.isOrdered = isOrdered; - - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - // Get the namespace for the write operations - const namespace = collection.s.namespace; - // Used to mark operation as executed - const executed = false; - - // Current item - const currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - const bson = topology.bson; - // Set max byte size - const isMaster = topology.lastIsMaster(); - - // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents - // over 2mb are still allowed - const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); - const maxBsonObjectSize = - isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; - const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; - const maxWriteBatchSize = - isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; - - // Calculates the largest possible size of an Array key, represented as a BSON string - // element. This calculation: - // 1 byte for BSON type - // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) - // + 1 bytes for null terminator - const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, collection.s.db); - finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); - const writeConcern = finalOptions.writeConcern; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Final results - const bulkResult = { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult, - // Current batch state - currentBatch: null, - currentIndex: 0, - // ordered specific - currentBatchSize: 0, - currentBatchSizeBytes: 0, - // unordered specific - currentInsertBatch: null, - currentUpdateBatch: null, - currentRemoveBatch: null, - batches: [], - // Write concern - writeConcern: writeConcern, - // Max batch size options - maxBsonObjectSize, - maxBatchSizeBytes, - maxWriteBatchSize, - maxKeySize, - // Namespace - namespace: namespace, - // BSON - bson: bson, - // Topology - topology: topology, - // Options - options: finalOptions, - // Current operation - currentOp: currentOp, - // Executed - executed: executed, - // Collection - collection: collection, - // Promise Library - promiseLibrary: promiseLibrary, - // Fundamental error - err: null, - // check keys - checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true - }; - - // bypass Validation - if (options.bypassDocumentValidation === true) { - this.s.bypassDocumentValidation = true; - } - } - - /** - * Add a single insert document to the bulk operation - * - * @param {object} document the document to insert - * @throws {MongoError} - * @return {BulkOperationBase} A reference to self - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * // Adds three inserts to the bulkOp. - * bulkOp - * .insert({ a: 1 }) - * .insert({ b: 2 }) - * .insert({ c: 3 }); - * await bulkOp.execute(); - */ - insert(document) { - if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) - document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, document); - } - - /** - * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. - * Returns a builder object used to complete the definition of the operation. - * - * @method - * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} - * @throws {MongoError} if a selector is not specified - * @return {FindOperators} A helper object with which the write operation can be defined. - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * - * // Add an updateOne to the bulkOp - * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); - * - * // Add an updateMany to the bulkOp - * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); - * - * // Add an upsert - * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); - * - * // Add a deletion - * bulkOp.find({ g: 7 }).deleteOne(); - * - * // Add a multi deletion - * bulkOp.find({ h: 8 }).delete(); - * - * // Add a replaceOne - * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); - * - * // Update using a pipeline (requires Mongodb 4.2 or higher) - * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ - * { $set: { total: { $sum: [ '$y', '$z' ] } } } - * ]); - * - * // All of the ops will now be executed - * await bulkOp.execute(); - */ - find(selector) { - if (!selector) { - throw toError('Bulk find operation must specify a selector'); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - }; - - return new FindOperators(this); - } - - /** - * Specifies a raw operation to perform in the bulk write. - * - * @method - * @param {object} op The raw operation to perform. - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @return {BulkOperationBase} A reference to self - */ - raw(op) { - const key = Object.keys(op)[0]; - - // Set up the force server object id - const forceServerObjectId = - typeof this.s.options.forceServerObjectId === 'boolean' - ? this.s.options.forceServerObjectId - : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if ( - (op.updateOne && op.updateOne.q) || - (op.updateMany && op.updateMany.q) || - (op.replaceOne && op.replaceOne.q) - ) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return this.s.options.addToOperationsList(this, UPDATE, op[key]); - } - - // Crud spec update format - if (op.updateOne || op.updateMany || op.replaceOne) { - if (op.replaceOne && hasAtomicOperators(op[key].replacement)) { - throw new TypeError('Replacement document must not use atomic operators'); - } else if ((op.updateOne || op.updateMany) && !hasAtomicOperators(op[key].update)) { - throw new TypeError('Update document requires atomic operators'); - } - - const multi = op.updateOne || op.replaceOne ? false : true; - const operation = { - q: op[key].filter, - u: op[key].update || op[key].replacement, - multi: multi - }; - - if (op[key].hint) { - operation.hint = op[key].hint; - } - - if (this.isOrdered) { - operation.upsert = op[key].upsert ? true : false; - if (op.collation) operation.collation = op.collation; - } else { - if (op[key].upsert) operation.upsert = true; - } - if (op[key].arrayFilters) { - // TODO: this check should be done at command construction against a connection, not a topology - if (maxWireVersion(this.s.topology) < 6) { - throw new TypeError('arrayFilters are only supported on MongoDB 3.6+'); - } - - operation.arrayFilters = op[key].arrayFilters; - } - - return this.s.options.addToOperationsList(this, UPDATE, operation); - } - - // Remove operations - if ( - op.removeOne || - op.removeMany || - (op.deleteOne && op.deleteOne.q) || - (op.deleteMany && op.deleteMany.q) - ) { - op[key].limit = op.removeOne ? 1 : 0; - return this.s.options.addToOperationsList(this, REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if (op.deleteOne || op.deleteMany) { - const limit = op.deleteOne ? 1 : 0; - const operation = { q: op[key].filter, limit: limit }; - if (op[key].hint) { - operation.hint = op[key].hint; - } - if (this.isOrdered) { - if (op.collation) operation.collation = op.collation; - } - return this.s.options.addToOperationsList(this, REMOVE, operation); - } - - // Insert operations - if (op.insertOne && op.insertOne.document == null) { - if (forceServerObjectId !== true && op.insertOne._id == null) - op.insertOne._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne); - } else if (op.insertOne && op.insertOne.document) { - if (forceServerObjectId !== true && op.insertOne.document._id == null) - op.insertOne.document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); - } - - if (op.insertMany) { - emitWarningOnce( - 'bulk operation `insertMany` has been deprecated; use multiple `insertOne` ops instead' - ); - for (let i = 0; i < op.insertMany.length; i++) { - if (forceServerObjectId !== true && op.insertMany[i]._id == null) - op.insertMany[i]._id = new ObjectID(); - this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError( - 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' - ); - } - - /** - * helper function to assist with promiseOrCallback behavior - * @ignore - * @param {*} err - * @param {*} callback - */ - _handleEarlyError(err, callback) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - - return this.s.promiseLibrary.reject(err); - } - - /** - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @method - * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation - * @param {object} writeConcern - * @param {object} options - * @param {function} callback - */ - bulkExecute(_writeConcern, options, callback) { - if (typeof options === 'function') { - callback = options; - } - - const finalOptions = Object.assign({}, this.s.options, options); - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - if (this.s.executed) { - const executedError = toError('batch cannot be re-executed'); - return this._handleEarlyError(executedError, callback); - } - - // If we have current batch - if (this.isOrdered) { - if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - } else { - if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - } - // If we have no operations in the bulk raise an error - if (this.s.batches.length === 0) { - const emptyBatchError = toError('Invalid Operation, no operations specified'); - return this._handleEarlyError(emptyBatchError, callback); - } - return { options: finalOptions, callback }; - } - - /** - * The callback format for results - * @callback BulkOperationBase~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - - /** - * Execute the bulk operation - * - * @method - * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors - * @throws {MongoError} Throws error if the bulk object has already been executed - * @throws {MongoError} Throws error if the bulk object does not have any operations - * @return {Promise|void} returns Promise if no callback passed - */ - execute(_writeConcern, options, callback) { - const ret = this.bulkExecute(_writeConcern, options, callback); - if (!ret || isPromiseLike(ret)) { - return ret; - } - - options = ret.options; - callback = ret.callback; - - return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); - } - - /** - * Handles final options before executing command - * - * An internal method. Do not invoke. Will not be accessible in the future - * - * @ignore - * @param {object} config - * @param {object} config.options - * @param {number} config.batch - * @param {function} config.resultHandler - * @param {function} callback - */ - finalOptionsHandler(config, callback) { - const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); - if (this.s.writeConcern != null) { - finalOptions.writeConcern = this.s.writeConcern; - } - - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; - } - - // Set an operationIf if provided - if (this.operationId) { - config.resultHandler.operationId = this.operationId; - } - - // Serialize functions - if (this.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true; - } - - // Ignore undefined - if (this.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true; - } - - // Is the bypassDocumentValidation options specific - if (this.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; - } - - // Is the checkKeys option disabled - if (this.s.checkKeys === false) { - finalOptions.checkKeys = false; - } - - if (finalOptions.retryWrites) { - if (config.batch.batchType === UPDATE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); - } - - if (config.batch.batchType === REMOVE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); - } - } - - try { - if (config.batch.batchType === INSERT) { - this.s.topology.insert( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === UPDATE) { - this.s.topology.update( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === REMOVE) { - this.s.topology.remove( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } - } catch (err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); - } - } - - /** - * Handles the write error before executing commands - * - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @param {function} callback - * @param {BulkWriteResult} writeResult - * @param {class} self either OrderedBulkOperation or UnorderedBulkOperation - */ - handleWriteError(callback, writeResult) { - if (this.s.bulkResult.writeErrors.length > 0) { - const msg = this.s.bulkResult.writeErrors[0].errmsg - ? this.s.bulkResult.writeErrors[0].errmsg - : 'write operation failed'; - - handleCallback( - callback, - new BulkWriteError( - toError({ - message: msg, - code: this.s.bulkResult.writeErrors[0].code, - writeErrors: this.s.bulkResult.writeErrors - }), - writeResult - ), - null - ); - return true; - } - - if (writeResult.getWriteConcernError()) { - handleCallback( - callback, - new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), - null - ); - return true; - } - } -} - -Object.defineProperty(BulkOperationBase.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// Exports symbols -module.exports = { - Batch, - BulkOperationBase, - mergeBatchResults, - bson, - INSERT: INSERT, - UPDATE: UPDATE, - REMOVE: REMOVE, - BulkWriteError, - BulkWriteResult -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/bulk/ordered.js b/reverse_engineering/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index a976bed..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {OrderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {OrderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBsonObjectSize) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Check if we need to create a new batch - if ( - // New batch if we exceed the max batch op size - bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || - // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, - // since we can't sent an empty batch - (bulkOperation.s.currentBatchSize > 0 && - bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes) || - // New batch if the new op does not have the same op type as the current batch - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Reset the current size trackers - bulkOperation.s.currentBatchSize = 0; - bulkOperation.s.currentBatchSizeBytes = 0; - } - - if (docType === common.INSERT) { - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.currentIndex, - _id: document._id - }); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatchSize += 1; - bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; - bulkOperation.s.currentIndex += 1; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -class OrderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, true); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeOrderedBulkOp(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/bulk/unordered.js b/reverse_engineering/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index c126c5b..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {UnorderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {UnorderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBsonObjectSize) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); - // Holds the current batch - bulkOperation.s.currentBatch = null; - // Get the right type of batch - if (docType === common.INSERT) { - bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; - } else if (docType === common.UPDATE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; - } - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Check if we need to create a new batch - if ( - // New batch if we exceed the max batch op size - bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || - // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, - // since we can't sent an empty batch - (bulkOperation.s.currentBatch.size > 0 && - bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes) || - // New batch if the new op does not have the same op type as the current batch - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; - - // Save back the current Batch to the right type - if (docType === common.INSERT) { - bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.bulkResult.insertedIds.length, - _id: document._id - }); - } else if (docType === common.UPDATE) { - bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; - } - - // Update current batch size - bulkOperation.s.currentBatch.size += 1; - bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -class UnorderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, false); - } - - handleWriteError(callback, writeResult) { - if (this.s.batches.length) { - return false; - } - - return super.handleWriteError(callback, writeResult); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeUnorderedBulkOp(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/change_stream.js b/reverse_engineering/node_modules/mongodb/lib/change_stream.js deleted file mode 100644 index b226702..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/change_stream.js +++ /dev/null @@ -1,623 +0,0 @@ -'use strict'; - -const Denque = require('denque'); -const EventEmitter = require('events'); -const isResumableError = require('./error').isResumableError; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const relayEvents = require('./core/utils').relayEvents; -const maxWireVersion = require('./core/utils').maxWireVersion; -const maybePromise = require('./utils').maybePromise; -const now = require('./utils').now; -const calculateDurationInMs = require('./utils').calculateDurationInMs; -const AggregateOperation = require('./operations/aggregate'); - -const kResumeQueue = Symbol('resumeQueue'); - -const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; -const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( - CHANGE_STREAM_OPTIONS -); - -const CHANGE_DOMAIN_TYPES = { - COLLECTION: Symbol('Collection'), - DATABASE: Symbol('Database'), - CLUSTER: Symbol('Cluster') -}; - -/** - * @typedef ResumeToken - * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. - * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token - */ - -/** - * @typedef OperationTime - * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} - * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response - */ - -/** - * @typedef ChangeStreamOptions - * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. - * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. - * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. - * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. - * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. - * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - */ - -/** - * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. - * @class ChangeStream - * @since 3.0.0 - * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream - * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents - * @param {ChangeStreamOptions} [options] Optional settings - * @fires ChangeStream#close - * @fires ChangeStream#change - * @fires ChangeStream#end - * @fires ChangeStream#error - * @fires ChangeStream#resumeTokenChanged - * @return {ChangeStream} a ChangeStream instance. - */ -class ChangeStream extends EventEmitter { - constructor(parent, pipeline, options) { - super(); - const Collection = require('./collection'); - const Db = require('./db'); - const MongoClient = require('./mongo_client'); - - this.pipeline = pipeline || []; - this.options = options || {}; - - this.parent = parent; - this.namespace = parent.s.namespace; - if (parent instanceof Collection) { - this.type = CHANGE_DOMAIN_TYPES.COLLECTION; - this.topology = parent.s.db.serverConfig; - } else if (parent instanceof Db) { - this.type = CHANGE_DOMAIN_TYPES.DATABASE; - this.topology = parent.serverConfig; - } else if (parent instanceof MongoClient) { - this.type = CHANGE_DOMAIN_TYPES.CLUSTER; - this.topology = parent.topology; - } else { - throw new TypeError( - 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' - ); - } - - this.promiseLibrary = parent.s.promiseLibrary; - if (!this.options.readPreference && parent.s.readPreference) { - this.options.readPreference = parent.s.readPreference; - } - - this[kResumeQueue] = new Denque(); - - // Create contained Change Stream cursor - this.cursor = createChangeStreamCursor(this, options); - - this.closed = false; - - // Listen for any `change` listeners being added to ChangeStream - this.on('newListener', eventName => { - if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { - this.cursor.on('data', change => processNewChange(this, change)); - } - }); - - // Listen for all `change` listeners being removed from ChangeStream - this.on('removeListener', eventName => { - if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { - this.cursor.removeAllListeners('data'); - } - }); - } - - /** - * @property {ResumeToken} resumeToken - * The cached resume token that will be used to resume - * after the most recently returned change. - */ - get resumeToken() { - return this.cursor.resumeToken; - } - - /** - * Check if there is any document still available in the Change Stream - * @function ChangeStream.prototype.hasNext - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @returns {Promise|void} returns Promise if no callback passed - */ - hasNext(callback) { - return maybePromise(this.parent, callback, cb => { - getCursor(this, (err, cursor) => { - if (err) return cb(err); // failed to resume, raise an error - cursor.hasNext(cb); - }); - }); - } - - /** - * Get the next available document from the Change Stream, returns null if no more documents are available. - * @function ChangeStream.prototype.next - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @returns {Promise|void} returns Promise if no callback passed - */ - next(callback) { - return maybePromise(this.parent, callback, cb => { - getCursor(this, (err, cursor) => { - if (err) return cb(err); // failed to resume, raise an error - cursor.next((error, change) => { - if (error) { - this[kResumeQueue].push(() => this.next(cb)); - processError(this, error, cb); - return; - } - processNewChange(this, change, cb); - }); - }); - }); - } - - /** - * Is the change stream closed - * @method ChangeStream.prototype.isClosed - * @return {boolean} - */ - isClosed() { - return this.closed || (this.cursor && this.cursor.isClosed()); - } - - /** - * Close the Change Stream - * @method ChangeStream.prototype.close - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(callback) { - return maybePromise(this.parent, callback, cb => { - if (this.closed) return cb(); - - // flag the change stream as explicitly closed - this.closed = true; - - if (!this.cursor) return cb(); - - // Tidy up the existing cursor - const cursor = this.cursor; - - return cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - this.cursor = undefined; - - return cb(err); - }); - }); - } - - /** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @method - * @param {Writable} destination The destination for writing data - * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} - * @return {null} - */ - pipe(destination, options) { - if (!this.pipeDestinations) { - this.pipeDestinations = []; - } - this.pipeDestinations.push(destination); - return this.cursor.pipe(destination, options); - } - - /** - * This method will remove the hooks set up for a previous pipe() call. - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - unpipe(destination) { - if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { - this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); - } - return this.cursor.unpipe(destination); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ - stream(options) { - this.streamOptions = options; - return this.cursor.stream(options); - } - - /** - * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @return {null} - */ - pause() { - return this.cursor.pause(); - } - - /** - * This method will cause the readable stream to resume emitting data events. - * @return {null} - */ - resume() { - return this.cursor.resume(); - } -} - -class ChangeStreamCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - - options = options || {}; - this._resumeToken = null; - this.startAtOperationTime = options.startAtOperationTime; - - if (options.startAfter) { - this.resumeToken = options.startAfter; - } else if (options.resumeAfter) { - this.resumeToken = options.resumeAfter; - } - } - - set resumeToken(token) { - this._resumeToken = token; - this.emit('resumeTokenChanged', token); - } - - get resumeToken() { - return this._resumeToken; - } - - get resumeOptions() { - const result = {}; - for (const optionName of CURSOR_OPTIONS) { - if (this.options[optionName]) result[optionName] = this.options[optionName]; - } - - if (this.resumeToken || this.startAtOperationTime) { - ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); - - if (this.resumeToken) { - const resumeKey = - this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter'; - result[resumeKey] = this.resumeToken; - } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { - result.startAtOperationTime = this.startAtOperationTime; - } - } - - return result; - } - - cacheResumeToken(resumeToken) { - if (this.bufferedCount() === 0 && this.cursorState.postBatchResumeToken) { - this.resumeToken = this.cursorState.postBatchResumeToken; - } else { - this.resumeToken = resumeToken; - } - this.hasReceived = true; - } - - _processBatch(batchName, response) { - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor[batchName].length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - } - - _initializeCursor(callback) { - super._initializeCursor((err, result) => { - if (err || result == null) { - callback(err, result); - return; - } - - const response = result.documents[0]; - - if ( - this.startAtOperationTime == null && - this.resumeAfter == null && - this.startAfter == null && - maxWireVersion(this.server) >= 7 - ) { - this.startAtOperationTime = response.operationTime; - } - - this._processBatch('firstBatch', response); - - this.emit('init', result); - this.emit('response'); - callback(err, result); - }); - } - - _getMore(callback) { - super._getMore((err, response) => { - if (err) { - callback(err); - return; - } - - this._processBatch('nextBatch', response); - - this.emit('more', response); - this.emit('response'); - callback(err, response); - }); - } -} - -/** - * @event ChangeStreamCursor#response - * internal event DO NOT USE - * @ignore - */ - -// Create a new change stream cursor based on self's configuration -function createChangeStreamCursor(self, options) { - const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; - applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); - if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { - changeStreamStageOptions.allChangesForCluster = true; - } - - const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); - const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); - - const changeStreamCursor = new ChangeStreamCursor( - self.topology, - new AggregateOperation(self.parent, pipeline, options), - cursorOptions - ); - - relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); - - /** - * Fired for each new matching change in the specified namespace. Attaching a `change` - * event listener to a Change Stream will switch the stream into flowing mode. Data will - * then be passed as soon as it is available. - * - * @event ChangeStream#change - * @type {object} - */ - if (self.listenerCount('change') > 0) { - changeStreamCursor.on('data', function(change) { - processNewChange(self, change); - }); - } - - /** - * Change stream close event - * - * @event ChangeStream#close - * @type {null} - */ - - /** - * Change stream end event - * - * @event ChangeStream#end - * @type {null} - */ - - /** - * Emitted each time the change stream stores a new resume token. - * - * @event ChangeStream#resumeTokenChanged - * @type {ResumeToken} - */ - - /** - * Fired when the stream encounters an error. - * - * @event ChangeStream#error - * @type {Error} - */ - changeStreamCursor.on('error', function(error) { - processError(self, error); - }); - - if (self.pipeDestinations) { - const cursorStream = changeStreamCursor.stream(self.streamOptions); - for (let pipeDestination of self.pipeDestinations) { - cursorStream.pipe(pipeDestination); - } - } - - return changeStreamCursor; -} - -function applyKnownOptions(target, source, optionNames) { - optionNames.forEach(name => { - if (source[name]) { - target[name] = source[name]; - } - }); - - return target; -} - -// This method performs a basic server selection loop, satisfying the requirements of -// ChangeStream resumability until the new SDAM layer can be used. -const SELECTION_TIMEOUT = 30000; -function waitForTopologyConnected(topology, options, callback) { - setTimeout(() => { - if (options && options.start == null) { - options.start = now(); - } - - const start = options.start || now(); - const timeout = options.timeout || SELECTION_TIMEOUT; - const readPreference = options.readPreference; - if (topology.isConnected({ readPreference })) { - return callback(); - } - - if (calculateDurationInMs(start) > timeout) { - return callback(new MongoError('Timed out waiting for connection')); - } - - waitForTopologyConnected(topology, options, callback); - }, 500); // this is an arbitrary wait time to allow SDAM to transition -} - -function processNewChange(changeStream, change, callback) { - const cursor = changeStream.cursor; - - // a null change means the cursor has been notified, implicitly closing the change stream - if (change == null) { - changeStream.closed = true; - } - - if (changeStream.closed) { - if (callback) callback(new MongoError('ChangeStream is closed')); - return; - } - - if (change && !change._id) { - const noResumeTokenError = new Error( - 'A change stream document has been received that lacks a resume token (_id).' - ); - - if (!callback) return changeStream.emit('error', noResumeTokenError); - return callback(noResumeTokenError); - } - - // cache the resume token - cursor.cacheResumeToken(change._id); - - // wipe the startAtOperationTime if there was one so that there won't be a conflict - // between resumeToken and startAtOperationTime if we need to reconnect the cursor - changeStream.options.startAtOperationTime = undefined; - - // Return the change - if (!callback) return changeStream.emit('change', change); - return callback(undefined, change); -} - -function processError(changeStream, error, callback) { - const topology = changeStream.topology; - const cursor = changeStream.cursor; - - // If the change stream has been closed explictly, do not process error. - if (changeStream.closed) { - if (callback) callback(new MongoError('ChangeStream is closed')); - return; - } - - // if the resume succeeds, continue with the new cursor - function resumeWithCursor(newCursor) { - changeStream.cursor = newCursor; - processResumeQueue(changeStream); - } - - // otherwise, raise an error and close the change stream - function unresumableError(err) { - if (!callback) { - changeStream.emit('error', err); - changeStream.emit('close'); - } - processResumeQueue(changeStream, err); - changeStream.closed = true; - } - - if (cursor && isResumableError(error, maxWireVersion(cursor.server))) { - changeStream.cursor = undefined; - - // stop listening to all events from old cursor - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - - // close internal cursor, ignore errors - cursor.close(); - - waitForTopologyConnected(topology, { readPreference: cursor.options.readPreference }, err => { - // if the topology can't reconnect, close the stream - if (err) return unresumableError(err); - - // create a new cursor, preserving the old cursor's options - const newCursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - - // attempt to continue in emitter mode - if (!callback) return resumeWithCursor(newCursor); - - // attempt to continue in iterator mode - newCursor.hasNext(err => { - // if there's an error immediately after resuming, close the stream - if (err) return unresumableError(err); - resumeWithCursor(newCursor); - }); - }); - return; - } - - if (!callback) return changeStream.emit('error', error); - return callback(error); -} - -/** - * Safely provides a cursor across resume attempts - * - * @param {ChangeStream} changeStream the parent ChangeStream - * @param {function} callback gets the cursor or error - * @param {ChangeStreamCursor} [oldCursor] when resuming from an error, carry over options from previous cursor - */ -function getCursor(changeStream, callback) { - if (changeStream.isClosed()) { - callback(new MongoError('ChangeStream is closed.')); - return; - } - - // if a cursor exists and it is open, return it - if (changeStream.cursor) { - callback(undefined, changeStream.cursor); - return; - } - - // no cursor, queue callback until topology reconnects - changeStream[kResumeQueue].push(callback); -} - -/** - * Drain the resume queue when a new has become available - * - * @param {ChangeStream} changeStream the parent ChangeStream - * @param {ChangeStreamCursor?} changeStream.cursor the new cursor - * @param {Error} [err] error getting a new cursor - */ -function processResumeQueue(changeStream, err) { - while (changeStream[kResumeQueue].length) { - const request = changeStream[kResumeQueue].pop(); - if (changeStream.isClosed() && !err) { - request(new MongoError('Change Stream is not open.')); - return; - } - request(err, changeStream.cursor); - } -} - -/** - * The callback format for results - * @callback ChangeStream~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -module.exports = ChangeStream; diff --git a/reverse_engineering/node_modules/mongodb/lib/cmap/connection.js b/reverse_engineering/node_modules/mongodb/lib/cmap/connection.js deleted file mode 100644 index 13e0766..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/cmap/connection.js +++ /dev/null @@ -1,416 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const MessageStream = require('./message_stream'); -const MongoError = require('../core/error').MongoError; -const MongoNetworkError = require('../core/error').MongoNetworkError; -const MongoNetworkTimeoutError = require('../core/error').MongoNetworkTimeoutError; -const MongoWriteConcernError = require('../core/error').MongoWriteConcernError; -const CommandResult = require('../core/connection/command_result'); -const StreamDescription = require('./stream_description').StreamDescription; -const wp = require('../core/wireprotocol'); -const apm = require('../core/connection/apm'); -const updateSessionFromResponse = require('../core/sessions').updateSessionFromResponse; -const uuidV4 = require('../core/utils').uuidV4; -const now = require('../utils').now; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -const kStream = Symbol('stream'); -const kQueue = Symbol('queue'); -const kMessageStream = Symbol('messageStream'); -const kGeneration = Symbol('generation'); -const kLastUseTime = Symbol('lastUseTime'); -const kClusterTime = Symbol('clusterTime'); -const kDescription = Symbol('description'); -const kIsMaster = Symbol('ismaster'); -const kAutoEncrypter = Symbol('autoEncrypter'); - -class Connection extends EventEmitter { - constructor(stream, options) { - super(options); - - this.id = options.id; - this.address = streamIdentifier(stream); - this.bson = options.bson; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 0; - this.host = options.host || 'localhost'; - this.port = options.port || 27017; - this.monitorCommands = - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false; - this.serverApi = options.serverApi; - - this.closed = false; - this.destroyed = false; - - this[kDescription] = new StreamDescription(this.address, options); - this[kGeneration] = options.generation; - this[kLastUseTime] = now(); - - // retain a reference to an `AutoEncrypter` if present - if (options.autoEncrypter) { - this[kAutoEncrypter] = options.autoEncrypter; - } - - // setup parser stream and message handling - this[kQueue] = new Map(); - this[kMessageStream] = new MessageStream(options); - this[kMessageStream].on('message', messageHandler(this)); - this[kStream] = stream; - stream.on('error', () => { - /* ignore errors, listen to `close` instead */ - }); - - this[kMessageStream].on('error', error => this.handleIssue({ destroy: error })); - stream.on('close', () => this.handleIssue({ isClose: true })); - stream.on('timeout', () => this.handleIssue({ isTimeout: true, destroy: true })); - - // hook the message stream up to the passed in stream - stream.pipe(this[kMessageStream]); - this[kMessageStream].pipe(stream); - } - - get description() { - return this[kDescription]; - } - - get ismaster() { - return this[kIsMaster]; - } - - // the `connect` method stores the result of the handshake ismaster on the connection - set ismaster(response) { - this[kDescription].receiveResponse(response); - - // TODO: remove this, and only use the `StreamDescription` in the future - this[kIsMaster] = response; - } - - get generation() { - return this[kGeneration] || 0; - } - - get idleTime() { - return calculateDurationInMs(this[kLastUseTime]); - } - - get clusterTime() { - return this[kClusterTime]; - } - - get stream() { - return this[kStream]; - } - - markAvailable() { - this[kLastUseTime] = now(); - } - - /** - * @param {{ isTimeout?: boolean; isClose?: boolean; destroy?: boolean | Error }} issue - */ - handleIssue(issue) { - if (this.closed) { - return; - } - - if (issue.destroy) { - this[kStream].destroy(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); - } - - this.closed = true; - - for (const idAndOp of this[kQueue]) { - const op = idAndOp[1]; - if (issue.isTimeout) { - op.cb( - new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, { - beforeHandshake: this.ismaster == null - }) - ); - } else if (issue.isClose) { - op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`)); - } else { - op.cb(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); - } - } - - this[kQueue].clear(); - this.emit('close'); - } - - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - if (this[kStream] == null || this.destroyed) { - this.destroyed = true; - if (typeof callback === 'function') { - callback(); - } - - return; - } - - if (options.force) { - this[kStream].destroy(); - this.destroyed = true; - if (typeof callback === 'function') { - callback(); - } - - return; - } - - this[kStream].end(err => { - this.destroyed = true; - if (typeof callback === 'function') { - callback(err); - } - }); - } - - applyApiVersion(options) { - if (this.serverApi) { - options.serverApi = this.serverApi; - } - return options; - } - - // Wire protocol methods - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - wp.command(makeServerTrampoline(this), ns, cmd, this.applyApiVersion(options), callback); - } - - query(ns, cmd, cursorState, options, callback) { - wp.query( - makeServerTrampoline(this), - ns, - cmd, - cursorState, - this.applyApiVersion(options), - callback - ); - } - - getMore(ns, cursorState, batchSize, options, callback) { - wp.getMore( - makeServerTrampoline(this), - ns, - cursorState, - batchSize, - this.applyApiVersion(options), - callback - ); - } - - killCursors(ns, cursorState, callback) { - wp.killCursors(makeServerTrampoline(this), ns, cursorState, this.applyApiVersion({}), callback); - } - - insert(ns, ops, options, callback) { - wp.insert(makeServerTrampoline(this), ns, ops, this.applyApiVersion(options), callback); - } - - update(ns, ops, options, callback) { - wp.update(makeServerTrampoline(this), ns, ops, this.applyApiVersion(options), callback); - } - - remove(ns, ops, options, callback) { - wp.remove(makeServerTrampoline(this), ns, ops, this.applyApiVersion(options), callback); - } -} - -/// This lets us emulate a legacy `Server` instance so we can work with the existing wire -/// protocol methods. Eventually, the operation executor will return a `Connection` to execute -/// against. -function makeServerTrampoline(connection) { - const server = { - description: connection.description, - clusterTime: connection[kClusterTime], - s: { - bson: connection.bson, - pool: { write: write.bind(connection), isConnected: () => true } - } - }; - - if (connection[kAutoEncrypter]) { - server.autoEncrypter = connection[kAutoEncrypter]; - } - - return server; -} - -function messageHandler(conn) { - return function messageHandler(message) { - // always emit the message, in case we are streaming - conn.emit('message', message); - if (!conn[kQueue].has(message.responseTo)) { - return; - } - - const operationDescription = conn[kQueue].get(message.responseTo); - const callback = operationDescription.cb; - - // SERVER-45775: For exhaust responses we should be able to use the same requestId to - // track response, however the server currently synthetically produces remote requests - // making the `responseTo` change on each response - conn[kQueue].delete(message.responseTo); - if (message.moreToCome) { - // requeue the callback for next synthetic request - conn[kQueue].set(message.requestId, operationDescription); - } else if (operationDescription.socketTimeoutOverride) { - conn[kStream].setTimeout(conn.socketTimeout); - } - - try { - // Pass in the entire description because it has BSON parsing options - message.parse(operationDescription); - } catch (err) { - callback(new MongoError(err)); - return; - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = operationDescription.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (document.$clusterTime) { - conn[kClusterTime] = document.$clusterTime; - conn.emit('clusterTimeReceived', document.$clusterTime); - } - - if (operationDescription.command) { - if (document.writeConcernError) { - callback(new MongoWriteConcernError(document.writeConcernError, document)); - return; - } - - if (document.ok === 0 || document.$err || document.errmsg || document.code) { - callback(new MongoError(document)); - return; - } - } - } - - // NODE-2382: reenable in our glorious non-leaky abstraction future - // callback(null, operationDescription.fullResult ? message : message.documents[0]); - - callback( - undefined, - new CommandResult( - operationDescription.fullResult ? message : message.documents[0], - conn, - message - ) - ); - }; -} - -function streamIdentifier(stream) { - if (typeof stream.address === 'function') { - return `${stream.remoteAddress}:${stream.remotePort}`; - } - - return uuidV4().toString('hex'); -} - -// Not meant to be called directly, the wire protocol methods call this assuming it is a `Pool` instance -function write(command, options, callback) { - if (typeof options === 'function') { - callback = options; - } - - options = options || {}; - const operationDescription = { - requestId: command.requestId, - cb: callback, - session: options.session, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, - noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, - documentsReturnedIn: options.documentsReturnedIn, - command: !!options.command, - - // for BSON parsing - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, - raw: typeof options.raw === 'boolean' ? options.raw : false - }; - - if (this[kDescription] && this[kDescription].compressor) { - operationDescription.agreedCompressor = this[kDescription].compressor; - - if (this[kDescription].zlibCompressionLevel) { - operationDescription.zlibCompressionLevel = this[kDescription].zlibCompressionLevel; - } - } - - if (typeof options.socketTimeout === 'number') { - operationDescription.socketTimeoutOverride = true; - this[kStream].setTimeout(options.socketTimeout); - } - - // if command monitoring is enabled we need to modify the callback here - if (this.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operationDescription.started = now(); - operationDescription.cb = (err, reply) => { - if (err) { - this.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operationDescription.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - this.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operationDescription.started) - ); - } else { - this.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operationDescription.started) - ); - } - } - - if (typeof callback === 'function') { - callback(err, reply); - } - }; - } - - if (!operationDescription.noResponse) { - this[kQueue].set(operationDescription.requestId, operationDescription); - } - - try { - this[kMessageStream].writeCommand(command, operationDescription); - } catch (e) { - if (!operationDescription.noResponse) { - this[kQueue].delete(operationDescription.requestId); - operationDescription.cb(e); - return; - } - } - - if (operationDescription.noResponse) { - operationDescription.cb(); - } -} - -module.exports = { - Connection -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/cmap/connection_pool.js b/reverse_engineering/node_modules/mongodb/lib/cmap/connection_pool.js deleted file mode 100644 index 7f513e6..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/cmap/connection_pool.js +++ /dev/null @@ -1,593 +0,0 @@ -'use strict'; - -const Denque = require('denque'); -const EventEmitter = require('events').EventEmitter; -const Logger = require('../core/connection/logger'); -const makeCounter = require('../utils').makeCounter; -const MongoError = require('../core/error').MongoError; -const Connection = require('./connection').Connection; -const eachAsync = require('../core/utils').eachAsync; -const connect = require('../core/connection/connect'); -const relayEvents = require('../core/utils').relayEvents; - -const errors = require('./errors'); -const PoolClosedError = errors.PoolClosedError; -const WaitQueueTimeoutError = errors.WaitQueueTimeoutError; - -const events = require('./events'); -const ConnectionPoolCreatedEvent = events.ConnectionPoolCreatedEvent; -const ConnectionPoolClosedEvent = events.ConnectionPoolClosedEvent; -const ConnectionCreatedEvent = events.ConnectionCreatedEvent; -const ConnectionReadyEvent = events.ConnectionReadyEvent; -const ConnectionClosedEvent = events.ConnectionClosedEvent; -const ConnectionCheckOutStartedEvent = events.ConnectionCheckOutStartedEvent; -const ConnectionCheckOutFailedEvent = events.ConnectionCheckOutFailedEvent; -const ConnectionCheckedOutEvent = events.ConnectionCheckedOutEvent; -const ConnectionCheckedInEvent = events.ConnectionCheckedInEvent; -const ConnectionPoolClearedEvent = events.ConnectionPoolClearedEvent; - -const kLogger = Symbol('logger'); -const kConnections = Symbol('connections'); -const kPermits = Symbol('permits'); -const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); -const kGeneration = Symbol('generation'); -const kConnectionCounter = Symbol('connectionCounter'); -const kCancellationToken = Symbol('cancellationToken'); -const kWaitQueue = Symbol('waitQueue'); -const kCancelled = Symbol('cancelled'); - -const VALID_POOL_OPTIONS = new Set([ - // `connect` options - 'ssl', - 'bson', - 'connectionType', - 'serverApi', - 'monitorCommands', - 'socketTimeout', - 'credentials', - 'compression', - - // node Net options - 'host', - 'port', - 'localAddress', - 'localPort', - 'family', - 'hints', - 'lookup', - 'path', - - // node TLS options - 'ca', - 'cert', - 'sigalgs', - 'ciphers', - 'clientCertEngine', - 'crl', - 'dhparam', - 'ecdhCurve', - 'honorCipherOrder', - 'key', - 'privateKeyEngine', - 'privateKeyIdentifier', - 'maxVersion', - 'minVersion', - 'passphrase', - 'pfx', - 'secureOptions', - 'secureProtocol', - 'sessionIdContext', - 'allowHalfOpen', - 'rejectUnauthorized', - 'pskCallback', - 'ALPNProtocols', - 'servername', - 'checkServerIdentity', - 'session', - 'minDHSize', - 'secureContext', - - // spec options - 'maxPoolSize', - 'minPoolSize', - 'maxIdleTimeMS', - 'waitQueueTimeoutMS' -]); - -function resolveOptions(options, defaults) { - const newOptions = Array.from(VALID_POOL_OPTIONS).reduce((obj, key) => { - if (Object.prototype.hasOwnProperty.call(options, key)) { - obj[key] = options[key]; - } - - return obj; - }, {}); - - return Object.freeze(Object.assign({}, defaults, newOptions)); -} - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} ConnectionPoolOptions - * @property - * @property {string} [host] The host to connect to - * @property {number} [port] The port to connect to - * @property {bson} [bson] The BSON instance to use for new connections - * @property {number} [maxPoolSize=100] The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. - * @property {number} [minPoolSize=0] The minimum number of connections that MUST exist at any moment in a single connection pool. - * @property {number} [maxIdleTimeMS] The maximum amount of time a connection should remain idle in the connection pool before being marked idle. - * @property {number} [waitQueueTimeoutMS=0] The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. - */ - -/** - * A pool of connections which dynamically resizes, and emit events related to pool activity - * - * @property {number} generation An integer representing the SDAM generation of the pool - * @property {number} totalConnectionCount An integer expressing how many total connections (active + in use) the pool currently has - * @property {number} availableConnectionCount An integer expressing how many connections are currently available in the pool. - * @property {string} address The address of the endpoint the pool is connected to - * - * @emits ConnectionPool#connectionPoolCreated - * @emits ConnectionPool#connectionPoolClosed - * @emits ConnectionPool#connectionCreated - * @emits ConnectionPool#connectionReady - * @emits ConnectionPool#connectionClosed - * @emits ConnectionPool#connectionCheckOutStarted - * @emits ConnectionPool#connectionCheckOutFailed - * @emits ConnectionPool#connectionCheckedOut - * @emits ConnectionPool#connectionCheckedIn - * @emits ConnectionPool#connectionPoolCleared - */ -class ConnectionPool extends EventEmitter { - /** - * Create a new Connection Pool - * - * @param {ConnectionPoolOptions} options - */ - constructor(options) { - super(); - options = options || {}; - - this.closed = false; - this.options = resolveOptions(options, { - connectionType: Connection, - maxPoolSize: typeof options.maxPoolSize === 'number' ? options.maxPoolSize : 100, - minPoolSize: typeof options.minPoolSize === 'number' ? options.minPoolSize : 0, - maxIdleTimeMS: typeof options.maxIdleTimeMS === 'number' ? options.maxIdleTimeMS : 0, - waitQueueTimeoutMS: - typeof options.waitQueueTimeoutMS === 'number' ? options.waitQueueTimeoutMS : 0, - autoEncrypter: options.autoEncrypter, - metadata: options.metadata, - useUnifiedTopology: options.useUnifiedTopology - }); - - if (options.minSize > options.maxSize) { - throw new TypeError( - 'Connection pool minimum size must not be greater than maximum pool size' - ); - } - - this[kLogger] = Logger('ConnectionPool', options); - this[kConnections] = new Denque(); - this[kPermits] = this.options.maxPoolSize; - this[kMinPoolSizeTimer] = undefined; - this[kGeneration] = 0; - this[kConnectionCounter] = makeCounter(1); - this[kCancellationToken] = new EventEmitter(); - this[kCancellationToken].setMaxListeners(Infinity); - this[kWaitQueue] = new Denque(); - - process.nextTick(() => { - this.emit('connectionPoolCreated', new ConnectionPoolCreatedEvent(this)); - ensureMinPoolSize(this); - }); - } - - get address() { - return `${this.options.host}:${this.options.port}`; - } - - get generation() { - return this[kGeneration]; - } - - get totalConnectionCount() { - return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]); - } - - get availableConnectionCount() { - return this[kConnections].length; - } - - get waitQueueSize() { - return this[kWaitQueue].length; - } - - /** - * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it - * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or - * explicitly destroyed by the new owner. - * - * @param {ConnectionPool~checkOutCallback} callback - */ - checkOut(callback) { - this.emit('connectionCheckOutStarted', new ConnectionCheckOutStartedEvent(this)); - - if (this.closed) { - this.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(this, 'poolClosed')); - callback(new PoolClosedError(this)); - return; - } - - const waitQueueMember = { callback }; - - const pool = this; - const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; - if (waitQueueTimeoutMS) { - waitQueueMember.timer = setTimeout(() => { - waitQueueMember[kCancelled] = true; - waitQueueMember.timer = undefined; - - pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, 'timeout')); - waitQueueMember.callback(new WaitQueueTimeoutError(pool)); - }, waitQueueTimeoutMS); - } - - this[kWaitQueue].push(waitQueueMember); - process.nextTick(() => processWaitQueue(this)); - } - - /** - * Check a connection into the pool. - * - * @param {Connection} connection The connection to check in - */ - checkIn(connection) { - const poolClosed = this.closed; - const stale = connectionIsStale(this, connection); - const willDestroy = !!(poolClosed || stale || connection.closed); - - if (!willDestroy) { - connection.markAvailable(); - this[kConnections].push(connection); - } - - this.emit('connectionCheckedIn', new ConnectionCheckedInEvent(this, connection)); - - if (willDestroy) { - const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; - destroyConnection(this, connection, reason); - } - - process.nextTick(() => processWaitQueue(this)); - } - - /** - * Clear the pool - * - * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a - * previous generation will eventually be pruned during subsequent checkouts. - */ - clear() { - this[kGeneration] += 1; - this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this)); - } - - /** - * Close the pool - * - * @param {object} [options] Optional settings - * @param {boolean} [options.force] Force close connections - * @param {Function} callback - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - } - - options = Object.assign({ force: false }, options); - if (this.closed) { - return callback(); - } - - // immediately cancel any in-flight connections - this[kCancellationToken].emit('cancel'); - - // drain the wait queue - while (this.waitQueueSize) { - const waitQueueMember = this[kWaitQueue].pop(); - clearTimeout(waitQueueMember.timer); - if (!waitQueueMember[kCancelled]) { - waitQueueMember.callback(new MongoError('connection pool closed')); - } - } - - // clear the min pool size timer - if (this[kMinPoolSizeTimer]) { - clearTimeout(this[kMinPoolSizeTimer]); - } - - // end the connection counter - if (typeof this[kConnectionCounter].return === 'function') { - this[kConnectionCounter].return(); - } - - // mark the pool as closed immediately - this.closed = true; - - eachAsync( - this[kConnections].toArray(), - (conn, cb) => { - this.emit('connectionClosed', new ConnectionClosedEvent(this, conn, 'poolClosed')); - conn.destroy(options, cb); - }, - err => { - this[kConnections].clear(); - this.emit('connectionPoolClosed', new ConnectionPoolClosedEvent(this)); - callback(err); - } - ); - } - - /** - * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda - * has completed by calling back. - * - * NOTE: please note the required signature of `fn` - * - * @param {ConnectionPool~withConnectionCallback} fn A function which operates on a managed connection - * @param {Function} callback The original callback - * @return {Promise} - */ - withConnection(fn, callback) { - this.checkOut((err, conn) => { - // don't callback with `err` here, we might want to act upon it inside `fn` - - fn(err, conn, (fnErr, result) => { - if (typeof callback === 'function') { - if (fnErr) { - callback(fnErr); - } else { - callback(undefined, result); - } - } - - if (conn) { - this.checkIn(conn); - } - }); - }); - } -} - -function ensureMinPoolSize(pool) { - if (pool.closed || pool.options.minPoolSize === 0) { - return; - } - - const minPoolSize = pool.options.minPoolSize; - for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) { - createConnection(pool); - } - - pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); -} - -function connectionIsStale(pool, connection) { - return connection.generation !== pool[kGeneration]; -} - -function connectionIsIdle(pool, connection) { - return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); -} - -function createConnection(pool, callback) { - const connectOptions = Object.assign( - { - id: pool[kConnectionCounter].next().value, - generation: pool[kGeneration] - }, - pool.options - ); - - pool[kPermits]--; - connect(connectOptions, pool[kCancellationToken], (err, connection) => { - if (err) { - pool[kPermits]++; - pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // The pool might have closed since we started trying to create a connection - if (pool.closed) { - connection.destroy({ force: true }); - return; - } - - // forward all events from the connection to the pool - relayEvents(connection, pool, [ - 'commandStarted', - 'commandFailed', - 'commandSucceeded', - 'clusterTimeReceived' - ]); - - pool.emit('connectionCreated', new ConnectionCreatedEvent(pool, connection)); - - connection.markAvailable(); - pool.emit('connectionReady', new ConnectionReadyEvent(pool, connection)); - - // if a callback has been provided, check out the connection immediately - if (typeof callback === 'function') { - callback(undefined, connection); - return; - } - - // otherwise add it to the pool for later acquisition, and try to process the wait queue - pool[kConnections].push(connection); - process.nextTick(() => processWaitQueue(pool)); - }); -} - -function destroyConnection(pool, connection, reason) { - pool.emit('connectionClosed', new ConnectionClosedEvent(pool, connection, reason)); - - // allow more connections to be created - pool[kPermits]++; - - // destroy the connection - process.nextTick(() => connection.destroy()); -} - -function processWaitQueue(pool) { - if (pool.closed) { - return; - } - - while (pool.waitQueueSize) { - const waitQueueMember = pool[kWaitQueue].peekFront(); - if (waitQueueMember[kCancelled]) { - pool[kWaitQueue].shift(); - continue; - } - - if (!pool.availableConnectionCount) { - break; - } - - const connection = pool[kConnections].shift(); - const isStale = connectionIsStale(pool, connection); - const isIdle = connectionIsIdle(pool, connection); - if (!isStale && !isIdle && !connection.closed) { - pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); - clearTimeout(waitQueueMember.timer); - pool[kWaitQueue].shift(); - waitQueueMember.callback(undefined, connection); - return; - } - - const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; - destroyConnection(pool, connection, reason); - } - - const maxPoolSize = pool.options.maxPoolSize; - if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) { - createConnection(pool, (err, connection) => { - const waitQueueMember = pool[kWaitQueue].shift(); - if (waitQueueMember == null || waitQueueMember[kCancelled]) { - if (err == null) { - pool[kConnections].push(connection); - } - - return; - } - - if (err) { - pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, err)); - } else { - pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); - } - - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(err, connection); - }); - - return; - } -} - -/** - * A callback provided to `withConnection` - * - * @callback ConnectionPool~withConnectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Connection} connection The managed connection which was checked out of the pool. - * @param {Function} callback A function to call back after connection management is complete - */ - -/** - * A callback provided to `checkOut` - * - * @callback ConnectionPool~checkOutCallback - * @param {MongoError} error An error instance representing the error during checkout - * @param {Connection} connection A connection from the pool - */ - -/** - * Emitted once when the connection pool is created - * - * @event ConnectionPool#connectionPoolCreated - * @type {PoolCreatedEvent} - */ - -/** - * Emitted once when the connection pool is closed - * - * @event ConnectionPool#connectionPoolClosed - * @type {PoolClosedEvent} - */ - -/** - * Emitted each time a connection is created - * - * @event ConnectionPool#connectionCreated - * @type {ConnectionCreatedEvent} - */ - -/** - * Emitted when a connection becomes established, and is ready to use - * - * @event ConnectionPool#connectionReady - * @type {ConnectionReadyEvent} - */ - -/** - * Emitted when a connection is closed - * - * @event ConnectionPool#connectionClosed - * @type {ConnectionClosedEvent} - */ - -/** - * Emitted when an attempt to check out a connection begins - * - * @event ConnectionPool#connectionCheckOutStarted - * @type {ConnectionCheckOutStartedEvent} - */ - -/** - * Emitted when an attempt to check out a connection fails - * - * @event ConnectionPool#connectionCheckOutFailed - * @type {ConnectionCheckOutFailedEvent} - */ - -/** - * Emitted each time a connection is successfully checked out of the connection pool - * - * @event ConnectionPool#connectionCheckedOut - * @type {ConnectionCheckedOutEvent} - */ - -/** - * Emitted each time a connection is successfully checked into the connection pool - * - * @event ConnectionPool#connectionCheckedIn - * @type {ConnectionCheckedInEvent} - */ - -/** - * Emitted each time the connection pool is cleared and it's generation incremented - * - * @event ConnectionPool#connectionPoolCleared - * @type {PoolClearedEvent} - */ - -module.exports = { - ConnectionPool -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/cmap/errors.js b/reverse_engineering/node_modules/mongodb/lib/cmap/errors.js deleted file mode 100644 index d933019..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/cmap/errors.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; -const MongoError = require('../core/error').MongoError; - -/** - * An error indicating a connection pool is closed - * - * @property {string} address The address of the connection pool - * @extends MongoError - */ -class PoolClosedError extends MongoError { - constructor(pool) { - super('Attempted to check out a connection from closed connection pool'); - this.name = 'MongoPoolClosedError'; - this.address = pool.address; - } -} - -/** - * An error thrown when a request to check out a connection times out - * - * @property {string} address The address of the connection pool - * @extends MongoError - */ -class WaitQueueTimeoutError extends MongoError { - constructor(pool) { - super('Timed out while checking out a connection from connection pool'); - this.name = 'MongoWaitQueueTimeoutError'; - this.address = pool.address; - } -} - -module.exports = { - PoolClosedError, - WaitQueueTimeoutError -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/cmap/events.js b/reverse_engineering/node_modules/mongodb/lib/cmap/events.js deleted file mode 100644 index dcc8b67..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/cmap/events.js +++ /dev/null @@ -1,154 +0,0 @@ -'use strict'; - -/** - * The base class for all monitoring events published from the connection pool - * - * @property {number} time A timestamp when the event was created - * @property {string} address The address (host/port pair) of the pool - */ -class ConnectionPoolMonitoringEvent { - constructor(pool) { - this.time = new Date(); - this.address = pool.address; - } -} - -/** - * An event published when a connection pool is created - * - * @property {Object} options The options used to create this connection pool - */ -class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - this.options = pool.options; - } -} - -/** - * An event published when a connection pool is closed - */ -class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -/** - * An event published when a connection pool creates a new connection - * - * @property {number} connectionId A monotonically increasing, per-pool id for the newly created connection - */ -class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is ready for use - * - * @property {number} connectionId The id of the connection - */ -class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is closed - * - * @property {number} connectionId The id of the connection - * @property {string} reason The reason the connection was closed - */ -class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection, reason) { - super(pool); - this.connectionId = connection.id; - this.reason = reason || 'unknown'; - } -} - -/** - * An event published when a request to check a connection out begins - */ -class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -/** - * An event published when a request to check a connection out fails - * - * @property {string} reason The reason the attempt to check out failed - */ -class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, reason) { - super(pool); - this.reason = reason; - } -} - -/** - * An event published when a connection is checked out of the connection pool - * - * @property {number} connectionId The id of the connection - */ -class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is checked into the connection pool - * - * @property {number} connectionId The id of the connection - */ -class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection pool is cleared - */ -class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -const CMAP_EVENT_NAMES = [ - 'connectionPoolCreated', - 'connectionPoolClosed', - 'connectionCreated', - 'connectionReady', - 'connectionClosed', - 'connectionCheckOutStarted', - 'connectionCheckOutFailed', - 'connectionCheckedOut', - 'connectionCheckedIn', - 'connectionPoolCleared' -]; - -module.exports = { - CMAP_EVENT_NAMES, - ConnectionPoolCreatedEvent, - ConnectionPoolClosedEvent, - ConnectionCreatedEvent, - ConnectionReadyEvent, - ConnectionClosedEvent, - ConnectionCheckOutStartedEvent, - ConnectionCheckOutFailedEvent, - ConnectionCheckedOutEvent, - ConnectionCheckedInEvent, - ConnectionPoolClearedEvent -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/cmap/message_stream.js b/reverse_engineering/node_modules/mongodb/lib/cmap/message_stream.js deleted file mode 100644 index c8f458e..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/cmap/message_stream.js +++ /dev/null @@ -1,196 +0,0 @@ -'use strict'; - -const Duplex = require('stream').Duplex; -const BufferList = require('bl'); -const MongoParseError = require('../core/error').MongoParseError; -const decompress = require('../core/wireprotocol/compression').decompress; -const Response = require('../core/connection/commands').Response; -const BinMsg = require('../core/connection/msg').BinMsg; -const MongoError = require('../core/error').MongoError; -const OP_COMPRESSED = require('../core/wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../core/wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../core/wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../core/wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../core/wireprotocol/shared').opcodes; -const compress = require('../core/wireprotocol/compression').compress; -const compressorIDs = require('../core/wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../core/wireprotocol/compression').uncompressibleCommands; -const Msg = require('../core/connection/msg').Msg; - -const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; -const kBuffer = Symbol('buffer'); - -/** - * A duplex stream that is capable of reading and writing raw wire protocol messages, with - * support for optional compression - */ -class MessageStream extends Duplex { - constructor(options) { - options = options || {}; - super(options); - - this.bson = options.bson; - this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; - - this[kBuffer] = new BufferList(); - } - - _write(chunk, _, callback) { - const buffer = this[kBuffer]; - buffer.append(chunk); - - processIncomingData(this, callback); - } - - _read(/* size */) { - // NOTE: This implementation is empty because we explicitly push data to be read - // when `writeMessage` is called. - return; - } - - writeCommand(command, operationDescription) { - // TODO: agreed compressor should live in `StreamDescription` - const shouldCompress = operationDescription && !!operationDescription.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - const data = command.toBin(); - this.push(Array.isArray(data) ? Buffer.concat(data) : data); - return; - } - - // otherwise, compress the message - const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { - if (err) { - operationDescription.cb(err, null); - return; - } - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[operationDescription.agreedCompressor], 8); // compressorID - - this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); - }); - } -} - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return !uncompressibleCommands.has(commandName); -} - -function processIncomingData(stream, callback) { - const buffer = stream[kBuffer]; - if (buffer.length < 4) { - callback(); - return; - } - - const sizeOfMessage = buffer.readInt32LE(0); - if (sizeOfMessage < 0) { - callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); - return; - } - - if (sizeOfMessage > stream.maxBsonMessageSize) { - callback( - new MongoParseError( - `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` - ) - ); - return; - } - - if (sizeOfMessage > buffer.length) { - callback(); - return; - } - - const message = buffer.slice(0, sizeOfMessage); - buffer.consume(sizeOfMessage); - - const messageHeader = { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; - - let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; - const responseOptions = stream.responseOptions; - if (messageHeader.opCode !== OP_COMPRESSED) { - const messageBody = message.slice(MESSAGE_HEADER_SIZE); - stream.emit( - 'message', - new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) - ); - - if (buffer.length >= 4) { - processIncomingData(stream, callback); - } else { - callback(); - } - - return; - } - - messageHeader.fromCompressed = true; - messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); - messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); - const compressorID = message[MESSAGE_HEADER_SIZE + 8]; - const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); - - // recalculate based on wrapped opcode - ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; - - decompress(compressorID, compressedBuffer, (err, messageBody) => { - if (err) { - callback(err); - return; - } - - if (messageBody.length !== messageHeader.length) { - callback( - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - stream.emit( - 'message', - new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) - ); - - if (buffer.length >= 4) { - processIncomingData(stream, callback); - } else { - callback(); - } - }); -} - -module.exports = MessageStream; diff --git a/reverse_engineering/node_modules/mongodb/lib/cmap/stream_description.js b/reverse_engineering/node_modules/mongodb/lib/cmap/stream_description.js deleted file mode 100644 index e806a5f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/cmap/stream_description.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; -const parseServerType = require('../core/sdam/server_description').parseServerType; - -const RESPONSE_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - '__nodejs_mock_server__' -]; - -class StreamDescription { - constructor(address, options) { - this.address = address; - this.type = parseServerType(null); - this.minWireVersion = undefined; - this.maxWireVersion = undefined; - this.maxBsonObjectSize = 16777216; - this.maxMessageSizeBytes = 48000000; - this.maxWriteBatchSize = 100000; - this.compressors = - options && options.compression && Array.isArray(options.compression.compressors) - ? options.compression.compressors - : []; - } - - receiveResponse(response) { - this.type = parseServerType(response); - - RESPONSE_FIELDS.forEach(field => { - if (typeof response[field] !== 'undefined') { - this[field] = response[field]; - } - }); - - if (response.compression) { - this.compressor = this.compressors.filter(c => response.compression.indexOf(c) !== -1)[0]; - } - } -} - -module.exports = { - StreamDescription -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/collection.js b/reverse_engineering/node_modules/mongodb/lib/collection.js deleted file mode 100644 index 4145cdc..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,2249 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const emitWarningOnce = require('./utils').emitWarningOnce; -const checkCollectionName = require('./utils').checkCollectionName; -const ObjectID = require('./core').BSON.ObjectID; -const MongoError = require('./core').MongoError; -const normalizeHintField = require('./utils').normalizeHintField; -const decorateCommand = require('./utils').decorateCommand; -const decorateWithCollation = require('./utils').decorateWithCollation; -const decorateWithReadConcern = require('./utils').decorateWithReadConcern; -const formattedOrderClause = require('./utils').formattedOrderClause; -const ReadPreference = require('./core').ReadPreference; -const unordered = require('./bulk/unordered'); -const ordered = require('./bulk/ordered'); -const ChangeStream = require('./change_stream'); -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const AggregationCursor = require('./aggregation_cursor'); -const CommandCursor = require('./command_cursor'); - -// Operations -const ensureIndex = require('./operations/collection_ops').ensureIndex; -const group = require('./operations/collection_ops').group; -const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; -const removeDocuments = require('./operations/common_functions').removeDocuments; -const save = require('./operations/collection_ops').save; -const updateDocuments = require('./operations/common_functions').updateDocuments; - -const AggregateOperation = require('./operations/aggregate'); -const BulkWriteOperation = require('./operations/bulk_write'); -const CountDocumentsOperation = require('./operations/count_documents'); -const CreateIndexesOperation = require('./operations/create_indexes'); -const DeleteManyOperation = require('./operations/delete_many'); -const DeleteOneOperation = require('./operations/delete_one'); -const DistinctOperation = require('./operations/distinct'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropIndexOperation = require('./operations/drop_index'); -const DropIndexesOperation = require('./operations/drop_indexes'); -const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); -const FindOperation = require('./operations/find'); -const FindOneOperation = require('./operations/find_one'); -const FindAndModifyOperation = require('./operations/find_and_modify'); -const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); -const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); -const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); -const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); -const IndexesOperation = require('./operations/indexes'); -const IndexExistsOperation = require('./operations/index_exists'); -const IndexInformationOperation = require('./operations/index_information'); -const InsertManyOperation = require('./operations/insert_many'); -const InsertOneOperation = require('./operations/insert_one'); -const IsCappedOperation = require('./operations/is_capped'); -const ListIndexesOperation = require('./operations/list_indexes'); -const MapReduceOperation = require('./operations/map_reduce'); -const OptionsOperation = require('./operations/options_operation'); -const RenameOperation = require('./operations/rename'); -const ReIndexOperation = require('./operations/re_index'); -const ReplaceOneOperation = require('./operations/replace_one'); -const StatsOperation = require('./operations/stats'); -const UpdateManyOperation = require('./operations/update_many'); -const UpdateOneOperation = require('./operations/update_one'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection - * allowing for insert/update/remove/find and other command operation on that MongoDB collection. - * - * **COLLECTION Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - */ - -const mergeKeys = ['ignoreUndefined']; - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - */ -function Collection(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - - // Unpack variables - const internalHint = null; - const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - const serializeFunctions = - options == null || options.serializeFunctions == null - ? db.s.options.serializeFunctions - : options.serializeFunctions; - const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; - const promoteLongs = - options == null || options.promoteLongs == null - ? db.s.options.promoteLongs - : options.promoteLongs; - const promoteValues = - options == null || options.promoteValues == null - ? db.s.options.promoteValues - : options.promoteValues; - const promoteBuffers = - options == null || options.promoteBuffers == null - ? db.s.options.promoteBuffers - : options.promoteBuffers; - const bsonRegExp = - options == null || options.bsonRegExp == null ? db.s.options.bsonRegExp : options.bsonRegExp; - const collectionHint = null; - - const namespace = new MongoDBNamespace(dbName, name); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Set custom primary key factory if provided - pkFactory = pkFactory == null ? ObjectID : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory, - // Db - db: db, - // Topology - topology: topology, - // Options - options: options, - // Namespace - namespace: namespace, - // Read preference - readPreference: ReadPreference.fromOptions(options), - // SlaveOK - slaveOk: slaveOk, - // Serialize functions - serializeFunctions: serializeFunctions, - // Raw - raw: raw, - // promoteLongs - promoteLongs: promoteLongs, - // promoteValues - promoteValues: promoteValues, - // promoteBuffers - promoteBuffers: promoteBuffers, - // bsonRegExp - bsonRegExp: bsonRegExp, - // internalHint - internalHint: internalHint, - // collectionHint - collectionHint: collectionHint, - // Promise library - promiseLibrary: promiseLibrary, - // Read Concern - readConcern: ReadConcern.fromOptions(options), - // Write Concern - writeConcern: WriteConcern.fromOptions(options) - }; -} - -/** - * The name of the database this collection belongs to - * @member {string} dbName - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'dbName', { - enumerable: true, - get: function() { - return this.s.namespace.db; - } -}); - -/** - * The name of this collection - * @member {string} collectionName - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, - get: function() { - return this.s.namespace.collection; - } -}); - -/** - * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` - * @member {string} namespace - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * The current readConcern of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {ReadConcern} [readConcern] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, - get: function() { - if (this.s.readConcern == null) { - return this.s.db.readConcern; - } - return this.s.readConcern; - } -}); - -/** - * The current readPreference of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {ReadPreference} [readPreference] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - return this.s.db.readPreference; - } - - return this.s.readPreference; - } -}); - -/** - * The current writeConcern of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {WriteConcern} [writeConcern] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable: true, - get: function() { - if (this.s.writeConcern == null) { - return this.s.db.writeConcern; - } - return this.s.writeConcern; - } -}); - -/** - * The current index hint for the collection - * @member {object} [hint] - * @memberof Collection# - */ -Object.defineProperty(Collection.prototype, 'hint', { - enumerable: true, - get: function() { - return this.s.collectionHint; - }, - set: function(v) { - this.s.collectionHint = normalizeHintField(v); - } -}); - -const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot', 'oplogReplay']; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} [query={}] The cursor query object. - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} **or** {'a': 0, 'b': 0} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {boolean} [options.awaitData=false] Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true - * @param {boolean} [options.noCursorTimeout] The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {boolean} [options.allowDiskUse] Enables writing to temporary files on the server. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - emitWarningOnce('Third parameter to `find()` must be a callback or undefined'); - } - - let selector = query; - // figuring out arguments - if (typeof callback !== 'function') { - if (typeof options === 'function') { - callback = options; - options = undefined; - } else if (options == null) { - callback = typeof selector === 'function' ? selector : undefined; - selector = typeof selector === 'object' ? selector : undefined; - } - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - const object = selector; - if (Buffer.isBuffer(object)) { - const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); - if (object_size !== object.length) { - const error = new Error( - 'query selector raw message size does not match message header size [' + - object.length + - '] != [' + - object_size + - ']' - ); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if (selector != null && selector._bsontype === 'ObjectID') { - selector = { _id: selector }; - } - - if (!options) options = {}; - - let projection = options.projection || options.fields; - - if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { - projection = projection.length - ? projection.reduce((result, field) => { - result[field] = 1; - return result; - }, {}) - : { _id: 1 }; - } - - // Make a shallow copy of options - let newOptions = Object.assign({}, options); - - // Make a shallow copy of the collection options - for (let key in this.s.options) { - if (mergeKeys.indexOf(key) !== -1) { - newOptions[key] = this.s.options[key]; - } - } - - // Unpack options - newOptions.skip = options.skip ? options.skip : 0; - newOptions.limit = options.limit ? options.limit : 0; - newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = - options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions.readPreference = ReadPreference.resolve(this, newOptions); - - // Set slave ok to true if read preference different from primary - if ( - newOptions.readPreference != null && - (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') - ) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if (selector != null && typeof selector !== 'object') { - throw MongoError.create({ message: 'query selector must be an object', driver: true }); - } - - // Build the find command - const findCommand = { - find: this.s.namespace.toString(), - limit: newOptions.limit, - skip: newOptions.skip, - query: selector - }; - - if (typeof options.allowDiskUse === 'boolean') { - findCommand.allowDiskUse = options.allowDiskUse; - } - - // Ensure we use the right await data option - if (typeof newOptions.awaitdata === 'boolean') { - newOptions.awaitData = newOptions.awaitdata; - } - - // Translate to new command option noCursorTimeout - if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = !newOptions.timeout; - - decorateCommand(findCommand, newOptions, ['session', 'collation']); - - if (projection) findCommand.fields = projection; - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; - // Set promoteLongs if available at collection level - if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') - newOptions.promoteLongs = this.s.promoteLongs; - if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') - newOptions.promoteValues = this.s.promoteValues; - if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') - newOptions.promoteBuffers = this.s.promoteBuffers; - if (newOptions.bsonRegExp == null && typeof this.s.bsonRegExp === 'boolean') - newOptions.bsonRegExp = this.s.bsonRegExp; - - // Sort options - if (findCommand.sort) { - findCommand.sort = formattedOrderClause(findCommand.sort); - } - - // Set the readConcern - decorateWithReadConcern(findCommand, this, options); - - // Decorate find command with collation options - try { - decorateWithCollation(findCommand, this, options); - } catch (err) { - if (typeof callback === 'function') return callback(err, null); - throw err; - } - - const cursor = this.s.topology.cursor( - new FindOperation(this, this.s.namespace, findCommand, newOptions), - newOptions - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; - } -); - -/** - * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object} doc Document to insert. - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const insertOneOperation = new InsertOneOperation(this, doc, options); - - return executeOperation(this.s.topology, insertOneOperation, callback); -}; - -/** - * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : { ordered: true }; - - const insertManyOperation = new InsertManyOperation(this, docs, options); - - return executeOperation(this.s.topology, insertManyOperation, callback); -}; - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {BulkWriteError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: true }; - - if (!Array.isArray(operations)) { - throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); - } - - const bulkWriteOperation = new BulkWriteOperation(this, operations, options); - - return executeOperation(this.s.topology, bulkWriteOperation, callback); -}; - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {number} result.ok Is 1 if the command executed correctly. - * @property {number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {number} result.ok Is 1 if the command executed correctly. - * @property {number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = deprecate(function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: false }; - docs = !Array.isArray(docs) ? [docs] : docs; - - if (options.keepGoing === true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - * @property {Object} message The raw msg response wrapped in an internal class - * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document in a collection - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation( - this.s.topology, - new UpdateOneOperation(this, filter, update, options), - callback - ); -}; - -/** - * Replace a document in a collection with another document - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} doc The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation( - this.s.topology, - new ReplaceOneOperation(this, filter, doc, options), - callback - ); -}; - -/** - * Update multiple documents in a collection - * @method - * @param {object} filter The Filter used to select the documents to update - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation( - this.s.topology, - new UpdateManyOperation(this, filter, update, options), - callback - ); -}; - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = deprecate(function(selector, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, updateDocuments, [ - this, - selector, - update, - options, - callback - ]); -}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for deletes - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document from a collection - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {string|object} [options.hint] optional index hint for optimizing the filter query - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteOneOperation = new DeleteOneOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteOneOperation, callback); -}; - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -/** - * Delete multiple documents from a collection - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {string|object} [options.hint] optional index hint for optimizing the filter query - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteManyOperation = new DeleteManyOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteManyOperation, callback); -}; - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = deprecate(function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, removeDocuments, [ - this, - selector, - options, - callback - ]); -}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = deprecate(function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); -}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * The callback format for an aggregation call - * @callback Collection~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOne = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - emitWarningOnce('Third parameter to `findOne()` must be a callback or undefined'); - } - - if (typeof query === 'function') (callback = query), (query = {}), (options = {}); - if (typeof options === 'function') (callback = options), (options = {}); - query = query || {}; - options = options || {}; - - const findOneOperation = new FindOneOperation(this, query, options); - - return executeOperation(this.s.topology, findOneOperation, callback); - } -); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - const renameOperation = new RenameOperation(this, newName, options); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Returns the options of the collection. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(opts, callback) { - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - const optionsOperation = new OptionsOperation(this, opts); - - return executeOperation(this.s.topology, optionsOperation, callback); -}; - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const isCappedOperation = new IsCappedOperation(this, options); - - return executeOperation(this.s.topology, isCappedOperation, callback); -}; - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|array|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * - * await collection.createIndex({ a: 1, b: -1 }); - * - * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes - * await collection.createIndex([ [c, 1], [d, -1] ]); - * - * // Equivalent to { e: 1 } - * await collection.createIndex('e'); - * - * // Equivalent to { f: 1, g: 1 } - * await collection.createIndex(['f', 'g']) - * - * // Equivalent to { h: 1, i: -1 } - * await collection.createIndex([ { h: 1 }, { i: -1 } ]); - * - * // Equivalent to { j: 1, k: -1, l: 2d } - * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const createIndexesOperation = new CreateIndexesOperation( - this, - this.collectionName, - fieldOrSpec, - options - ); - - return executeOperation(this.s.topology, createIndexesOperation, callback); -}; - -/** - * @typedef {object} Collection~IndexDefinition - * @description A definition for an index. Used by the createIndex command. - * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ - */ - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. - * - * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. - * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. - * - * @method - * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * await collection.createIndexes([ - * // Simple index on field fizz - * { - * key: { fizz: 1 }, - * } - * // wildcard index - * { - * key: { '$**': 1 } - * }, - * // named index on darmok and jalad - * { - * key: { darmok: 1, jalad: -1 } - * name: 'tanagra' - * } - * ]); - */ -Collection.prototype.createIndexes = function(indexSpecs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - options = options ? Object.assign({}, options) : {}; - - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const createIndexesOperation = new CreateIndexesOperation( - this, - this.collectionName, - indexSpecs, - options - ); - - return executeOperation(this.s.topology, createIndexesOperation, callback); -}; - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - const dropIndexOperation = new DropIndexOperation(this, indexName, options); - - return executeOperation(this.s.topology, dropIndexOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const dropIndexesOperation = new DropIndexesOperation(this, options); - - return executeOperation(this.s.topology, dropIndexesOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = deprecate( - Collection.prototype.dropIndexes, - 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' -); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @deprecated use db.command instead - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const reIndexOperation = new ReIndexOperation(this, options); - - return executeOperation(this.s.topology, reIndexOperation, callback); -}, 'collection.reIndex is deprecated. Use db.command instead.'); - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - const cursor = new CommandCursor( - this.s.topology, - new ListIndexesOperation(this, options), - options - ); - - return cursor; -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - fieldOrSpec, - options, - callback - ]); -}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexExistsOperation = new IndexExistsOperation(this, indexes, options); - - return executeOperation(this.s.topology, indexExistsOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const indexInformationOperation = new IndexInformationOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * An estimated count of matching documents in the db to a query. - * - * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents - * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. - * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * - * @method - * @param {object} [query={}] The query for the count. - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {boolean} [options.limit] The limit of documents to count. - * @param {boolean} [options.skip] The number of documents to skip for the count. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead - */ -Collection.prototype.count = deprecate(function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.topology, - new EstimatedDocumentCountOperation(this, Object.assign({ query }, options)), - callback - ); -}, 'collection.count is deprecated, and will be removed in a future version.' + - ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); - -/** - * Gets an estimate of the count of documents in a collection using collection metadata. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - */ -Collection.prototype.estimatedDocumentCount = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); - - return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); -}; - -/** - * Gets the number of documents matching the filter. - * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} - * the following query operators must be replaced: - * - * | Operator | Replacement | - * | -------- | ----------- | - * | `$where` | [`$expr`][1] | - * | `$near` | [`$geoWithin`][2] with [`$center`][3] | - * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | - * - * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ - * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - * - * @param {object} [query] the query for the count - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specifies a collation. - * @param {string|object} [options.hint] The index to use. - * @param {number} [options.limit] The maximum number of document to count. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {number} [options.skip] The number of documents to skip before counting. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ - * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - */ - -Collection.prototype.countDocuments = function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - const countDocumentsOperation = new CountDocumentsOperation(this, query, options); - - return executeOperation(this.s.topology, countDocumentsOperation, callback); -}; - -/** - * The distinct command returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} [query] The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - const queryOption = args.length ? args.shift() || {} : {}; - const optionsOption = args.length ? args.shift() || {} : {}; - - const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); - - return executeOperation(this.s.topology, distinctOperation, callback); -}; - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexesOperation = new IndexesOperation(this, options); - - return executeOperation(this.s.topology, indexesOperation, callback); -}; - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const statsOperation = new StatsOperation(this, options); - - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default even if a document was upserted unless `returnDocument` is specified as `'after'`, in which case the upserted document will be returned. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation( - this.s.topology, - new FindOneAndDeleteOperation(this, filter, options), - callback - ); -}; - -/** - * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} replacement The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string|object} [options.hint] An optional index to use for this operation - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`. - * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = deprecateOptions( - { - name: 'collection.findOneAndReplace', - deprecatedOptions: ['returnOriginal'], - optionsIndex: 2 - }, - function(filter, replacement, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation( - this.s.topology, - new FindOneAndReplaceOperation(this, filter, replacement, options), - callback - ); - } -); - -/** - * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update Update operations to be performed on the document - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string|object} [options.hint] An optional index to use for this operation - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`. - * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] An ptional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = deprecateOptions( - { - name: 'collection.findOneAndUpdate', - deprecatedOptions: ['returnOriginal'], - optionsIndex: 2 - }, - function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation( - this.s.topology, - new FindOneAndUpdateOperation(this, filter, update, options), - callback - ); - } -); - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = deprecate( - _findAndModify, - 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' -); - -/** - * @ignore - */ - -Collection.prototype._findAndModify = _findAndModify; - -function _findAndModify(query, sort, doc, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - options = Object.assign({}, options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, doc, options), - callback - ); -} - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Add the remove option - options.remove = true; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, null, options), - callback - ); -}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - if (Array.isArray(pipeline)) { - // Set up callback if one is provided - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - const args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - const opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = - opts && - (opts.readPreference || - opts.explain || - opts.cursor || - opts.out || - opts.maxTimeMS || - opts.hint || - opts.allowDiskUse) - ? args.pop() - : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. - * @method - * @since 3.0.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Collection.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = ReadPreference.resolve(this, options); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if (options.session) { - options.session = undefined; - } - - return executeLegacyOperation( - this.s.topology, - parallelCollectionScan, - [this, options, callback], - { skipSessions: true } - ); -}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance] Include results up to maxDistance from the point. - * @param {object} [options.search] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated See {@link https://docs.mongodb.com/manual/geospatial-queries/|geospatial queries docs} for current geospatial support - */ -Collection.prototype.geoHaystackSearch = deprecate(function(x, y, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); - - return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); -}, 'geoHaystackSearch is deprecated, and will be removed in a future version.'); - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. - */ -Collection.prototype.group = deprecate(function( - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback -) { - const args = Array.prototype.slice.call(arguments, 3); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if (!(typeof finalize === 'function')) { - command = finalize; - finalize = null; - } - - if ( - !Array.isArray(keys) && - keys instanceof Object && - typeof keys !== 'function' && - !(keys._bsontype === 'Code') - ) { - keys = Object.keys(keys); - } - - if (typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if (typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - return executeLegacyOperation(this.s.topology, group, [ - this, - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback - ]); -}, -'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query] Query filter object. - * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize] Finalize function. - * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - if ('function' === typeof options) (callback = options), (options = {}); - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if (null == options.out) { - throw new Error( - 'the out option parameter must be defined, see mongodb docs for possible values' - ); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); - - return executeOperation(this.s.topology, mapReduceOperation, callback); -}; - -/** - * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -}; - -/** - * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session's options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Collection.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -module.exports = Collection; diff --git a/reverse_engineering/node_modules/mongodb/lib/command_cursor.js b/reverse_engineering/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index cd0f9d7..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,269 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -class CommandCursor extends Cursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {CommandCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - if (this.cmd.cursor) { - this.cmd.cursor.batchSize = value; - } - - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ - maxTimeMS(value) { - if (this.topology.lastIsMaster().minWireVersion > 2) { - this.cmd.maxTimeMS = value; - } - - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function CommandCursor.prototype.hasNext - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = CommandCursor; diff --git a/reverse_engineering/node_modules/mongodb/lib/command_utils.js b/reverse_engineering/node_modules/mongodb/lib/command_utils.js deleted file mode 100644 index a8f52b2..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/command_utils.js +++ /dev/null @@ -1,124 +0,0 @@ -'use strict'; -const Msg = require('./core/connection/msg').Msg; -const KillCursor = require('./core/connection/commands').KillCursor; -const GetMore = require('./core/connection/commands').GetMore; -const deepCopy = require('./utils').deepCopy; - -/** Commands that we want to redact because of the sensitive nature of their contents */ -const SENSITIVE_COMMANDS = new Set([ - 'authenticate', - 'saslStart', - 'saslContinue', - 'getnonce', - 'createUser', - 'updateUser', - 'copydbgetnonce', - 'copydbsaslstart', - 'copydb' -]); - -const HELLO_COMMANDS = new Set(['hello', 'ismaster', 'isMaster']); - -const LEGACY_FIND_QUERY_MAP = { - $query: 'filter', - $orderby: 'sort', - $hint: 'hint', - $comment: 'comment', - $maxScan: 'maxScan', - $max: 'max', - $min: 'min', - $returnKey: 'returnKey', - $showDiskLoc: 'showRecordId', - $maxTimeMS: 'maxTimeMS', - $snapshot: 'snapshot' -}; - -const LEGACY_FIND_OPTIONS_MAP = { - numberToSkip: 'skip', - numberToReturn: 'batchSize', - returnFieldsSelector: 'projection' -}; - -const OP_QUERY_KEYS = [ - 'tailable', - 'oplogReplay', - 'noCursorTimeout', - 'awaitData', - 'partial', - 'exhaust' -]; - -const collectionName = command => command.ns.split('.')[1]; - -const shouldRedactCommand = (commandName, cmd) => - SENSITIVE_COMMANDS.has(commandName) || - (HELLO_COMMANDS.has(commandName) && !!cmd.speculativeAuthenticate); - -/** - * Extract the actual command from the query, possibly upconverting if it's a legacy - * format - * - * @param {Object} command the command - */ -const extractCommand = command => { - let extractedCommand; - if (command instanceof GetMore) { - extractedCommand = { - getMore: deepCopy(command.cursorId), - collection: collectionName(command), - batchSize: command.numberToReturn - }; - } else if (command instanceof KillCursor) { - extractedCommand = { - killCursors: collectionName(command), - cursors: deepCopy(command.cursorIds) - }; - } else if (command instanceof Msg) { - extractedCommand = deepCopy(command.command); - } else if (command.query && command.query.$query) { - let result; - if (command.ns === 'admin.$cmd') { - // upconvert legacy command - result = Object.assign({}, command.query.$query); - } else { - // upconvert legacy find command - result = { find: collectionName(command) }; - Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { - if (typeof command.query[key] !== 'undefined') - result[LEGACY_FIND_QUERY_MAP[key]] = deepCopy(command.query[key]); - }); - } - - Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { - if (typeof command[key] !== 'undefined') - result[LEGACY_FIND_OPTIONS_MAP[key]] = deepCopy(command[key]); - }); - - OP_QUERY_KEYS.forEach(key => { - if (command[key]) result[key] = command[key]; - }); - - if (typeof command.pre32Limit !== 'undefined') { - result.limit = command.pre32Limit; - } - - if (command.query.$explain) { - extractedCommand = { explain: result }; - } else { - extractedCommand = result; - } - } else { - extractedCommand = deepCopy(command.query || command); - } - - const commandName = Object.keys(extractedCommand)[0]; - return { - cmd: extractedCommand, - name: commandName, - shouldRedact: shouldRedactCommand(commandName, extractedCommand) - }; -}; - -module.exports = { - extractCommand -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/constants.js b/reverse_engineering/node_modules/mongodb/lib/constants.js deleted file mode 100644 index d6cc68a..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/constants.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = { - SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', - SYSTEM_INDEX_COLLECTION: 'system.indexes', - SYSTEM_PROFILE_COLLECTION: 'system.profile', - SYSTEM_USER_COLLECTION: 'system.users', - SYSTEM_COMMAND_COLLECTION: '$cmd', - SYSTEM_JS_COLLECTION: 'system.js' -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/auth_provider.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/auth_provider.js deleted file mode 100644 index a5f6e99..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/auth_provider.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -/** - * Context used during authentication - * - * @property {Connection} connection The connection to authenticate - * @property {MongoCredentials} credentials The credentials to use for authentication - * @property {object} options The options passed to the `connect` method - * @property {object?} response The response of the initial handshake - * @property {Buffer?} nonce A random nonce generated for use in an authentication conversation - */ -class AuthContext { - constructor(connection, credentials, options) { - this.connection = connection; - this.credentials = credentials; - this.options = options; - } -} - -class AuthProvider { - constructor(bson) { - this.bson = bson; - } - - /** - * Prepare the handshake document before the initial handshake. - * - * @param {object} handshakeDoc The document used for the initial handshake on a connection - * @param {AuthContext} authContext Context for authentication flow - * @param {function} callback - */ - prepare(handshakeDoc, context, callback) { - callback(undefined, handshakeDoc); - } - - /** - * Authenticate - * - * @param {AuthContext} context A shared context for authentication flow - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - auth(context, callback) { - callback(new TypeError('`auth` method must be overridden by subclass')); - } -} - -/** - * This is a result from an authentication provider - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = { AuthContext, AuthProvider }; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js deleted file mode 100644 index 92ac605..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const MongoCR = require('./mongocr'); -const X509 = require('./x509'); -const Plain = require('./plain'); -const GSSAPI = require('./gssapi'); -const ScramSHA1 = require('./scram').ScramSHA1; -const ScramSHA256 = require('./scram').ScramSHA256; -const MongoDBAWS = require('./mongodb_aws'); - -/** - * Returns the default authentication providers. - * - * @param {BSON} bson Bson definition - * @returns {Object} a mapping of auth names to auth types - */ -function defaultAuthProviders(bson) { - return { - 'mongodb-aws': new MongoDBAWS(bson), - mongocr: new MongoCR(bson), - x509: new X509(bson), - plain: new Plain(bson), - gssapi: new GSSAPI(bson), - 'scram-sha-1': new ScramSHA1(bson), - 'scram-sha-256': new ScramSHA256(bson) - }; -} - -module.exports = { defaultAuthProviders }; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/gssapi.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/gssapi.js deleted file mode 100644 index 9a6c110..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/gssapi.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; -const dns = require('dns'); - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -const MongoError = require('../error').MongoError; - -let kerberos; - -class GSSAPI extends AuthProvider { - auth(authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - if (credentials == null) return callback(new MongoError('credentials required')); - const username = credentials.username; - function externalCommand(command, cb) { - return connection.command('$external.$cmd', command, cb); - } - makeKerberosClient(authContext, (err, client) => { - if (err) return callback(err); - if (client == null) return callback(new MongoError('gssapi client missing')); - client.step('', (err, payload) => { - if (err) return callback(err); - externalCommand(saslStart(payload), (err, response) => { - if (err) return callback(err); - const result = response.result; - negotiate(client, 10, result.payload, (err, payload) => { - if (err) return callback(err); - externalCommand(saslContinue(payload, result.conversationId), (err, response) => { - if (err) return callback(err); - const result = response.result; - finalize(client, username, result.payload, (err, payload) => { - if (err) return callback(err); - externalCommand( - { - saslContinue: 1, - conversationId: result.conversationId, - payload - }, - (err, result) => { - if (err) return callback(err); - callback(undefined, result); - } - ); - }); - }); - }); - }); - }); - }); - } -} -module.exports = GSSAPI; - -function makeKerberosClient(authContext, callback) { - const host = authContext.options.host; - const port = authContext.options.port; - const credentials = authContext.credentials; - if (!host || !port || !credentials) { - return callback( - new MongoError( - `Connection must specify: ${host ? 'host' : ''}, ${port ? 'port' : ''}, ${ - credentials ? 'host' : 'credentials' - }.` - ) - ); - } - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e); - } - } - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const serviceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - performGssapiCanonicalizeHostName(host, mechanismProperties, (err, host) => { - if (err) return callback(err); - const initOptions = {}; - if (password != null) { - Object.assign(initOptions, { user: username, password: password }); - } - kerberos.initializeClient( - `${serviceName}${process.platform === 'win32' ? '/' : '@'}${host}`, - initOptions, - (err, client) => { - if (err) return callback(new MongoError(err)); - callback(null, client); - } - ); - }); -} - -function saslStart(payload) { - return { - saslStart: 1, - mechanism: 'GSSAPI', - payload, - autoAuthorize: 1 - }; -} -function saslContinue(payload, conversationId) { - return { - saslContinue: 1, - conversationId, - payload - }; -} -function negotiate(client, retries, payload, callback) { - client.step(payload, (err, response) => { - // Retries exhausted, raise error - if (err && retries === 0) return callback(err); - // Adjust number of retries and call step again - if (err) return negotiate(client, retries - 1, payload, callback); - // Return the payload - callback(undefined, response || ''); - }); -} -function finalize(client, user, payload, callback) { - // GSS Client Unwrap - client.unwrap(payload, (err, response) => { - if (err) return callback(err); - // Wrap the response - client.wrap(response || '', { user }, (err, wrapped) => { - if (err) return callback(err); - // Return the payload - callback(undefined, wrapped); - }); - }); -} -function performGssapiCanonicalizeHostName(host, mechanismProperties, callback) { - const canonicalizeHostName = - typeof mechanismProperties.gssapiCanonicalizeHostName === 'boolean' - ? mechanismProperties.gssapiCanonicalizeHostName - : false; - if (!canonicalizeHostName) return callback(undefined, host); - // Attempt to resolve the host name - dns.resolveCname(host, (err, r) => { - if (err) return callback(err); - // Get the first resolve host id - if (Array.isArray(r) && r.length > 0) { - return callback(undefined, r[0]); - } - callback(undefined, host); - }); -} diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/mongo_credentials.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/mongo_credentials.js deleted file mode 100644 index 82f0251..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/mongo_credentials.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -// Resolves the default auth mechanism according to -// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst -function getDefaultAuthMechanism(ismaster) { - if (ismaster) { - // If ismaster contains saslSupportedMechs, use scram-sha-256 - // if it is available, else scram-sha-1 - if (Array.isArray(ismaster.saslSupportedMechs)) { - return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 - ? 'scram-sha-256' - : 'scram-sha-1'; - } - - // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 - if (ismaster.maxWireVersion >= 3) { - return 'scram-sha-1'; - } - } - - // Default for wireprotocol < 3 - return 'mongocr'; -} - -/** - * A representation of the credentials used by MongoDB - * @class - * @property {string} mechanism The method used to authenticate - * @property {string} [username] The username used for authentication - * @property {string} [password] The password used for authentication - * @property {string} [source] The database that the user should authenticate against - * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms - */ -class MongoCredentials { - /** - * Creates a new MongoCredentials object - * @param {object} [options] - * @param {string} [options.username] The username used for authentication - * @param {string} [options.password] The password used for authentication - * @param {string} [options.source] The database that the user should authenticate against - * @param {string} [options.mechanism] The method used to authenticate - * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms - */ - constructor(options) { - options = options || {}; - this.username = options.username; - this.password = options.password; - this.source = options.source || options.db; - this.mechanism = options.mechanism || 'default'; - this.mechanismProperties = options.mechanismProperties || {}; - - if (/MONGODB-AWS/i.test(this.mechanism)) { - if (!this.username && process.env.AWS_ACCESS_KEY_ID) { - this.username = process.env.AWS_ACCESS_KEY_ID; - } - - if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) { - this.password = process.env.AWS_SECRET_ACCESS_KEY; - } - - if ( - this.mechanismProperties.AWS_SESSION_TOKEN == null && - process.env.AWS_SESSION_TOKEN != null - ) { - this.mechanismProperties.AWS_SESSION_TOKEN = process.env.AWS_SESSION_TOKEN; - } - } - - Object.freeze(this.mechanismProperties); - Object.freeze(this); - } - - /** - * Determines if two MongoCredentials objects are equivalent - * @param {MongoCredentials} other another MongoCredentials object - * @returns {boolean} true if the two objects are equal. - */ - equals(other) { - return ( - this.mechanism === other.mechanism && - this.username === other.username && - this.password === other.password && - this.source === other.source - ); - } - - /** - * If the authentication mechanism is set to "default", resolves the authMechanism - * based on the server version and server supported sasl mechanisms. - * - * @param {Object} [ismaster] An ismaster response from the server - * @returns {MongoCredentials} - */ - resolveAuthMechanism(ismaster) { - // If the mechanism is not "default", then it does not need to be resolved - if (/DEFAULT/i.test(this.mechanism)) { - return new MongoCredentials({ - username: this.username, - password: this.password, - source: this.source, - mechanism: getDefaultAuthMechanism(ismaster), - mechanismProperties: this.mechanismProperties - }); - } - - return this; - } -} - -module.exports = { MongoCredentials }; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/mongocr.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/mongocr.js deleted file mode 100644 index 0b1c341..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/mongocr.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const AuthProvider = require('./auth_provider').AuthProvider; - -class MongoCR extends AuthProvider { - auth(authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - const username = credentials.username; - const password = credentials.password; - const source = credentials.source; - - connection.command(`${source}.$cmd`, { getnonce: 1 }, (err, result) => { - let nonce = null; - let key = null; - - // Get nonce - if (err == null) { - const r = result.result; - nonce = r.nonce; - // Use node md5 generator - let md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - const hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password, 'utf8'); - key = md5.digest('hex'); - } - - const authenticateCommand = { - authenticate: 1, - user: username, - nonce, - key - }; - - connection.command(`${source}.$cmd`, authenticateCommand, callback); - }); - } -} - -module.exports = MongoCR; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/mongodb_aws.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/mongodb_aws.js deleted file mode 100644 index 6fcf3f3..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/mongodb_aws.js +++ /dev/null @@ -1,258 +0,0 @@ -'use strict'; -const AuthProvider = require('./auth_provider').AuthProvider; -const MongoCredentials = require('./mongo_credentials').MongoCredentials; -const MongoError = require('../error').MongoError; -const crypto = require('crypto'); -const http = require('http'); -const maxWireVersion = require('../utils').maxWireVersion; -const url = require('url'); - -let aws4; -try { - // Ensure you always wrap an optional require in the try block NODE-3199 - aws4 = require('aws4'); -} catch (e) { - // don't do anything; -} - -const ASCII_N = 110; -const AWS_RELATIVE_URI = 'http://169.254.170.2'; -const AWS_EC2_URI = 'http://169.254.169.254'; -const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; - -class MongoDBAWS extends AuthProvider { - auth(authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - - if (maxWireVersion(connection) < 9) { - callback(new MongoError('MONGODB-AWS authentication requires MongoDB version 4.4 or later')); - return; - } - - if (aws4 == null) { - callback( - new MongoError( - 'MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project' - ) - ); - - return; - } - - if (credentials.username == null) { - makeTempCredentials(credentials, (err, tempCredentials) => { - if (err) return callback(err); - - authContext.credentials = tempCredentials; - this.auth(authContext, callback); - }); - - return; - } - - const db = credentials.source; - const bson = this.bson; - - const accessKeyId = credentials.username; - const secretAccessKey = credentials.password; - const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; - - // If all three defined, include sessionToken, else include username and pass, else no credentials - const awsCredentials = - accessKeyId && secretAccessKey && sessionToken - ? { accessKeyId, secretAccessKey, sessionToken } - : accessKeyId && secretAccessKey - ? { accessKeyId, secretAccessKey } - : undefined; - - crypto.randomBytes(32, (err, nonce) => { - if (err) { - callback(err); - return; - } - - const saslStart = { - saslStart: 1, - mechanism: 'MONGODB-AWS', - payload: bson.serialize({ r: nonce, p: ASCII_N }) - }; - - connection.command(`${db}.$cmd`, saslStart, (err, result) => { - if (err) return callback(err); - - const res = result.result; - const serverResponse = bson.deserialize(res.payload.buffer); - const host = serverResponse.h; - const serverNonce = serverResponse.s.buffer; - if (serverNonce.length !== 64) { - callback( - new MongoError(`Invalid server nonce length ${serverNonce.length}, expected 64`) - ); - return; - } - - if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) { - callback(new MongoError('Server nonce does not begin with client nonce')); - return; - } - - if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { - callback(new MongoError(`Server returned an invalid host: "${host}"`)); - return; - } - - const body = 'Action=GetCallerIdentity&Version=2011-06-15'; - const options = aws4.sign( - { - method: 'POST', - host, - region: deriveRegion(serverResponse.h), - service: 'sts', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Content-Length': body.length, - 'X-MongoDB-Server-Nonce': serverNonce.toString('base64'), - 'X-MongoDB-GS2-CB-Flag': 'n' - }, - path: '/', - body - }, - awsCredentials - ); - - const authorization = options.headers.Authorization; - const date = options.headers['X-Amz-Date']; - const payload = { a: authorization, d: date }; - if (sessionToken) { - payload.t = sessionToken; - } - - const saslContinue = { - saslContinue: 1, - conversationId: 1, - payload: bson.serialize(payload) - }; - - connection.command(`${db}.$cmd`, saslContinue, err => { - if (err) return callback(err); - callback(); - }); - }); - }); - } -} - -function makeTempCredentials(credentials, callback) { - function done(creds) { - if (creds.AccessKeyId == null || creds.SecretAccessKey == null || creds.Token == null) { - callback(new MongoError('Could not obtain temporary MONGODB-AWS credentials')); - return; - } - - callback( - undefined, - new MongoCredentials({ - username: creds.AccessKeyId, - password: creds.SecretAccessKey, - source: credentials.source, - mechanism: 'MONGODB-AWS', - mechanismProperties: { - AWS_SESSION_TOKEN: creds.Token - } - }) - ); - } - - // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI - // is set then drivers MUST assume that it was set by an AWS ECS agent - if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { - request( - `${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`, - undefined, - (err, res) => { - if (err) return callback(err); - done(res); - } - ); - - return; - } - - // Otherwise assume we are on an EC2 instance - - // get a token - - request( - `${AWS_EC2_URI}/latest/api/token`, - { method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } }, - (err, token) => { - if (err) return callback(err); - - // get role name - request( - `${AWS_EC2_URI}/${AWS_EC2_PATH}`, - { json: false, headers: { 'X-aws-ec2-metadata-token': token } }, - (err, roleName) => { - if (err) return callback(err); - - // get temp credentials - request( - `${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, - { headers: { 'X-aws-ec2-metadata-token': token } }, - (err, creds) => { - if (err) return callback(err); - done(creds); - } - ); - } - ); - } - ); -} - -function deriveRegion(host) { - const parts = host.split('.'); - if (parts.length === 1 || parts[1] === 'amazonaws') { - return 'us-east-1'; - } - - return parts[1]; -} - -function request(uri, options, callback) { - options = Object.assign( - { - method: 'GET', - timeout: 10000, - json: true - }, - url.parse(uri), - options - ); - - const req = http.request(options, res => { - res.setEncoding('utf8'); - - let data = ''; - res.on('data', d => (data += d)); - res.on('end', () => { - if (options.json === false) { - callback(undefined, data); - return; - } - - try { - const parsed = JSON.parse(data); - callback(undefined, parsed); - } catch (err) { - callback(new MongoError(`Invalid JSON response: "${data}"`)); - } - }); - }); - - req.on('error', err => callback(err)); - req.end(); -} - -module.exports = MongoDBAWS; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/plain.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/plain.js deleted file mode 100644 index f8de3dd..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/plain.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const AuthProvider = require('./auth_provider').AuthProvider; - -// TODO: can we get the Binary type from this.bson instead? -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -class Plain extends AuthProvider { - auth(authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - const username = credentials.username; - const password = credentials.password; - - const payload = new Binary(`\x00${username}\x00${password}`); - const command = { - saslStart: 1, - mechanism: 'PLAIN', - payload: payload, - autoAuthorize: 1 - }; - - connection.command('$external.$cmd', command, callback); - } -} - -module.exports = Plain; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/scram.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/scram.js deleted file mode 100644 index 2d17878..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/scram.js +++ /dev/null @@ -1,348 +0,0 @@ -'use strict'; -const crypto = require('crypto'); -const Buffer = require('safe-buffer').Buffer; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const AuthProvider = require('./auth_provider').AuthProvider; -const emitWarningOnce = require('../../utils').emitWarning; - -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -let saslprep; -try { - // Ensure you always wrap an optional require in the try block NODE-3199 - saslprep = require('saslprep'); -} catch (e) { - // don't do anything; -} - -class ScramSHA extends AuthProvider { - constructor(bson, cryptoMethod) { - super(bson); - this.cryptoMethod = cryptoMethod || 'sha1'; - } - - prepare(handshakeDoc, authContext, callback) { - const cryptoMethod = this.cryptoMethod; - if (cryptoMethod === 'sha256' && saslprep == null) { - emitWarningOnce('Warning: no saslprep library specified. Passwords will not be sanitized'); - } - - crypto.randomBytes(24, (err, nonce) => { - if (err) { - return callback(err); - } - - // store the nonce for later use - Object.assign(authContext, { nonce }); - - const credentials = authContext.credentials; - const request = Object.assign({}, handshakeDoc, { - speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), { - db: credentials.source - }) - }); - - callback(undefined, request); - }); - } - - auth(authContext, callback) { - const response = authContext.response; - if (response && response.speculativeAuthenticate) { - continueScramConversation( - this.cryptoMethod, - response.speculativeAuthenticate, - authContext, - callback - ); - - return; - } - - executeScram(this.cryptoMethod, authContext, callback); - } -} - -function cleanUsername(username) { - return username.replace('=', '=3D').replace(',', '=2C'); -} - -function clientFirstMessageBare(username, nonce) { - // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. - // Since the username is not sasl-prep-d, we need to do this here. - return Buffer.concat([ - Buffer.from('n=', 'utf8'), - Buffer.from(username, 'utf8'), - Buffer.from(',r=', 'utf8'), - Buffer.from(nonce.toString('base64'), 'utf8') - ]); -} - -function makeFirstMessage(cryptoMethod, credentials, nonce) { - const username = cleanUsername(credentials.username); - const mechanism = cryptoMethod === 'sha1' ? 'SCRAM-SHA-1' : 'SCRAM-SHA-256'; - - // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. - // Since the username is not sasl-prep-d, we need to do this here. - return { - saslStart: 1, - mechanism, - payload: new Binary( - Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)]) - ), - autoAuthorize: 1, - options: { skipEmptyExchange: true } - }; -} - -function executeScram(cryptoMethod, authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - const nonce = authContext.nonce; - const db = credentials.source; - - const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); - connection.command(`${db}.$cmd`, saslStartCmd, (_err, result) => { - const err = resolveError(_err, result); - if (err) { - return callback(err); - } - - continueScramConversation(cryptoMethod, result.result, authContext, callback); - }); -} - -function continueScramConversation(cryptoMethod, response, authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - const nonce = authContext.nonce; - - const db = credentials.source; - const username = cleanUsername(credentials.username); - const password = credentials.password; - - let processedPassword; - if (cryptoMethod === 'sha256') { - processedPassword = saslprep ? saslprep(password) : password; - } else { - try { - processedPassword = passwordDigest(username, password); - } catch (e) { - return callback(e); - } - } - - const payload = Buffer.isBuffer(response.payload) - ? new Binary(response.payload) - : response.payload; - const dict = parsePayload(payload.value()); - - const iterations = parseInt(dict.i, 10); - if (iterations && iterations < 4096) { - callback(new MongoError(`Server returned an invalid iteration count ${iterations}`), false); - return; - } - - const salt = dict.s; - const rnonce = dict.r; - if (rnonce.startsWith('nonce')) { - callback(new MongoError(`Server returned an invalid nonce: ${rnonce}`), false); - return; - } - - // Set up start of proof - const withoutProof = `c=biws,r=${rnonce}`; - const saltedPassword = HI( - processedPassword, - Buffer.from(salt, 'base64'), - iterations, - cryptoMethod - ); - - const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); - const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); - const storedKey = H(cryptoMethod, clientKey); - const authMessage = [ - clientFirstMessageBare(username, nonce), - payload.value().toString('base64'), - withoutProof - ].join(','); - - const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); - const clientProof = `p=${xor(clientKey, clientSignature)}`; - const clientFinal = [withoutProof, clientProof].join(','); - - const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); - const saslContinueCmd = { - saslContinue: 1, - conversationId: response.conversationId, - payload: new Binary(Buffer.from(clientFinal)) - }; - - connection.command(`${db}.$cmd`, saslContinueCmd, (_err, result) => { - const err = resolveError(_err, result); - if (err) { - return callback(err); - } - - const r = result.result; - const parsedResponse = parsePayload(r.payload.value()); - if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { - callback(new MongoError('Server returned an invalid signature')); - return; - } - - if (!r || r.done !== false) { - return callback(err, r); - } - - const retrySaslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: Buffer.alloc(0) - }; - - connection.command(`${db}.$cmd`, retrySaslContinueCmd, callback); - }); -} - -function parsePayload(payload) { - const dict = {}; - const parts = payload.split(','); - for (let i = 0; i < parts.length; i++) { - const valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -} - -function passwordDigest(username, password) { - if (typeof username !== 'string') { - throw new MongoError('username must be a string'); - } - - if (typeof password !== 'string') { - throw new MongoError('password must be a string'); - } - - if (password.length === 0) { - throw new MongoError('password cannot be empty'); - } - - const md5 = crypto.createHash('md5'); - md5.update(`${username}:mongo:${password}`, 'utf8'); - return md5.digest('hex'); -} - -// XOR two buffers -function xor(a, b) { - if (!Buffer.isBuffer(a)) { - a = Buffer.from(a); - } - - if (!Buffer.isBuffer(b)) { - b = Buffer.from(b); - } - - const length = Math.max(a.length, b.length); - const res = []; - - for (let i = 0; i < length; i += 1) { - res.push(a[i] ^ b[i]); - } - - return Buffer.from(res).toString('base64'); -} - -function H(method, text) { - return crypto - .createHash(method) - .update(text) - .digest(); -} - -function HMAC(method, key, text) { - return crypto - .createHmac(method, key) - .update(text) - .digest(); -} - -let _hiCache = {}; -let _hiCacheCount = 0; -function _hiCachePurge() { - _hiCache = {}; - _hiCacheCount = 0; -} - -const hiLengthMap = { - sha256: 32, - sha1: 20 -}; - -function HI(data, salt, iterations, cryptoMethod) { - // omit the work if already generated - const key = [data, salt.toString('base64'), iterations].join('_'); - if (_hiCache[key] !== undefined) { - return _hiCache[key]; - } - - // generate the salt - const saltedData = crypto.pbkdf2Sync( - data, - salt, - iterations, - hiLengthMap[cryptoMethod], - cryptoMethod - ); - - // cache a copy to speed up the next lookup, but prevent unbounded cache growth - if (_hiCacheCount >= 200) { - _hiCachePurge(); - } - - _hiCache[key] = saltedData; - _hiCacheCount += 1; - return saltedData; -} - -function compareDigest(lhs, rhs) { - if (lhs.length !== rhs.length) { - return false; - } - - if (typeof crypto.timingSafeEqual === 'function') { - return crypto.timingSafeEqual(lhs, rhs); - } - - let result = 0; - for (let i = 0; i < lhs.length; i++) { - result |= lhs[i] ^ rhs[i]; - } - - return result === 0; -} - -function resolveError(err, result) { - if (err) return err; - - const r = result.result; - if (r.$err || r.errmsg) return new MongoError(r); -} - -class ScramSHA1 extends ScramSHA { - constructor(bson) { - super(bson, 'sha1'); - } -} - -class ScramSHA256 extends ScramSHA { - constructor(bson) { - super(bson, 'sha256'); - } -} - -module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/auth/x509.js b/reverse_engineering/node_modules/mongodb/lib/core/auth/x509.js deleted file mode 100644 index 4dafa3c..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/auth/x509.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; -const AuthProvider = require('./auth_provider').AuthProvider; - -class X509 extends AuthProvider { - prepare(handshakeDoc, authContext, callback) { - const credentials = authContext.credentials; - Object.assign(handshakeDoc, { - speculativeAuthenticate: x509AuthenticateCommand(credentials) - }); - - callback(undefined, handshakeDoc); - } - - auth(authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - const response = authContext.response; - if (response.speculativeAuthenticate) { - return callback(); - } - - connection.command('$external.$cmd', x509AuthenticateCommand(credentials), callback); - } -} - -function x509AuthenticateCommand(credentials) { - const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; - if (credentials.username) { - Object.assign(command, { user: credentials.username }); - } - - return command; -} - -module.exports = X509; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/apm.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/apm.js deleted file mode 100644 index 875e418..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/apm.js +++ /dev/null @@ -1,138 +0,0 @@ -'use strict'; -const KillCursor = require('../connection/commands').KillCursor; -const GetMore = require('../connection/commands').GetMore; -const calculateDurationInMs = require('../../utils').calculateDurationInMs; -const extractCommand = require('../../command_utils').extractCommand; - -// helper methods -const namespace = command => command.ns; -const databaseName = command => command.ns.split('.')[0]; -const generateConnectionId = pool => - pool.options ? `${pool.options.host}:${pool.options.port}` : pool.address; -const isLegacyPool = pool => pool.s && pool.queue; - -const extractReply = (command, reply) => { - if (command instanceof GetMore) { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - nextBatch: reply.message.documents - } - }; - } - - if (command instanceof KillCursor) { - return { - ok: 1, - cursorsUnknown: command.cursorIds - }; - } - - // is this a legacy find command? - if (command.query && typeof command.query.$query !== 'undefined') { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - firstBatch: reply.message.documents - } - }; - } - - return reply && reply.result ? reply.result : reply; -}; - -const extractConnectionDetails = pool => { - if (isLegacyPool(pool)) { - return { - connectionId: generateConnectionId(pool) - }; - } - - // APM in the modern pool is done at the `Connection` level, so we rename it here for - // readability. - const connection = pool; - return { - address: connection.address, - connectionId: connection.id - }; -}; - -/** An event indicating the start of a given command */ -class CommandStartedEvent { - /** - * Create a started event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - */ - constructor(pool, command) { - const extractedCommand = extractCommand(command); - const commandName = extractedCommand.name; - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - databaseName: databaseName(command), - commandName, - command: extractedCommand.shouldRedact ? {} : extractedCommand.cmd - }); - } -} - -/** An event indicating the success of a given command */ -class CommandSucceededEvent { - /** - * Create a succeeded event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {Object} reply the reply for this command from the server - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, reply, started) { - const extractedCommand = extractCommand(command); - const commandName = extractedCommand.name; - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - reply: extractedCommand.shouldRedact ? {} : extractReply(command, reply) - }); - } -} - -/** An event indicating the failure of a given command */ -class CommandFailedEvent { - /** - * Create a failure event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {MongoError|Object} error the generated error or a server error response - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, error, started) { - const extractedCommand = extractCommand(command); - const commandName = extractedCommand.name; - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - failure: extractedCommand.shouldRedact ? {} : error - }); - } -} - -module.exports = { - CommandStartedEvent, - CommandSucceededEvent, - CommandFailedEvent -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/command_result.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/command_result.js deleted file mode 100644 index 762aa3f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/command_result.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection, message) { - this.result = result; - this.connection = connection; - this.message = message; -}; - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - let result = Object.assign({}, this, this.result); - delete result.message; - return result; -}; - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -}; - -module.exports = CommandResult; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/commands.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/commands.js deleted file mode 100644 index b5446d9..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/commands.js +++ /dev/null @@ -1,516 +0,0 @@ -'use strict'; - -var retrieveBSON = require('./utils').retrieveBSON; -var BSON = retrieveBSON(); -var Long = BSON.Long; -const Buffer = require('safe-buffer').Buffer; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var opcodes = require('../wireprotocol/shared').opcodes; - -// Query flags -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 1; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if (ns == null) throw new Error('ns must be specified for query'); - if (query == null) throw new Error('query must be specified for query'); - - // Validate that we are not passing 0x00 in the collection name - if (ns.indexOf('\x00') !== -1) { - throw new Error('namespace cannot contain a null character'); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = Query.getRequestId(); - - // special case for pre-3.2 find commands, delete ASAP - this.pre32Limit = options.pre32Limit; - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; - this.oplogReplay = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -}; - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -}; - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if (this.tailable) { - flags |= OPTS_TAILABLE_CURSOR; - } - - if (this.slaveOk) { - flags |= OPTS_SLAVE; - } - - if (this.oplogReplay) { - flags |= OPTS_OPLOG_REPLAY; - } - - if (this.noCursorTimeout) { - flags |= OPTS_NO_CURSOR_TIMEOUT; - } - - if (this.awaitData) { - flags |= OPTS_AWAIT_DATA; - } - - if (this.exhaust) { - flags |= OPTS_EXHAUST; - } - - if (this.partial) { - flags |= OPTS_PARTIAL; - } - - // If batchSize is different to self.numberToReturn - if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = Buffer.alloc( - 4 * 4 + // Header - 4 + // Flags - Buffer.byteLength(self.ns) + - 1 + // namespace - 4 + // numberToSkip - 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - - // Add query document - buffers.push(query); - - if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = totalLength & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = this.requestId & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = 0 & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; - header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; - header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; - header[index] = opcodes.OP_QUERY & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = flags & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = this.numberToSkip & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -}; - -Query.getRequestId = function() { - return ++_requestId; -}; - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; - _buffer[index] = opcodes.OP_GETMORE & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getHighBits() & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -}; - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, ns, cursorIds) { - this.ns = ns; - this.requestId = _requestId++; - this.cursorIds = cursorIds; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; - - // Create command buffer - var index = 0; - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = this.cursorIds.length & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for (var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -}; - -var Response = function(bson, message, msgHeader, msgBody, opts) { - opts = opts || { - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - bsonRegExp: false - }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read the message body - this.responseFlags = msgBody.readInt32LE(0); - this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); - this.startingFrom = msgBody.readInt32LE(12); - this.numberReturned = msgBody.readInt32LE(16); - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; - this.bsonRegExp = typeof opts.bsonRegExp === 'boolean' ? opts.bsonRegExp : false; -}; - -Response.prototype.isParsed = function() { - return this.parsed; -}; - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - var promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - var promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - var promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; - var bsonRegExp = - typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : this.opts.bsonRegExp; - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers, - bsonRegExp: bsonRegExp - }; - - // Position within OP_REPLY at which documents start - // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) - this.index = 20; - - // - // Parse Body - // - for (var i = 0; i < this.numberReturned; i++) { - bsonSize = - this.data[this.index] | - (this.data[this.index + 1] << 8) | - (this.data[this.index + 2] << 16) | - (this.data[this.index + 3] << 24); - - // If we have raw results specified slice the return document - if (raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize( - this.data.slice(this.index, this.index + bsonSize), - _options - ); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - // Set parsed - this.parsed = true; -}; - -module.exports = { - Query: Query, - GetMore: GetMore, - Response: Response, - KillCursor: KillCursor -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/connect.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/connect.js deleted file mode 100644 index b3f487d..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/connect.js +++ /dev/null @@ -1,372 +0,0 @@ -'use strict'; -const net = require('net'); -const tls = require('tls'); -const Connection = require('./connection'); -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError; -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; -const AuthContext = require('../auth/auth_provider').AuthContext; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const makeClientMetadata = require('../utils').makeClientMetadata; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -let AUTH_PROVIDERS; - -function connect(options, cancellationToken, callback) { - if (typeof cancellationToken === 'function') { - callback = cancellationToken; - cancellationToken = undefined; - } - - const ConnectionType = options && options.connectionType ? options.connectionType : Connection; - if (AUTH_PROVIDERS == null) { - AUTH_PROVIDERS = defaultAuthProviders(options.bson); - } - - const family = options.family !== void 0 ? options.family : 0; - makeConnection(family, options, cancellationToken, (err, socket) => { - if (err) { - callback(err, socket); // in the error case, `socket` is the originating error event name - return; - } - - performInitialHandshake(new ConnectionType(socket, options), options, callback); - }); -} - -function isModernConnectionType(conn) { - return !(conn instanceof Connection); -} - -function checkSupportedServer(ismaster, options) { - const serverVersionHighEnough = - ismaster && - typeof ismaster.maxWireVersion === 'number' && - ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; - const serverVersionLowEnough = - ismaster && - typeof ismaster.minWireVersion === 'number' && - ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; - - if (serverVersionHighEnough) { - if (serverVersionLowEnough) { - return null; - } - - const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ismaster.minWireVersion}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); - } - - const message = `Server at ${options.host}:${ - options.port - } reports maximum wire version ${ismaster.maxWireVersion || - 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); -} - -function performInitialHandshake(conn, options, _callback) { - const callback = function(err, ret) { - if (err && conn) { - conn.destroy(); - } - _callback(err, ret); - }; - - const credentials = options.credentials; - if (credentials) { - if (!credentials.mechanism.match(/DEFAULT/i) && !AUTH_PROVIDERS[credentials.mechanism]) { - callback(new MongoError(`authMechanism '${credentials.mechanism}' not supported`)); - return; - } - } - - const authContext = new AuthContext(conn, credentials, options); - prepareHandshakeDocument(authContext, (err, handshakeDoc) => { - if (err) { - return callback(err); - } - - const handshakeOptions = Object.assign({}, options); - if (options.connectTimeoutMS || options.connectionTimeout) { - // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS - handshakeOptions.socketTimeout = options.connectTimeoutMS || options.connectionTimeout; - } - - handshakeDoc.helloOk = !!options.useUnifiedTopology; - - const start = new Date().getTime(); - conn.command('admin.$cmd', handshakeDoc, handshakeOptions, (err, result) => { - if (err) { - callback(err); - return; - } - - const response = result.result; - if (response.ok === 0) { - callback(new MongoError(response)); - return; - } - - if ('isWritablePrimary' in response) { - // Provide pre-hello-style response document. - response.ismaster = response.isWritablePrimary; - } - - if (options.useUnifiedTopology && response.helloOk) { - conn.helloOk = true; - } - - const supportedServerErr = checkSupportedServer(response, options); - if (supportedServerErr) { - callback(supportedServerErr); - return; - } - - if (!isModernConnectionType(conn)) { - // resolve compression - if (response.compression) { - const agreedCompressors = handshakeDoc.compression.filter( - compressor => response.compression.indexOf(compressor) !== -1 - ); - - if (agreedCompressors.length) { - conn.agreedCompressor = agreedCompressors[0]; - } - - if (options.compression && options.compression.zlibCompressionLevel) { - conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; - } - } - } - - // NOTE: This is metadata attached to the connection while porting away from - // handshake being done in the `Server` class. Likely, it should be - // relocated, or at very least restructured. - conn.ismaster = response; - conn.lastIsMasterMS = new Date().getTime() - start; - - if (!response.arbiterOnly && credentials) { - // store the response on auth context - Object.assign(authContext, { response }); - - const resolvedCredentials = credentials.resolveAuthMechanism(response); - const authProvider = AUTH_PROVIDERS[resolvedCredentials.mechanism]; - authProvider.auth(authContext, err => { - if (err) return callback(err); - callback(undefined, conn); - }); - - return; - } - - callback(undefined, conn); - }); - }); -} - -function prepareHandshakeDocument(authContext, callback) { - const options = authContext.options; - const serverApi = authContext.connection.serverApi; - const compressors = - options.compression && options.compression.compressors ? options.compression.compressors : []; - - const handshakeDoc = { - [serverApi ? 'hello' : 'ismaster']: true, - client: options.metadata || makeClientMetadata(options), - compression: compressors - }; - - const credentials = authContext.credentials; - if (credentials) { - if (credentials.mechanism.match(/DEFAULT/i) && credentials.username) { - Object.assign(handshakeDoc, { - saslSupportedMechs: `${credentials.source}.${credentials.username}` - }); - - AUTH_PROVIDERS['scram-sha-256'].prepare(handshakeDoc, authContext, callback); - return; - } - - const authProvider = AUTH_PROVIDERS[credentials.mechanism]; - if (authProvider == null) { - return callback(new MongoError(`No AuthProvider for ${credentials.mechanism} defined.`)); - } - authProvider.prepare(handshakeDoc, authContext, callback); - return; - } - - callback(undefined, handshakeDoc); -} - -const LEGAL_SSL_SOCKET_OPTIONS = [ - 'pfx', - 'key', - 'passphrase', - 'cert', - 'ca', - 'ciphers', - 'NPNProtocols', - 'ALPNProtocols', - 'servername', - 'ecdhCurve', - 'secureProtocol', - 'secureContext', - 'session', - 'minDHSize', - 'crl', - 'rejectUnauthorized' -]; - -function parseConnectOptions(family, options) { - const host = typeof options.host === 'string' ? options.host : 'localhost'; - if (host.indexOf('/') !== -1) { - return { path: host }; - } - - const result = { - family, - host, - port: typeof options.port === 'number' ? options.port : 27017, - rejectUnauthorized: false - }; - - return result; -} - -function parseSslOptions(family, options) { - const result = parseConnectOptions(family, options); - - // Merge in valid SSL options - for (const name in options) { - if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { - result[name] = options[name]; - } - } - - // Override checkServerIdentity behavior - if (options.checkServerIdentity === false) { - // Skip the identiy check by retuning undefined as per node documents - // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback - result.checkServerIdentity = function() { - return undefined; - }; - } else if (typeof options.checkServerIdentity === 'function') { - result.checkServerIdentity = options.checkServerIdentity; - } - - // Set default sni servername to be the same as host - if (result.servername == null && !net.isIP(result.host)) { - result.servername = result.host; - } - - return result; -} - -const SOCKET_ERROR_EVENTS = new Set(['error', 'close', 'timeout', 'parseError']); -function makeConnection(family, options, cancellationToken, _callback) { - const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; - const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - let keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000; - const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; - const connectionTimeout = - typeof options.connectionTimeout === 'number' - ? options.connectionTimeout - : typeof options.connectTimeoutMS === 'number' - ? options.connectTimeoutMS - : 30000; - const socketTimeoutMS = - typeof options.socketTimeoutMS === 'number' - ? options.socketTimeoutMS - : typeof options.socketTimeout === 'number' - ? options.socketTimeout - : 0; - const rejectUnauthorized = - typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; - - if (keepAliveInitialDelay > socketTimeoutMS) { - keepAliveInitialDelay = Math.round(socketTimeoutMS / 2); - } - - let socket; - const callback = function(err, ret) { - if (err && socket) { - socket.destroy(); - } - - _callback(err, ret); - }; - - try { - if (useSsl) { - socket = tls.connect(parseSslOptions(family, options)); - if (typeof socket.disableRenegotiation === 'function') { - socket.disableRenegotiation(); - } - } else { - socket = net.createConnection(parseConnectOptions(family, options)); - } - } catch (err) { - return callback(err); - } - - socket.setKeepAlive(keepAlive, keepAliveInitialDelay); - socket.setTimeout(connectionTimeout); - socket.setNoDelay(noDelay); - - const connectEvent = useSsl ? 'secureConnect' : 'connect'; - let cancellationHandler; - function errorHandler(eventName) { - return err => { - SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); - if (cancellationHandler) { - cancellationToken.removeListener('cancel', cancellationHandler); - } - - socket.removeListener(connectEvent, connectHandler); - callback(connectionFailureError(eventName, err)); - }; - } - - function connectHandler() { - SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); - if (cancellationHandler) { - cancellationToken.removeListener('cancel', cancellationHandler); - } - - if (socket.authorizationError && rejectUnauthorized) { - return callback(socket.authorizationError); - } - - socket.setTimeout(socketTimeoutMS); - callback(null, socket); - } - - SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); - if (cancellationToken) { - cancellationHandler = errorHandler('cancel'); - cancellationToken.once('cancel', cancellationHandler); - } - - socket.once(connectEvent, connectHandler); -} - -function connectionFailureError(type, err) { - switch (type) { - case 'error': - return new MongoNetworkError(err); - case 'timeout': - return new MongoNetworkTimeoutError(`connection timed out`); - case 'close': - return new MongoNetworkError(`connection closed`); - case 'cancel': - return new MongoNetworkError(`connection establishment was cancelled`); - default: - return new MongoNetworkError(`unknown network error`); - } -} - -module.exports = connect; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/connection.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/connection.js deleted file mode 100644 index 3bd36a7..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/connection.js +++ /dev/null @@ -1,716 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const crypto = require('crypto'); -const debugOptions = require('./utils').debugOptions; -const parseHeader = require('../wireprotocol/shared').parseHeader; -const decompress = require('../wireprotocol/compression').decompress; -const Response = require('./commands').Response; -const BinMsg = require('./msg').BinMsg; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError; -const MongoError = require('../error').MongoError; -const Logger = require('./logger'); -const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const Buffer = require('safe-buffer').Buffer; -const Query = require('./commands').Query; -const CommandResult = require('./command_result'); - -let _id = 0; - -const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; -const DEBUG_FIELDS = [ - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'checkServerIdentity' -]; - -let connectionAccountingSpy = undefined; -let connectionAccounting = false; -let connections = {}; - -/** - * A class representing a single connection to a MongoDB server - * - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @fires Connection#message - */ -class Connection extends EventEmitter { - /** - * Creates a new Connection instance - * - * **NOTE**: Internal class, do not instantiate directly - * - * @param {Socket} socket The socket this connection wraps - * @param {Object} options Various settings - * @param {object} options.bson An implementation of bson serialize and deserialize - * @param {string} [options.host='localhost'] The host the socket is connected to - * @param {number} [options.port=27017] The port used for the socket connection - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) - */ - constructor(socket, options) { - super(); - - options = options || {}; - if (!options.bson) { - throw new TypeError('must pass in valid bson parser'); - } - - this.id = _id++; - this.options = options; - this.logger = Logger('Connection', options); - this.bson = options.bson; - this.tag = options.tag; - this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; - this.helloOk = undefined; - - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 0; - - // These values are inspected directly in tests, but maybe not necessary to keep around - this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000; - this.connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - if (this.keepAliveInitialDelay > this.socketTimeout) { - this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); - } - - // Debug information - if (this.logger.isDebug()) { - this.logger.debug( - `creating connection ${this.id} with options [${JSON.stringify( - debugOptions(DEBUG_FIELDS, options) - )}]` - ); - } - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false - }; - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.writeStream = null; - this.destroyed = false; - this.timedOut = false; - - // Create hash method - const hash = crypto.createHash('sha1'); - hash.update(this.address); - this.hashedName = hash.digest('hex'); - - // All operations in flight on the connection - this.workItems = []; - - // setup socket - this.socket = socket; - this.socket.once('error', errorHandler(this)); - this.socket.once('timeout', timeoutHandler(this)); - this.socket.once('close', closeHandler(this)); - this.socket.on('data', dataHandler(this)); - - if (connectionAccounting) { - addConnection(this.id, this); - } - } - - setSocketTimeout(value) { - if (this.socket) { - this.socket.setTimeout(value); - } - } - - resetSocketTimeout() { - if (this.socket) { - this.socket.setTimeout(this.socketTimeout); - } - } - - static enableConnectionAccounting(spy) { - if (spy) { - connectionAccountingSpy = spy; - } - - connectionAccounting = true; - connections = {}; - } - - static disableConnectionAccounting() { - connectionAccounting = false; - connectionAccountingSpy = undefined; - } - - static connections() { - return connections; - } - - get address() { - return `${this.host}:${this.port}`; - } - - /** - * Unref this connection - * @method - * @return {boolean} - * @deprecated This function is deprecated and will be removed in the next major version. - */ - unref() { - if (this.socket == null) { - this.once('connect', () => this.socket.unref()); - return; - } - - this.socket.unref(); - } - - /** - * Flush all work Items on this connection - * - * @param {*} err The error to propagate to the flushed work items - */ - flush(err) { - while (this.workItems.length > 0) { - const workItem = this.workItems.shift(); - if (workItem.cb) { - workItem.cb(err); - } - } - } - - /** - * Destroy connection - * @method - */ - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - - if (connectionAccounting) { - deleteConnection(this.id); - } - - if (this.socket == null) { - this.destroyed = true; - return; - } - - if (options.force || this.timedOut) { - this.socket.destroy(); - this.destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - this.socket.end(err => { - this.destroyed = true; - if (typeof callback === 'function') callback(err, null); - }); - } - - /** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ - write(buffer) { - // Debug Log - if (this.logger.isDebug()) { - if (!Array.isArray(buffer)) { - this.logger.debug(`writing buffer [ ${buffer.length} ] to ${this.address}`); - } else { - for (let i = 0; i < buffer.length; i++) - this.logger.debug(`writing buffer [ ${buffer[i].length} ] to ${this.address}`); - } - } - - // Double check that the connection is not destroyed - if (this.socket.destroyed === false) { - // Write out the command - if (!Array.isArray(buffer)) { - this.socket.write(buffer, 'binary'); - return true; - } - - // Iterate over all buffers and write them in order to the socket - for (let i = 0; i < buffer.length; i++) { - this.socket.write(buffer[i], 'binary'); - } - - return true; - } - - // Connection is destroyed return write failed - return false; - } - - /** - * Return id of connection as a string - * @method - * @return {string} - */ - toString() { - return '' + this.id; - } - - /** - * Return json object of connection - * @method - * @return {object} - */ - toJSON() { - return { id: this.id, host: this.host, port: this.port }; - } - - /** - * Is the connection connected - * @method - * @return {boolean} - */ - isConnected() { - if (this.destroyed) return false; - return !this.socket.destroyed && this.socket.writable; - } - - /** - * @ignore - */ - command(ns, command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - const conn = this; - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 0; - const bson = conn.options.bson; - const query = new Query(bson, ns, command, { - numberToSkip: 0, - numberToReturn: 1 - }); - - const noop = () => {}; - function _callback(err, result) { - callback(err, result); - callback = noop; - } - - function errorHandler(err) { - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - if (err == null) { - err = new MongoError(`runCommand failed for connection to '${conn.address}'`); - } - - // ignore all future errors - conn.on('error', noop); - _callback(err); - } - - function messageHandler(msg) { - if (msg.responseTo !== query.requestId) { - return; - } - - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - msg.parse({ promoteValues: true }); - - const response = msg.documents[0]; - if (response.ok === 0 || response.$err || response.errmsg || response.code) { - _callback(new MongoError(response)); - return; - } - - _callback(undefined, new CommandResult(response, this, msg)); - } - - conn.setSocketTimeout(socketTimeout); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); - conn.on('message', messageHandler); - conn.write(query.toBin()); - } -} - -const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; - -function deleteConnection(id) { - // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) - delete connections[id]; - - if (connectionAccountingSpy) { - connectionAccountingSpy.deleteConnection(id); - } -} - -function addConnection(id, connection) { - // console.log("=== added connection " + id + " :: " + connection.port) - connections[id] = connection; - - if (connectionAccountingSpy) { - connectionAccountingSpy.addConnection(id, connection); - } -} - -// -// Connection handlers -function errorHandler(conn) { - return function(err) { - if (connectionAccounting) deleteConnection(conn.id); - // Debug information - if (conn.logger.isDebug()) { - conn.logger.debug( - `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` - ); - } - - conn.emit('error', new MongoNetworkError(err), conn); - }; -} - -function timeoutHandler(conn) { - return function() { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); - } - - conn.timedOut = true; - conn.emit( - 'timeout', - new MongoNetworkTimeoutError(`connection ${conn.id} to ${conn.address} timed out`, { - beforeHandshake: conn.ismaster == null - }), - conn - ); - }; -} - -function closeHandler(conn) { - return function(hadError) { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); - } - - if (!hadError) { - conn.emit( - 'close', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), - conn - ); - } - }; -} - -// Handle a message once it is received -function processMessage(conn, message) { - const msgHeader = parseHeader(message); - if (msgHeader.opCode !== OP_COMPRESSED) { - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - message.slice(MESSAGE_HEADER_SIZE), - conn.responseOptions - ), - conn - ); - - return; - } - - msgHeader.fromCompressed = true; - let index = MESSAGE_HEADER_SIZE; - msgHeader.opCode = message.readInt32LE(index); - index += 4; - msgHeader.length = message.readInt32LE(index); - index += 4; - const compressorID = message[index]; - index++; - - decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { - if (err) { - conn.emit('error', err); - return; - } - - if (decompressedMsgBody.length !== msgHeader.length) { - conn.emit( - 'error', - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - decompressedMsgBody, - conn.responseOptions - ), - conn - ); - }); -} - -function dataHandler(conn) { - return function(data) { - // Parse until we are done with the data - while (data.length > 0) { - // If we still have bytes to read on the current message - if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; - // Check if the current chunk contains the rest of the message - if (remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(conn.buffer, conn.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - conn.bytesRead = conn.bytesRead + data.length; - - // Reset state of buffer - data = Buffer.alloc(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - const emitBuffer = conn.buffer; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - - processMessage(conn, emitBuffer); - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if (conn.stubBuffer.length + data.length > 4) { - // Prepad the data - const newData = Buffer.alloc(conn.stubBuffer.length + data.length); - conn.stubBuffer.copy(newData, 0); - data.copy(newData, conn.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - } else { - // Add the the bytes to the stub buffer - const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); - // Copy existing stub buffer - conn.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, conn.stubBuffer.length); - // Exit parsing loop - data = Buffer.alloc(0); - } - } else { - if (data.length > 4) { - // Retrieve the message size - const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); - // If we have a negative sizeOfMessage emit error and return - if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: '', - bin: conn.buffer, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: conn.bytesRead, - stubBuffer: conn.stubBuffer - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage > data.length - ) { - conn.buffer = Buffer.alloc(sizeOfMessage); - // Copy all the data into the buffer - data.copy(conn.buffer, 0); - // Update bytes read - conn.bytesRead = data.length; - // Update sizeOfMessage - conn.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage === data.length - ) { - const emitBuffer = data; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - // Emit the message - processMessage(conn, emitBuffer); - } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: null, - bin: data, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: 0, - buffer: null, - stubBuffer: null - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - - // Clear out the state of the parser - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else { - const emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - processMessage(conn, emitBuffer); - } - } else { - // Create a buffer that contains the space for the non-complete message - conn.stubBuffer = Buffer.alloc(data.length); - // Copy the data to the stub buffer - data.copy(conn.stubBuffer, 0); - // Exit parsing loop - data = Buffer.alloc(0); - } - } - } - } - }; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -/** - * An event emitted each time the connection receives a parsed message from the wire - * - * @event Connection#message - * @type {Connection} - */ - -module.exports = Connection; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/logger.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/logger.js deleted file mode 100644 index b2957a5..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/logger.js +++ /dev/null @@ -1,252 +0,0 @@ -'use strict'; - -var f = require('util').format, - MongoError = require('../error').MongoError; - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * @callback Logger~loggerCallback - * @param {string} msg message being logged - * @param {object} state an object containing more metadata about the logging message - */ - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Logger~loggerCallback} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - */ -var Logger = function(className, options) { - if (!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - this.className = className; - - // Current logger - if (options.logger) { - currentLogger = options.logger; - } else if (currentLogger == null) { - // eslint-disable-next-line no-console - currentLogger = console.log; - } - - // Set level of logging, default is error - if (options.loggerLevel) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if (filteredClasses[this.className] == null) classFilters[this.className] = true; -}; - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if ( - this.isDebug() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}; - -/** - * Log a message at the warn level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -(Logger.prototype.warn = function(message, object) { - if ( - this.isWarn() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); - var state = { - type: 'warn', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}), - /** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.info = function(message, object) { - if ( - this.isInfo() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.error = function(message, object) { - if ( - this.isError() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Is the logger set at info level - * @method - * @return {boolean} - */ - (Logger.prototype.isInfo = function() { - return level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isError = function() { - return level === 'error' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isWarn = function() { - return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at debug level - * @method - * @return {boolean} - */ - (Logger.prototype.isDebug = function() { - return level === 'debug'; - }); - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -}; - -/** - * Get the current logger function - * @method - * @return {Logger~loggerCallback} - */ -Logger.currentLogger = function() { - return currentLogger; -}; - -/** - * Set the current logger function - * @method - * @param {Logger~loggerCallback} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); - currentLogger = logger; -}; - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if (type === 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -}; - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { - throw new Error(f('%s is an illegal logging level', _level)); - } - - level = _level; -}; - -module.exports = Logger; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/msg.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/msg.js deleted file mode 100644 index 49744c3..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/msg.js +++ /dev/null @@ -1,233 +0,0 @@ -'use strict'; - -// Implementation of OP_MSG spec: -// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst -// -// struct Section { -// uint8 payloadType; -// union payload { -// document document; // payloadType == 0 -// struct sequence { // payloadType == 1 -// int32 size; -// cstring identifier; -// document* documents; -// }; -// }; -// }; - -// struct OP_MSG { -// struct MsgHeader { -// int32 messageLength; -// int32 requestID; -// int32 responseTo; -// int32 opCode = 2013; -// }; -// uint32 flagBits; -// Section+ sections; -// [uint32 checksum;] -// }; - -const Buffer = require('safe-buffer').Buffer; -const opcodes = require('../wireprotocol/shared').opcodes; -const databaseNamespace = require('../wireprotocol/shared').databaseNamespace; -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../../core/error').MongoError; - -// Incrementing request id -let _requestId = 0; - -// Msg Flags -const OPTS_CHECKSUM_PRESENT = 1; -const OPTS_MORE_TO_COME = 2; -const OPTS_EXHAUST_ALLOWED = 1 << 16; - -class Msg { - constructor(bson, ns, command, options) { - // Basic options needed to be passed in - if (command == null) throw new Error('query must be specified for query'); - - // Basic options - this.bson = bson; - this.ns = ns; - this.command = command; - this.command.$db = databaseNamespace(ns); - - if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { - this.command.$readPreference = options.readPreference.toJSON(); - } - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - - // flags - this.checksumPresent = false; - this.moreToCome = options.moreToCome || false; - this.exhaustAllowed = - typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; - } - - toBin() { - const buffers = []; - let flags = 0; - - if (this.checksumPresent) { - flags |= OPTS_CHECKSUM_PRESENT; - } - - if (this.moreToCome) { - flags |= OPTS_MORE_TO_COME; - } - - if (this.exhaustAllowed) { - flags |= OPTS_EXHAUST_ALLOWED; - } - - const header = Buffer.alloc( - 4 * 4 + // Header - 4 // Flags - ); - - buffers.push(header); - - let totalLength = header.length; - const command = this.command; - totalLength += this.makeDocumentSegment(buffers, command); - - header.writeInt32LE(totalLength, 0); // messageLength - header.writeInt32LE(this.requestId, 4); // requestID - header.writeInt32LE(0, 8); // responseTo - header.writeInt32LE(opcodes.OP_MSG, 12); // opCode - header.writeUInt32LE(flags, 16); // flags - return buffers; - } - - makeDocumentSegment(buffers, document) { - const payloadTypeBuffer = Buffer.alloc(1); - payloadTypeBuffer[0] = 0; - - const documentBuffer = this.serializeBson(document); - buffers.push(payloadTypeBuffer); - buffers.push(documentBuffer); - - return payloadTypeBuffer.length + documentBuffer.length; - } - - serializeBson(document) { - return this.bson.serialize(document, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - } -} - -Msg.getRequestId = function() { - _requestId = (_requestId + 1) & 0x7fffffff; - return _requestId; -}; - -class BinMsg { - constructor(bson, message, msgHeader, msgBody, opts) { - opts = opts || { - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - bsonRegExp: false - }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read response flags - this.responseFlags = msgBody.readInt32LE(0); - this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; - this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; - this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; - this.bsonRegExp = typeof opts.bsonRegExp === 'boolean' ? opts.bsonRegExp : false; - - this.documents = []; - } - - isParsed() { - return this.parsed; - } - - parse(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - this.index = 4; - // Allow the return of raw documents instead of parsing - const raw = options.raw || false; - const documentsReturnedIn = options.documentsReturnedIn || null; - const promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - const promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - const promoteBuffers = - typeof options.promoteBuffers === 'boolean' - ? options.promoteBuffers - : this.opts.promoteBuffers; - const bsonRegExp = - typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : this.opts.bsonRegExp; - - // Set up the options - const _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers, - bsonRegExp: bsonRegExp - }; - - while (this.index < this.data.length) { - const payloadType = this.data.readUInt8(this.index++); - if (payloadType === 1) { - // It was decided that no driver makes use of payload type 1 - throw new MongoError('OP_MSG Payload Type 1 detected unsupported protocol'); - } else if (payloadType === 0) { - const bsonSize = this.data.readUInt32LE(this.index); - const bin = this.data.slice(this.index, this.index + bsonSize); - this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); - - this.index += bsonSize; - } - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - this.parsed = true; - } -} - -module.exports = { Msg, BinMsg }; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/pool.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/pool.js deleted file mode 100644 index 951a7a0..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/pool.js +++ /dev/null @@ -1,1286 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const EventEmitter = require('events').EventEmitter; -const MongoError = require('../error').MongoError; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const MongoWriteConcernError = require('../error').MongoWriteConcernError; -const Logger = require('./logger'); -const f = require('util').format; -const Msg = require('./msg').Msg; -const CommandResult = require('./command_result'); -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../wireprotocol/shared').opcodes; -const compress = require('../wireprotocol/compression').compress; -const compressorIDs = require('../wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; -const apm = require('./apm'); -const Buffer = require('safe-buffer').Buffer; -const connect = require('./connect'); -const updateSessionFromResponse = require('../sessions').updateSessionFromResponse; -const eachAsync = require('../utils').eachAsync; -const makeStateMachine = require('../utils').makeStateMachine; -const now = require('../../utils').now; - -const DISCONNECTED = 'disconnected'; -const CONNECTING = 'connecting'; -const CONNECTED = 'connected'; -const DRAINING = 'draining'; -const DESTROYING = 'destroying'; -const DESTROYED = 'destroyed'; -const stateTransition = makeStateMachine({ - [DISCONNECTED]: [CONNECTING, DRAINING, DISCONNECTED], - [CONNECTING]: [CONNECTING, CONNECTED, DRAINING, DISCONNECTED], - [CONNECTED]: [CONNECTED, DISCONNECTED, DRAINING], - [DRAINING]: [DRAINING, DESTROYING, DESTROYED], - [DESTROYING]: [DESTROYING, DESTROYED], - [DESTROYED]: [DESTROYED] -}); - -const CONNECTION_EVENTS = new Set([ - 'error', - 'close', - 'timeout', - 'parseError', - 'connect', - 'message' -]); - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Max server connection pool size - * @param {number} [options.minSize=0] Minimum server connection pool size - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=0] TCP Socket timeout setting for replicaset monitoring socket - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(topology, options) { - // Add event listener - EventEmitter.call(this); - - // Store topology for later use - this.topology = topology; - - this.s = { - state: DISCONNECTED, - cancellationToken: new EventEmitter() - }; - - // we don't care how many connections are listening for cancellation - this.s.cancellationToken.setMaxListeners(Infinity); - - // Add the options - this.options = Object.assign( - { - // Host and port settings - host: 'localhost', - port: 27017, - // Pool default max size - size: 5, - // Pool default min size - minSize: 0, - // socket settings - connectionTimeout: 30000, - socketTimeout: 0, - keepAlive: true, - keepAliveInitialDelay: 120000, - noDelay: true, - // SSL Settings - ssl: false, - checkServerIdentity: true, - ca: null, - crl: null, - cert: null, - key: null, - passphrase: null, - rejectUnauthorized: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - bsonRegExp: false, - // Reconnection options - reconnect: true, - reconnectInterval: 1000, - reconnectTries: 30, - // Enable domains - domainsEnabled: false, - // feature flag for determining if we are running with the unified topology or not - legacyCompatMode: true - }, - options - ); - - // Identification information - this.id = _id++; - // Current reconnect retries - this.retriesLeft = this.options.reconnectTries; - this.reconnectId = null; - this.reconnectError = null; - // No bson parser passed in - if ( - !options.bson || - (options.bson && - (typeof options.bson.serialize !== 'function' || - typeof options.bson.deserialize !== 'function')) - ) { - throw new Error('must pass in valid bson parser'); - } - - // Logger instance - this.logger = Logger('Pool', options); - // Connections - this.availableConnections = []; - this.inUseConnections = []; - this.connectingConnections = 0; - // Currently executing - this.executing = false; - // Operation work queue - this.queue = []; - - // Number of consecutive timeouts caught - this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; - - // event handlers - const pool = this; - this._messageHandler = messageHandler(this); - this._connectionCloseHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'close', err, connection); - }; - - this._connectionErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'error', err, connection); - }; - - this._connectionTimeoutHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'timeout', err, connection); - }; - - this._connectionParseErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'parseError', err, connection); - }; -}; - -inherits(Pool, EventEmitter); - -Object.defineProperty(Pool.prototype, 'size', { - enumerable: true, - get: function() { - return this.options.size; - } -}); - -Object.defineProperty(Pool.prototype, 'minSize', { - enumerable: true, - get: function() { - return this.options.minSize; - } -}); - -Object.defineProperty(Pool.prototype, 'connectionTimeout', { - enumerable: true, - get: function() { - return this.options.connectionTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'socketTimeout', { - enumerable: true, - get: function() { - return this.options.socketTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'state', { - enumerable: true, - get: function() { - return this.s.state; - } -}); - -// clears all pool state -function resetPoolState(pool) { - pool.inUseConnections = []; - pool.availableConnections = []; - pool.connectingConnections = 0; - pool.executing = false; - pool.numberOfConsecutiveTimeouts = 0; - pool.connectionIndex = 0; - pool.retriesLeft = pool.options.reconnectTries; - pool.reconnectId = null; -} - -function connectionFailureHandler(pool, event, err, conn) { - if (conn) { - if (conn._connectionFailHandled) { - return; - } - - conn._connectionFailHandled = true; - conn.destroy(); - - // Remove the connection - removeConnection(pool, conn); - - // flush remaining work items - conn.flush(err); - } - - // Did we catch a timeout, increment the numberOfConsecutiveTimeouts - if (event === 'timeout') { - pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; - - // Have we timed out more than reconnectTries in a row ? - // Force close the pool as we are trying to connect to tcp sink hole - if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { - pool.numberOfConsecutiveTimeouts = 0; - // Destroy all connections and pool - pool.destroy(true); - // Emit close event - return pool.emit('close', pool); - } - } - - // No more socket available propegate the event - if (pool.socketCount() === 0) { - if (pool.state !== DESTROYED && pool.state !== DESTROYING && pool.state !== DRAINING) { - if (pool.options.reconnect) { - stateTransition(pool, DISCONNECTED); - } - } - - // Do not emit error events, they are always close events - // do not trigger the low level error handler in node - event = event === 'error' ? 'close' : event; - pool.emit(event, err); - } - - // Start reconnection attempts - if (!pool.reconnectId && pool.options.reconnect) { - pool.reconnectError = err; - pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); - } - - // Do we need to do anything to maintain the minimum pool size - const totalConnections = totalConnectionCount(pool); - if (totalConnections < pool.minSize) { - createConnection(pool); - } -} - -function attemptReconnect(pool, callback) { - return function() { - pool.emit('attemptReconnect', pool); - - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.retriesLeft = pool.retriesLeft - 1; - if (pool.retriesLeft <= 0) { - pool.destroy(); - - const error = new MongoTimeoutError( - `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${pool.options.reconnectInterval} ms`, - pool.reconnectError - ); - - pool.emit('reconnectFailed', error); - if (typeof callback === 'function') { - callback(error); - } - - return; - } - - // clear the reconnect id on retry - pool.reconnectId = null; - - // now retry creating a connection - createConnection(pool, (err, conn) => { - if (err == null) { - pool.reconnectId = null; - pool.retriesLeft = pool.options.reconnectTries; - pool.emit('reconnect', pool); - } - - if (typeof callback === 'function') { - callback(err, conn); - } - }); - }; -} - -function moveConnectionBetween(connection, from, to) { - var index = from.indexOf(connection); - // Move the connection from connecting to available - if (index !== -1) { - from.splice(index, 1); - to.push(connection); - } -} - -function messageHandler(self) { - return function(message, connection) { - // workItem to execute - var workItem = null; - - // Locate the workItem - for (var i = 0; i < connection.workItems.length; i++) { - if (connection.workItems[i].requestId === message.responseTo) { - // Get the callback - workItem = connection.workItems[i]; - // Remove from list of workItems - connection.workItems.splice(i, 1); - } - } - - if (workItem && workItem.monitoring) { - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - } - - // Reset timeout counter - self.numberOfConsecutiveTimeouts = 0; - - // Reset the connection timeout if we modified it for - // this operation - if (workItem && workItem.socketTimeout) { - connection.resetSocketTimeout(); - } - - // Log if debug enabled - if (self.logger.isDebug()) { - self.logger.debug( - f( - 'message [ %s ] received from %s:%s', - message.raw.length, - self.options.host, - self.options.port - ) - ); - } - - function handleOperationCallback(self, cb, err, result) { - // No domain enabled - if (!self.options.domainsEnabled) { - return process.nextTick(function() { - return cb(err, result); - }); - } - - // Domain enabled just call the callback - cb(err, result); - } - - // Keep executing, ensure current message handler does not stop execution - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - - // Time to dispatch the message if we have a callback - if (workItem && !workItem.immediateRelease) { - try { - // Parse the message according to the provided options - message.parse(workItem); - } catch (err) { - return handleOperationCallback(self, workItem.cb, new MongoError(err)); - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = workItem.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (self.topology && document.$clusterTime) { - self.topology.clusterTime = document.$clusterTime; - } - } - - // Establish if we have an error - if (workItem.command && message.documents[0]) { - const responseDoc = message.documents[0]; - - if (responseDoc.writeConcernError) { - const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); - return handleOperationCallback(self, workItem.cb, err); - } - - if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { - return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); - } - } - - // Add the connection details - message.hashedName = connection.hashedName; - - // Return the documents - handleOperationCallback( - self, - workItem.cb, - null, - new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) - ); - } - }; -} - -/** - * Return the total socket count in the pool. - * @method - * @return {Number} The number of socket available. - */ -Pool.prototype.socketCount = function() { - return this.availableConnections.length + this.inUseConnections.length; - // + this.connectingConnections.length; -}; - -function totalConnectionCount(pool) { - return ( - pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections - ); -} - -/** - * Return all pool connections - * @method - * @return {Connection[]} The pool connections - */ -Pool.prototype.allConnections = function() { - return this.availableConnections.concat(this.inUseConnections); -}; - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - return this.allConnections()[0]; -}; - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - // We are in a destroyed state - if (this.state === DESTROYED || this.state === DESTROYING) { - return false; - } - - // Get connections - var connections = this.availableConnections.concat(this.inUseConnections); - - // Check if we have any connected connections - for (var i = 0; i < connections.length; i++) { - if (connections[i].isConnected()) return true; - } - - // Not connected - return false; -}; - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state === DESTROYED || this.state === DESTROYING; -}; - -/** - * Is the pool in a disconnected state - * @method - * @return {boolean} - */ -Pool.prototype.isDisconnected = function() { - return this.state === DISCONNECTED; -}; - -/** - * Connect pool - */ -Pool.prototype.connect = function(callback) { - if (this.state !== DISCONNECTED) { - throw new MongoError('connection in unlawful state ' + this.state); - } - - stateTransition(this, CONNECTING); - createConnection(this, (err, conn) => { - if (err) { - if (typeof callback === 'function') { - this.destroy(); - callback(err); - return; - } - - if (this.state === CONNECTING) { - this.emit('error', err); - } - - this.destroy(); - return; - } - - stateTransition(this, CONNECTED); - - // create min connections - if (this.minSize) { - for (let i = 0; i < this.minSize; i++) { - createConnection(this); - } - } - - if (typeof callback === 'function') { - callback(null, conn); - } else { - this.emit('connect', this, conn); - } - }); -}; - -/** - * Authenticate using a specified mechanism - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Logout all users against a database - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.logout = function(dbName, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Unref the pool - * @method - * @deprecated This function is deprecated and will be removed in the next major version. - */ -Pool.prototype.unref = function() { - // Get all the known connections - var connections = this.availableConnections.concat(this.inUseConnections); - - connections.forEach(function(c) { - c.unref(); - }); -}; - -// Destroy the connections -function destroy(self, connections, options, callback) { - stateTransition(self, DESTROYING); - - // indicate that in-flight connections should cancel - self.s.cancellationToken.emit('cancel'); - - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - // ignore any errors during destruction - conn.on('error', () => {}); - - conn.destroy(options, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') callback(err, null); - return; - } - - resetPoolState(self); - self.queue = []; - - stateTransition(self, DESTROYED); - if (typeof callback === 'function') callback(null, null); - } - ); -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function(force, callback) { - var self = this; - if (typeof force === 'function') { - callback = force; - force = false; - } - - // Do not try again if the pool is already dead - if (this.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') callback(null, null); - return; - } - - // Set state to draining - stateTransition(this, DRAINING); - - // Are we force closing - if (force) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Flush any remaining work items with - // an error - while (self.queue.length > 0) { - var workItem = self.queue.shift(); - if (typeof workItem.cb === 'function') { - workItem.cb(new MongoError('Pool was force destroyed')); - } - } - - // Destroy the topology - return destroy(self, connections, { force: true }, callback); - } - - // Clear out the reconnect if set - if (this.reconnectId) { - clearTimeout(this.reconnectId); - } - - // Wait for the operations to drain before we close the pool - function checkStatus() { - if (self.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - flushMonitoringOperations(self.queue); - - if (self.queue.length === 0) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Check if we have any in flight operations - for (var i = 0; i < connections.length; i++) { - // There is an operation still in flight, reschedule a - // check waiting for it to drain - if (connections[i].workItems.length > 0) { - return setTimeout(checkStatus, 1); - } - } - - destroy(self, connections, { force: false }, callback); - } else { - // Ensure we empty the queue - _execute(self)(); - // Set timeout - setTimeout(checkStatus, 1); - } - } - - // Initiate drain of operations - checkStatus(); -}; - -/** - * Reset all connections of this pool - * - * @param {function} [callback] - */ -Pool.prototype.reset = function(callback) { - if (this.s.state !== CONNECTED) { - if (typeof callback === 'function') { - callback(new MongoError('pool is not connected, reset aborted')); - } - - return; - } - - // signal in-flight connections should be cancelled - this.s.cancellationToken.emit('cancel'); - - // destroy existing connections - const connections = this.availableConnections.concat(this.inUseConnections); - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - conn.destroy({ force: true }, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - } - - resetPoolState(this); - - // create a new connection, this will ultimately trigger execution - createConnection(this, () => { - if (typeof callback === 'function') { - callback(null, null); - } - }); - } - ); -}; - -// Prepare the buffer that Pool.prototype.write() uses to send to the server -function serializeCommand(self, command, callback) { - const originalCommandBuffer = command.toBin(); - - // Check whether we and the server have agreed to use a compressor - const shouldCompress = !!self.options.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - return callback(null, originalCommandBuffer); - } - - // Transform originalCommandBuffer into OP_COMPRESSED - const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress(self, messageToBeCompressed, function(err, compressedMessage) { - if (err) return callback(err, null); - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID - - return callback(null, [msgHeader, compressionDetails, compressedMessage]); - }); -} - -/** - * Write a message to MongoDB - * @method - * @return {Connection} - */ -Pool.prototype.write = function(command, options, cb) { - var self = this; - // Ensure we have a callback - if (typeof options === 'function') { - cb = options; - } - - // Always have options - options = options || {}; - - // We need to have a callback function unless the message returns no response - if (!(typeof cb === 'function') && !options.noResponse) { - throw new MongoError('write method must provide a callback'); - } - - // Pool was destroyed error out - if (this.state === DESTROYED || this.state === DESTROYING) { - cb(new MongoError('pool destroyed')); - return; - } - - if (this.state === DRAINING) { - cb(new MongoError('pool is draining, new operations prohibited')); - return; - } - - if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { - // if we have a domain bind to it - var oldCb = cb; - cb = process.domain.bind(function() { - // v8 - argumentsToArray one-liner - var args = new Array(arguments.length); - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - // bounce off event loop so domain switch takes place - process.nextTick(function() { - oldCb.apply(null, args); - }); - }); - } - - // Do we have an operation - var operation = { - cb: cb, - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - bsonRegExp: false, - fullResult: false - }; - - // Set the options for the parsing - operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; - operation.promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : true; - operation.promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; - operation.bsonRegExp = typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false; - operation.raw = typeof options.raw === 'boolean' ? options.raw : false; - operation.immediateRelease = - typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; - operation.documentsReturnedIn = options.documentsReturnedIn; - operation.command = typeof options.command === 'boolean' ? options.command : false; - operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; - operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; - operation.session = options.session || null; - - // Optional per operation socketTimeout - operation.socketTimeout = options.socketTimeout; - operation.monitoring = options.monitoring; - - // Get the requestId - operation.requestId = command.requestId; - - // If command monitoring is enabled we need to modify the callback here - if (self.options.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operation.started = now(); - operation.cb = (err, reply) => { - if (err) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operation.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operation.started) - ); - } else { - self.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operation.started) - ); - } - } - - if (typeof cb === 'function') cb(err, reply); - }; - } - - // Prepare the operation buffer - serializeCommand(self, command, (err, serializedBuffers) => { - if (err) throw err; - - // Set the operation's buffer to the serialization of the commands - operation.buffer = serializedBuffers; - - // If we have a monitoring operation schedule as the very first operation - // Otherwise add to back of queue - if (options.monitoring) { - self.queue.unshift(operation); - } else { - self.queue.push(operation); - } - - // Attempt to execute the operation - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - }); -}; - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return !uncompressibleCommands.has(commandName); -} - -// Remove connection method -function remove(connection, connections) { - for (var i = 0; i < connections.length; i++) { - if (connections[i] === connection) { - connections.splice(i, 1); - return true; - } - } -} - -function removeConnection(self, connection) { - if (remove(connection, self.availableConnections)) return; - if (remove(connection, self.inUseConnections)) return; -} - -function createConnection(pool, callback) { - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.connectingConnections++; - connect(pool.options, pool.s.cancellationToken, (err, connection) => { - pool.connectingConnections--; - - if (err) { - if (pool.logger.isDebug()) { - pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - } - - // check if reconnect is enabled, and attempt retry if so - if (!pool.reconnectId && pool.options.reconnect) { - if (pool.state === CONNECTING && pool.options.legacyCompatMode) { - callback(err); - return; - } - - pool.reconnectError = err; - pool.reconnectId = setTimeout( - attemptReconnect(pool, callback), - pool.options.reconnectInterval - ); - - return; - } - - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // the pool might have been closed since we started creating the connection - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Pool was destroyed after connection creation')); - } - - connection.destroy(); - return; - } - - // otherwise, connect relevant event handlers and add it to our available connections - connection.on('error', pool._connectionErrorHandler); - connection.on('close', pool._connectionCloseHandler); - connection.on('timeout', pool._connectionTimeoutHandler); - connection.on('parseError', pool._connectionParseErrorHandler); - connection.on('message', pool._messageHandler); - - pool.availableConnections.push(connection); - - // if a callback was provided, return the connection - if (typeof callback === 'function') { - callback(null, connection); - } - - // immediately execute any waiting work - _execute(pool)(); - }); -} - -function flushMonitoringOperations(queue) { - for (var i = 0; i < queue.length; i++) { - if (queue[i].monitoring) { - var workItem = queue[i]; - queue.splice(i, 1); - workItem.cb( - new MongoError({ message: 'no connection available for monitoring', driver: true }) - ); - } - } -} - -function _execute(self) { - return function() { - if (self.state === DESTROYED) return; - // Already executing, skip - if (self.executing) return; - // Set pool as executing - self.executing = true; - - // New pool connections are in progress, wait them to finish - // before executing any more operation to ensure distribution of - // operations - if (self.connectingConnections > 0) { - self.executing = false; - return; - } - - // As long as we have available connections - // eslint-disable-next-line - while (true) { - // Total availble connections - const totalConnections = totalConnectionCount(self); - - // No available connections available, flush any monitoring ops - if (self.availableConnections.length === 0) { - // Flush any monitoring operations - flushMonitoringOperations(self.queue); - - // Try to create a new connection to execute stuck operation - if (totalConnections < self.options.size && self.queue.length > 0) { - createConnection(self); - } - - break; - } - - // No queue break - if (self.queue.length === 0) { - break; - } - - var connection = null; - const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); - - // No connection found that has no work on it, just pick one for pipelining - if (connections.length === 0) { - connection = - self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; - } else { - connection = connections[self.connectionIndex++ % connections.length]; - } - - // Is the connection connected - if (!connection.isConnected()) { - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - - // Get the next work item - var workItem = self.queue.shift(); - - // If we are monitoring we need to use a connection that is not - // running another operation to avoid socket timeout changes - // affecting an existing operation - if (workItem.monitoring) { - var foundValidConnection = false; - - for (let i = 0; i < self.availableConnections.length; i++) { - // If the connection is connected - // And there are no pending workItems on it - // Then we can safely use it for monitoring. - if ( - self.availableConnections[i].isConnected() && - self.availableConnections[i].workItems.length === 0 - ) { - foundValidConnection = true; - connection = self.availableConnections[i]; - break; - } - } - - // No safe connection found, attempt to grow the connections - // if possible and break from the loop - if (!foundValidConnection) { - // Put workItem back on the queue - self.queue.unshift(workItem); - - // Attempt to grow the pool if it's not yet maxsize - if (totalConnections < self.options.size && self.queue.length > 0) { - // Create a new connection - createConnection(self); - } - - // Re-execute the operation - setTimeout(() => _execute(self)(), 10); - break; - } - } - - // Don't execute operation until we have a full pool - if (totalConnections < self.options.size) { - // Connection has work items, then put it back on the queue - // and create a new connection - if (connection.workItems.length > 0) { - // Lets put the workItem back on the list - self.queue.unshift(workItem); - // Create a new connection - createConnection(self); - // Break from the loop - break; - } - } - - // Get actual binary commands - var buffer = workItem.buffer; - - // If we are monitoring take the connection of the availableConnections - if (workItem.monitoring) { - moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); - } - - // Track the executing commands on the mongo server - // as long as there is an expected response - if (!workItem.noResponse) { - connection.workItems.push(workItem); - } - - // We have a custom socketTimeout - if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { - connection.setSocketTimeout(workItem.socketTimeout); - } - - // Capture if write was successful - var writeSuccessful = true; - - // Put operation on the wire - if (Array.isArray(buffer)) { - for (let i = 0; i < buffer.length; i++) { - writeSuccessful = connection.write(buffer[i]); - } - } else { - writeSuccessful = connection.write(buffer); - } - - // if the command is designated noResponse, call the callback immeditely - if (workItem.noResponse && typeof workItem.cb === 'function') { - workItem.cb(null, null); - } - - if (writeSuccessful === false) { - // If write not successful put back on queue - self.queue.unshift(workItem); - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - } - - self.executing = false; - }; -} - -// Make execution loop available for testing -Pool._execute = _execute; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * A server reconnect event, used to verify that pool reconnected. - * - * @event Pool#reconnect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -/** - * The driver attempted to reconnect - * - * @event Pool#attemptReconnect - * @type {Pool} - */ - -/** - * The driver exhausted all reconnect attempts - * - * @event Pool#reconnectFailed - * @type {Pool} - */ - -module.exports = Pool; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/connection/utils.js b/reverse_engineering/node_modules/mongodb/lib/core/connection/utils.js deleted file mode 100644 index 40c9c3f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/connection/utils.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -const parsePackageVersion = require('../../utils').parsePackageVersion; -const MongoError = require('../error').MongoError; - -const require_optional = require('optional-require')(require); - -function debugOptions(debugFields, options) { - const finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -function retrieveBSON() { - const BSON = require('bson'); - BSON.native = false; - - const optionalBSON = require_optional('bson-ext'); - const bsonExtVersion = parsePackageVersion( - require_optional('bson-ext/package.json') || { version: '0.0.0' } - ); - if (optionalBSON) { - if (bsonExtVersion.major >= 4) { - throw new MongoError( - 'bson-ext version 4 and above does not work with the 3.x version of the mongodb driver' - ); - } - optionalBSON.native = true; - return optionalBSON; - } - - return BSON; -} - -// Throw an error if an attempt to use Snappy is made when Snappy is not installed -function noSnappyWarning() { - throw new Error( - 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' - ); -} - -const PKG_VERSION = Symbol('kPkgVersion'); - -// Facilitate loading Snappy optionally -function retrieveSnappy() { - const snappy = require_optional('snappy'); - if (!snappy) { - return { - compress: noSnappyWarning, - uncompress: noSnappyWarning, - compressSync: noSnappyWarning, - uncompressSync: noSnappyWarning - }; - } - - const snappyPkg = require_optional('snappy/package.json') || { version: '0.0.0' }; - const version = parsePackageVersion(snappyPkg); - snappy[PKG_VERSION] = version; - if (version.major >= 7) { - const compressOriginal = snappy.compress; - const uncompressOriginal = snappy.uncompress; - snappy.compress = (data, callback) => { - compressOriginal(data) - .then(res => callback(undefined, res)) - .catch(error => callback(error)); - }; - snappy.uncompress = (data, callback) => { - uncompressOriginal(data) - .then(res => callback(undefined, res)) - .catch(error => callback(error)); - }; - } - - return snappy; -} - -module.exports = { - PKG_VERSION, - debugOptions, - retrieveBSON, - retrieveSnappy -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/cursor.js b/reverse_engineering/node_modules/mongodb/lib/core/cursor.js deleted file mode 100644 index 7282a6b..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/cursor.js +++ /dev/null @@ -1,881 +0,0 @@ -'use strict'; - -const Logger = require('./connection/logger'); -const retrieveBSON = require('./connection/utils').retrieveBSON; -const MongoError = require('./error').MongoError; -const MongoNetworkError = require('./error').MongoNetworkError; -const collationNotSupported = require('./utils').collationNotSupported; -const ReadPreference = require('./topologies/read_preference'); -const isUnifiedTopology = require('./utils').isUnifiedTopology; -const executeOperation = require('../operations/execute_operation'); -const Readable = require('stream').Readable; -const SUPPORTS = require('../utils').SUPPORTS; -const MongoDBNamespace = require('../utils').MongoDBNamespace; -const mergeOptions = require('../utils').mergeOptions; -const OperationBase = require('../operations/operation').OperationBase; - -const BSON = retrieveBSON(); -const Long = BSON.Long; - -// Possible states for a cursor -const CursorState = { - INIT: 0, - OPEN: 1, - CLOSED: 2, - GET_MORE: 3 -}; - -// -// Handle callback (including any exceptions thrown) -function handleCallback(callback, err, result) { - try { - callback(err, result); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } -} - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - */ - -/** - * The core cursor class. All cursors in the driver build off of this one. - * - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -class CoreCursor extends Readable { - /** - * Create a new core `Cursor` instance. - * **NOTE** Not to be instantiated directly - * - * @param {object} topology The server topology instance. - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next - */ - constructor(topology, ns, cmd, options) { - super({ objectMode: true }); - options = options || {}; - - if (ns instanceof OperationBase) { - this.operation = ns; - ns = this.operation.ns.toString(); - options = this.operation.options; - cmd = this.operation.cmd ? this.operation.cmd : {}; - } - - // Cursor pool - this.pool = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = topology.s.bson; - this.ns = ns; - this.namespace = MongoDBNamespace.fromString(ns); - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null, - cmd, - documents: options.documents || [], - cursorIndex: 0, - dead: false, - killed: false, - init: false, - notified: false, - limit: options.limit || cmd.limit || 0, - skip: options.skip || cmd.skip || 0, - batchSize: options.batchSize || cmd.batchSize || 1000, - currentLimit: 0, - // Result field name if not a cursor (contains the array of results) - transforms: options.transforms, - raw: options.raw || (cmd && cmd.raw) - }; - - if (typeof options.session === 'object') { - this.cursorState.session = options.session; - } - - // Add promoteLong to cursor state - const topologyOptions = topology.s.options; - if (typeof topologyOptions.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = topologyOptions.promoteLongs; - } else if (typeof options.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if (typeof topologyOptions.promoteValues === 'boolean') { - this.cursorState.promoteValues = topologyOptions.promoteValues; - } else if (typeof options.promoteValues === 'boolean') { - this.cursorState.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if (typeof topologyOptions.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; - } else if (typeof options.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = options.promoteBuffers; - } - - // Add bsonRegExp to cursor state - if (typeof topologyOptions.bsonRegExp === 'boolean') { - this.cursorState.bsonRegExp = topologyOptions.bsonRegExp; - } else if (typeof options.bsonRegExp === 'boolean') { - this.cursorState.bsonRegExp = options.bsonRegExp; - } - - if (topologyOptions.reconnect) { - this.cursorState.reconnect = topologyOptions.reconnect; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if (typeof cmd === 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - this.cursorState.lastCursorId = this.cursorState.cursorId; - } else if (cmd instanceof Long) { - this.cursorState.cursorId = cmd; - this.cursorState.lastCursorId = cmd; - } - - // TODO: remove as part of NODE-2104 - if (this.operation) { - this.operation.cursorState = this.cursorState; - } - } - - setCursorBatchSize(value) { - this.cursorState.batchSize = value; - } - - cursorBatchSize() { - return this.cursorState.batchSize; - } - - setCursorLimit(value) { - this.cursorState.limit = value; - } - - cursorLimit() { - return this.cursorState.limit; - } - - setCursorSkip(value) { - this.cursorState.skip = value; - } - - cursorSkip() { - return this.cursorState.skip; - } - - /** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ - _next(callback) { - nextFunction(this, callback); - } - - /** - * Clone the cursor - * @method - * @return {Cursor} - */ - clone() { - const clonedOptions = mergeOptions({}, this.options); - delete clonedOptions.session; - return this.topology.cursor(this.ns, this.cmd, clonedOptions); - } - - /** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ - isDead() { - return this.cursorState.dead === true; - } - - /** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ - isKilled() { - return this.cursorState.killed === true; - } - - /** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ - isNotified() { - return this.cursorState.notified === true; - } - - /** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ - bufferedCount() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; - } - - /** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ - readBufferedDocuments(number) { - const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - let elements = this.cursorState.documents.slice( - this.cursorState.cursorIndex, - this.cursorState.cursorIndex + length - ); - - // Transform the doc with passed in transformation method if provided - if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { - // Transform all the elements - for (let i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + elements.length > this.cursorState.limit - ) { - elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; - } - - /** - * Resets local state for this cursor instance, and issues a `killCursors` command to the server - * - * @param {resultCallback} callback A callback function - */ - kill(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if ( - this.cursorState.cursorId == null || - this.cursorState.cursorId.isZero() || - this.cursorState.init === false - ) { - if (callback) callback(null, null); - return; - } - - this.server.killCursors(this.ns, this.cursorState, callback); - } - - /** - * Resets the cursor - */ - rewind() { - if (this.cursorState.init) { - if (!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } - } - - // Internal methods - _read() { - if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { - return this.push(null); - } - - // Get the next item - this._next((err, result) => { - if (err) { - if (this.listeners('error') && this.listeners('error').length > 0) { - this.emit('error', err); - } - if (!this.isDead()) this.close(); - - // Emit end event - this.emit('end'); - return this.emit('finish'); - } - - // If we provided a transformation method - if ( - this.cursorState.streamOptions && - typeof this.cursorState.streamOptions.transform === 'function' && - result != null - ) { - return this.push(this.cursorState.streamOptions.transform(result)); - } - - // Return the result - this.push(result); - - if (result === null && this.isDead()) { - this.once('end', () => { - this.close(); - this.emit('finish'); - }); - } - }); - } - - _endSession(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - const session = this.cursorState.session; - - if (session && (options.force || session.owner === this)) { - this.cursorState.session = undefined; - - if (this.operation) { - this.operation.clearSession(); - } - - session.endSession(callback); - return true; - } - - if (callback) { - callback(); - } - - return false; - } - - _getMore(callback) { - if (this.logger.isDebug()) { - this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); - } - - // Set the current batchSize - let batchSize = this.cursorState.batchSize; - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + batchSize > this.cursorState.limit - ) { - batchSize = this.cursorState.limit - this.cursorState.currentLimit; - } - - const cursorState = this.cursorState; - this.server.getMore(this.ns, cursorState, batchSize, this.options, (err, result, conn) => { - // NOTE: `getMore` modifies `cursorState`, would be very ideal not to do so in the future - if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) { - this._endSession(); - } - - callback(err, result, conn); - }); - } - - _initializeCursor(callback) { - const cursor = this; - - // NOTE: this goes away once cursors use `executeOperation` - if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { - cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - this._initializeCursor(callback); - }); - - return; - } - - function done(err, result) { - const cursorState = cursor.cursorState; - if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) { - cursor._endSession(); - } - - if ( - cursorState.documents.length === 0 && - cursorState.cursorId && - cursorState.cursorId.isZero() && - !cursor.cmd.tailable && - !cursor.cmd.awaitData - ) { - return setCursorNotified(cursor, callback); - } - - callback(err, result); - } - - const queryCallback = (err, r) => { - if (err) { - return done(err); - } - - const result = r.message; - - if (Array.isArray(result.documents) && result.documents.length === 1) { - const document = result.documents[0]; - - if (result.queryFailure) { - return done(new MongoError(document), null); - } - - // Check if we have a command cursor - if (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) { - // We have an error document, return the error - if (document.$err || document.errmsg) { - return done(new MongoError(document), null); - } - - // We have a cursor document - if (document.cursor != null && typeof document.cursor !== 'string') { - const id = document.cursor.id; - // If we have a namespace change set the new namespace for getmores - if (document.cursor.ns) { - cursor.ns = document.cursor.ns; - } - // Promote id to long if needed - cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; - cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; - cursor.cursorState.operationTime = document.operationTime; - - // If we have a firstBatch set it - if (Array.isArray(document.cursor.firstBatch)) { - cursor.cursorState.documents = document.cursor.firstBatch; //.reverse(); - } - - // Return after processing command cursor - return done(null, result); - } - } - } - - // Otherwise fall back to regular find path - const cursorId = result.cursorId || 0; - cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); - cursor.cursorState.documents = result.documents; - cursor.cursorState.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if ( - cursor.cursorState.transforms && - typeof cursor.cursorState.transforms.query === 'function' - ) { - cursor.cursorState.documents = cursor.cursorState.transforms.query(result); - } - - done(null, result); - }; - - if (cursor.operation) { - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - executeOperation(cursor.topology, cursor.operation, (err, result) => { - if (err) { - done(err); - return; - } - - cursor.server = cursor.operation.server; - cursor.cursorState.init = true; - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - queryCallback(err, result); - }); - - return; - } - - // Very explicitly choose what is passed to selectServer - const serverSelectOptions = {}; - if (cursor.cursorState.session) { - serverSelectOptions.session = cursor.cursorState.session; - } - - if (cursor.operation) { - serverSelectOptions.readPreference = cursor.operation.readPreference; - } else if (cursor.options.readPreference) { - serverSelectOptions.readPreference = cursor.options.readPreference; - } - - return cursor.topology.selectServer(serverSelectOptions, (err, server) => { - if (err) { - const disconnectHandler = cursor.disconnectHandler; - if (disconnectHandler != null) { - return disconnectHandler.addObjectAndMethod( - 'cursor', - cursor, - 'next', - [callback], - callback - ); - } - - return callback(err); - } - - cursor.server = server; - cursor.cursorState.init = true; - if (collationNotSupported(cursor.server, cursor.cmd)) { - return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); - } - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - if (cursor.cmd.find != null) { - server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); - return; - } - - const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); - server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); - }); - } -} - -if (SUPPORTS.ASYNC_ITERATOR) { - CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator; -} - -/** - * Validate if the pool is dead and return error - */ -function isConnectionDead(self, callback) { - if (self.pool && self.pool.isDestroyed()) { - self.cursorState.killed = true; - const err = new MongoNetworkError( - `connection to host ${self.pool.host}:${self.pool.port} was destroyed` - ); - - _setCursorNotifiedImpl(self, () => callback(err)); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -function isCursorDeadButNotkilled(self, callback) { - // Cursor is dead but not marked killed, return null - if (self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.killed = true; - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -function isCursorDeadAndKilled(self, callback) { - if (self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, new MongoError('cursor is dead')); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -function isCursorKilled(self, callback) { - if (self.cursorState.killed) { - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -function setCursorDeadAndNotified(self, callback) { - self.cursorState.dead = true; - setCursorNotified(self, callback); -} - -/** - * Mark cursor as being notified - */ -function setCursorNotified(self, callback) { - _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); -} - -function _setCursorNotifiedImpl(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - if (self.cursorState.session) { - self._endSession(callback); - return; - } - - return callback(); -} - -function nextFunction(self, callback) { - // We have notified about it - if (self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if (isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if (isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if (isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if (!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if (!self.topology.isConnected(self.options)) { - // Only need this for single server, because repl sets and mongos - // will always continue trying to reconnect - if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { - // Reconnect is disabled, so we'll never reconnect - return callback(new MongoError('no connection available')); - } - - if (self.disconnectHandler != null) { - if (self.topology.isDestroyed()) { - // Topology was destroyed, so don't try to wait for it to reconnect - return callback(new MongoError('Topology was destroyed')); - } - - self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - return; - } - } - - self._initializeCursor((err, result) => { - if (err || result === null) { - callback(err, result); - return; - } - - nextFunction(self, callback); - }); - - return; - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(() => - // Set cursor in dead and notified state - setCursorDeadAndNotified(self, callback) - ); - } else if ( - self.cursorState.cursorIndex === self.cursorState.documents.length && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if (self.topology.isDestroyed()) - return callback( - new MongoNetworkError('connection destroyed, not possible to instantiate cursor') - ); - - // Check if connection is dead and return if not possible to - // execute a getMore on this connection - if (isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getMore(function(err, doc, connection) { - if (err) { - return handleCallback(callback, err); - } - - // Save the returned connection to ensure all getMore's fire over the same connection - self.connection = connection; - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - // No more documents in the tailed cursor - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - return nextFunction(self, callback); - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - setCursorDeadAndNotified(self, callback); - } else { - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(() => - // Set cursor in dead and notified state - setCursorDeadAndNotified(self, callback) - ); - - return; - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Doc overflow - if (!doc || doc.$err) { - // Ensure we kill the cursor on the server - self.kill(() => - // Set cursor in dead and notified state - setCursorDeadAndNotified(self, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }) - ); - - return; - } - - // Transform the doc with passed in transformation method if provided - if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -module.exports = { - CursorState, - CoreCursor -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/error.js b/reverse_engineering/node_modules/mongodb/lib/core/error.js deleted file mode 100644 index 350b31c..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/error.js +++ /dev/null @@ -1,351 +0,0 @@ -'use strict'; - -const MONGODB_ERROR_CODES = require('../error_codes').MONGODB_ERROR_CODES; - -const kErrorLabels = Symbol('errorLabels'); - -/** - * Creates a new MongoError - * - * @augments Error - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoError extends Error { - constructor(message) { - if (message instanceof Error) { - super(message.message); - this.stack = message.stack; - } else { - if (typeof message === 'string') { - super(message); - } else { - super(message.message || message.errmsg || message.$err || 'n/a'); - if (message.errorLabels) { - this[kErrorLabels] = new Set(message.errorLabels); - } - - for (var name in message) { - if (name === 'errorLabels' || name === 'errmsg') { - continue; - } - - this[name] = message[name]; - } - } - - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'MongoError'; - } - - /** - * Legacy name for server error responses - */ - get errmsg() { - return this.message; - } - - /** - * Creates a new MongoError object - * - * @param {Error|string|object} options The options used to create the error. - * @return {MongoError} A MongoError instance - * @deprecated Use `new MongoError()` instead. - */ - static create(options) { - return new MongoError(options); - } - - /** - * Checks the error to see if it has an error label - * @param {string} label The error label to check for - * @returns {boolean} returns true if the error has the provided error label - */ - hasErrorLabel(label) { - if (this[kErrorLabels] == null) { - return false; - } - - return this[kErrorLabels].has(label); - } - - addErrorLabel(label) { - if (this[kErrorLabels] == null) { - this[kErrorLabels] = new Set(); - } - - this[kErrorLabels].add(label); - } - - get errorLabels() { - return this[kErrorLabels] ? Array.from(this[kErrorLabels]) : []; - } -} - -const kBeforeHandshake = Symbol('beforeHandshake'); -function isNetworkErrorBeforeHandshake(err) { - return err[kBeforeHandshake] === true; -} - -/** - * An error indicating an issue with the network, including TCP - * errors and timeouts. - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - * @extends MongoError - */ -class MongoNetworkError extends MongoError { - constructor(message, options) { - super(message); - this.name = 'MongoNetworkError'; - - if (options && typeof options.beforeHandshake === 'boolean') { - this[kBeforeHandshake] = options.beforeHandshake; - } - } -} - -/** - * An error indicating a network timeout occurred - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {object} [options.beforeHandshake] Indicates the timeout happened before a connection handshake completed - * @extends MongoError - */ -class MongoNetworkTimeoutError extends MongoNetworkError { - constructor(message, options) { - super(message, options); - this.name = 'MongoNetworkTimeoutError'; - } -} - -/** - * An error used when attempting to parse a value (like a connection string) - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @extends MongoError - */ -class MongoParseError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoParseError'; - } -} - -/** - * An error signifying a client-side timeout event - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - * @extends MongoError - */ -class MongoTimeoutError extends MongoError { - constructor(message, reason) { - if (reason && reason.error) { - super(reason.error.message || reason.error); - } else { - super(message); - } - - this.name = 'MongoTimeoutError'; - if (reason) { - this.reason = reason; - } - } -} - -/** - * An error signifying a client-side server selection error - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - * @extends MongoError - */ -class MongoServerSelectionError extends MongoTimeoutError { - constructor(message, reason) { - super(message, reason); - this.name = 'MongoServerSelectionError'; - } -} - -function makeWriteConcernResultObject(input) { - const output = Object.assign({}, input); - - if (output.ok === 0) { - output.ok = 1; - delete output.errmsg; - delete output.code; - delete output.codeName; - } - - return output; -} - -/** - * An error thrown when the server reports a writeConcernError - * - * @param {Error|string|object} message The error message - * @param {object} result The result document (provided if ok: 1) - * @property {string} message The error message - * @property {object} [result] The result document (provided if ok: 1) - * @extends MongoError - */ -class MongoWriteConcernError extends MongoError { - constructor(message, result) { - super(message); - this.name = 'MongoWriteConcernError'; - - if (result && Array.isArray(result.errorLabels)) { - this[kErrorLabels] = new Set(result.errorLabels); - } - - if (result != null) { - this.result = makeWriteConcernResultObject(result); - } - } -} - -// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms -const RETRYABLE_ERROR_CODES = new Set([ - MONGODB_ERROR_CODES.HostUnreachable, - MONGODB_ERROR_CODES.HostNotFound, - MONGODB_ERROR_CODES.NetworkTimeout, - MONGODB_ERROR_CODES.ShutdownInProgress, - MONGODB_ERROR_CODES.PrimarySteppedDown, - MONGODB_ERROR_CODES.SocketException, - MONGODB_ERROR_CODES.NotMaster, - MONGODB_ERROR_CODES.InterruptedAtShutdown, - MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, - MONGODB_ERROR_CODES.NotMasterNoSlaveOk, - MONGODB_ERROR_CODES.NotMasterOrSecondary -]); - -const RETRYABLE_WRITE_ERROR_CODES = new Set([ - MONGODB_ERROR_CODES.InterruptedAtShutdown, - MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, - MONGODB_ERROR_CODES.NotMaster, - MONGODB_ERROR_CODES.NotMasterNoSlaveOk, - MONGODB_ERROR_CODES.NotMasterOrSecondary, - MONGODB_ERROR_CODES.PrimarySteppedDown, - MONGODB_ERROR_CODES.ShutdownInProgress, - MONGODB_ERROR_CODES.HostNotFound, - MONGODB_ERROR_CODES.HostUnreachable, - MONGODB_ERROR_CODES.NetworkTimeout, - MONGODB_ERROR_CODES.SocketException, - MONGODB_ERROR_CODES.ExceededTimeLimit -]); - -function isRetryableWriteError(error) { - if (error instanceof MongoWriteConcernError) { - return ( - RETRYABLE_WRITE_ERROR_CODES.has(error.code) || - RETRYABLE_WRITE_ERROR_CODES.has(error.result.code) - ); - } - - return RETRYABLE_WRITE_ERROR_CODES.has(error.code); -} - -/** - * Determines whether an error is something the driver should attempt to retry - * - * @ignore - * @param {MongoError|Error} error - */ -function isRetryableError(error) { - return ( - RETRYABLE_ERROR_CODES.has(error.code) || - error instanceof MongoNetworkError || - error.message.match(/not master/) || - error.message.match(/node is recovering/) - ); -} - -const SDAM_RECOVERING_CODES = new Set([ - MONGODB_ERROR_CODES.ShutdownInProgress, - MONGODB_ERROR_CODES.PrimarySteppedDown, - MONGODB_ERROR_CODES.InterruptedAtShutdown, - MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, - MONGODB_ERROR_CODES.NotMasterOrSecondary -]); - -const SDAM_NOTMASTER_CODES = new Set([ - MONGODB_ERROR_CODES.NotMaster, - MONGODB_ERROR_CODES.NotMasterNoSlaveOk, - MONGODB_ERROR_CODES.LegacyNotPrimary -]); - -const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ - MONGODB_ERROR_CODES.InterruptedAtShutdown, - MONGODB_ERROR_CODES.ShutdownInProgress -]); - -function isRecoveringError(err) { - if (typeof err.code === 'number') { - // If any error code exists, we ignore the error.message - return SDAM_RECOVERING_CODES.has(err.code); - } - - return /not master or secondary/.test(err.message) || /node is recovering/.test(err.message); -} - -function isNotMasterError(err) { - if (typeof err.code === 'number') { - // If any error code exists, we ignore the error.message - return SDAM_NOTMASTER_CODES.has(err.code); - } - - if (isRecoveringError(err)) { - return false; - } - - return /not master/.test(err.message); -} - -function isNodeShuttingDownError(err) { - return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); -} - -/** - * Determines whether SDAM can recover from a given error. If it cannot - * then the pool will be cleared, and server state will completely reset - * locally. - * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering - * @param {MongoError} error - * @returns {boolean} - */ -function isSDAMUnrecoverableError(error) { - // NOTE: null check is here for a strictly pre-CMAP world, a timeout or - // close event are considered unrecoverable - if (error instanceof MongoParseError || error == null) { - return true; - } - - return isRecoveringError(error) || isNotMasterError(error); -} - -module.exports = { - MongoError, - MongoNetworkError, - MongoNetworkTimeoutError, - MongoParseError, - MongoTimeoutError, - MongoServerSelectionError, - MongoWriteConcernError, - isRetryableError, - isSDAMUnrecoverableError, - isNodeShuttingDownError, - isRetryableWriteError, - isNetworkErrorBeforeHandshake -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/index.js b/reverse_engineering/node_modules/mongodb/lib/core/index.js deleted file mode 100644 index 3093114..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/index.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -let BSON = require('bson'); -const require_optional = require('optional-require')(require); -const EJSON = require('./utils').retrieveEJSON(); - -try { - // Ensure you always wrap an optional require in the try block NODE-3199 - // Attempt to grab the native BSON parser - const BSONNative = require_optional('bson-ext'); - // If we got the native parser, use it instead of the - // Javascript one - if (BSONNative) { - BSON = BSONNative; - } -} catch (err) {} // eslint-disable-line - -/** An enumeration of valid server API versions */ -const ServerApiVersion = Object.freeze({ - v1: '1' -}); -const ValidServerApiVersions = Object.keys(ServerApiVersion).map(key => ServerApiVersion[key]); - -module.exports = { - // Versioned API - ServerApiVersion, - ValidServerApiVersions, - // Errors - MongoError: require('./error').MongoError, - MongoNetworkError: require('./error').MongoNetworkError, - MongoParseError: require('./error').MongoParseError, - MongoTimeoutError: require('./error').MongoTimeoutError, - MongoServerSelectionError: require('./error').MongoServerSelectionError, - MongoWriteConcernError: require('./error').MongoWriteConcernError, - // Core - Connection: require('./connection/connection'), - Server: require('./topologies/server'), - ReplSet: require('./topologies/replset'), - Mongos: require('./topologies/mongos'), - Logger: require('./connection/logger'), - Cursor: require('./cursor').CoreCursor, - ReadPreference: require('./topologies/read_preference'), - Sessions: require('./sessions'), - BSON: BSON, - EJSON: EJSON, - Topology: require('./sdam/topology').Topology, - // Raw operations - Query: require('./connection/commands').Query, - // Auth mechanisms - MongoCredentials: require('./auth/mongo_credentials').MongoCredentials, - defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders, - MongoCR: require('./auth/mongocr'), - X509: require('./auth/x509'), - Plain: require('./auth/plain'), - GSSAPI: require('./auth/gssapi'), - ScramSHA1: require('./auth/scram').ScramSHA1, - ScramSHA256: require('./auth/scram').ScramSHA256, - // Utilities - parseConnectionString: require('./uri_parser') -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/common.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/common.js deleted file mode 100644 index 3cfff42..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/common.js +++ /dev/null @@ -1,67 +0,0 @@ -'use strict'; - -// shared state names -const STATE_CLOSING = 'closing'; -const STATE_CLOSED = 'closed'; -const STATE_CONNECTING = 'connecting'; -const STATE_CONNECTED = 'connected'; - -// An enumeration of topology types we know about -const TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -// An enumeration of server types we know about -const ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -// helper to get a server's type that works for both legacy and unified topologies -function serverType(server) { - let description = server.s.description || server.s.serverDescription; - if (description.topologyType === TopologyType.Single) return description.servers[0].type; - return description.type; -} - -const TOPOLOGY_DEFAULTS = { - useUnifiedTopology: true, - localThresholdMS: 15, - serverSelectionTimeoutMS: 30000, - heartbeatFrequencyMS: 10000, - minHeartbeatFrequencyMS: 500 -}; - -function drainTimerQueue(queue) { - queue.forEach(clearTimeout); - queue.clear(); -} - -function clearAndRemoveTimerFrom(timer, timers) { - clearTimeout(timer); - return timers.delete(timer); -} - -module.exports = { - STATE_CLOSING, - STATE_CLOSED, - STATE_CONNECTING, - STATE_CONNECTED, - TOPOLOGY_DEFAULTS, - TopologyType, - ServerType, - serverType, - drainTimerQueue, - clearAndRemoveTimerFrom -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/events.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/events.js deleted file mode 100644 index 08a14ad..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/events.js +++ /dev/null @@ -1,124 +0,0 @@ -'use strict'; - -/** - * Published when server description changes, but does NOT include changes to the RTT. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {ServerDescription} previousDescription The previous server description - * @property {ServerDescription} newDescription The new server description - */ -class ServerDescriptionChangedEvent { - constructor(topologyId, address, previousDescription, newDescription) { - Object.assign(this, { topologyId, address, previousDescription, newDescription }); - } -} - -/** - * Published when server is initialized. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - */ -class ServerOpeningEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when server is closed. - * - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {Object} topologyId A unique identifier for the topology - */ -class ServerClosedEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when topology description changes. - * - * @property {Object} topologyId - * @property {TopologyDescription} previousDescription The old topology description - * @property {TopologyDescription} newDescription The new topology description - */ -class TopologyDescriptionChangedEvent { - constructor(topologyId, previousDescription, newDescription) { - Object.assign(this, { topologyId, previousDescription, newDescription }); - } -} - -/** - * Published when topology is initialized. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyOpeningEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Published when topology is closed. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyClosedEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Fired when the server monitor’s ismaster command is started - immediately before - * the ismaster command is serialized into raw BSON and written to the socket. - * - * @property {Object} connectionId The connection id for the command - */ -class ServerHeartbeatStartedEvent { - constructor(connectionId) { - Object.assign(this, { connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster succeeds. - * - * @param {Number} duration The execution time of the event in ms - * @param {Object} reply The command reply - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatSucceededEvent { - constructor(duration, reply, connectionId) { - Object.assign(this, { connectionId, duration, reply }); - } -} - -/** - * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. - * - * @param {Number} duration The execution time of the event in ms - * @param {MongoError|Object} failure The command failure - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatFailedEvent { - constructor(duration, failure, connectionId) { - Object.assign(this, { connectionId, duration, failure }); - } -} - -module.exports = { - ServerDescriptionChangedEvent, - ServerOpeningEvent, - ServerClosedEvent, - TopologyDescriptionChangedEvent, - TopologyOpeningEvent, - TopologyClosedEvent, - ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerHeartbeatFailedEvent -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/monitor.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/monitor.js deleted file mode 100644 index be20fb0..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/monitor.js +++ /dev/null @@ -1,428 +0,0 @@ -'use strict'; - -const ServerType = require('./common').ServerType; -const EventEmitter = require('events'); -const connect = require('../connection/connect'); -const Connection = require('../../cmap/connection').Connection; -const common = require('./common'); -const makeStateMachine = require('../utils').makeStateMachine; -const MongoNetworkError = require('../error').MongoNetworkError; -const BSON = require('../connection/utils').retrieveBSON(); -const makeInterruptableAsyncInterval = require('../../utils').makeInterruptableAsyncInterval; -const calculateDurationInMs = require('../../utils').calculateDurationInMs; -const now = require('../../utils').now; - -const sdamEvents = require('./events'); -const ServerHeartbeatStartedEvent = sdamEvents.ServerHeartbeatStartedEvent; -const ServerHeartbeatSucceededEvent = sdamEvents.ServerHeartbeatSucceededEvent; -const ServerHeartbeatFailedEvent = sdamEvents.ServerHeartbeatFailedEvent; - -const kServer = Symbol('server'); -const kMonitorId = Symbol('monitorId'); -const kConnection = Symbol('connection'); -const kCancellationToken = Symbol('cancellationToken'); -const kRTTPinger = Symbol('rttPinger'); -const kRoundTripTime = Symbol('roundTripTime'); - -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_IDLE = 'idle'; -const STATE_MONITORING = 'monitoring'; -const stateTransition = makeStateMachine({ - [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED], - [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], - [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], - [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] -}); - -const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); - -function isInCloseState(monitor) { - return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING; -} - -class Monitor extends EventEmitter { - constructor(server, options) { - super(options); - - this[kServer] = server; - this[kConnection] = undefined; - this[kCancellationToken] = new EventEmitter(); - this[kCancellationToken].setMaxListeners(Infinity); - this[kMonitorId] = null; - this.s = { - state: STATE_CLOSED - }; - - this.address = server.description.address; - this.options = Object.freeze({ - connectTimeoutMS: - typeof options.connectionTimeout === 'number' - ? options.connectionTimeout - : typeof options.connectTimeoutMS === 'number' - ? options.connectTimeoutMS - : 10000, - heartbeatFrequencyMS: - typeof options.heartbeatFrequencyMS === 'number' ? options.heartbeatFrequencyMS : 10000, - minHeartbeatFrequencyMS: - typeof options.minHeartbeatFrequencyMS === 'number' ? options.minHeartbeatFrequencyMS : 500, - useUnifiedTopology: options.useUnifiedTopology - }); - - // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration - const connectOptions = Object.assign( - { - id: '', - host: server.description.host, - port: server.description.port, - bson: server.s.bson, - connectionType: Connection - }, - server.s.options, - this.options, - - // force BSON serialization options - { - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: true, - bsonRegExp: true - } - ); - - // ensure no authentication is used for monitoring - delete connectOptions.credentials; - - // ensure encryption is not requested for monitoring - delete connectOptions.autoEncrypter; - - this.connectOptions = Object.freeze(connectOptions); - } - - connect() { - if (this.s.state !== STATE_CLOSED) { - return; - } - - // start - const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; - const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; - this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), { - interval: heartbeatFrequencyMS, - minInterval: minHeartbeatFrequencyMS, - immediate: true - }); - } - - requestCheck() { - if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { - return; - } - - this[kMonitorId].wake(); - } - - reset() { - const topologyVersion = this[kServer].description.topologyVersion; - if (isInCloseState(this) || topologyVersion == null) { - return; - } - - stateTransition(this, STATE_CLOSING); - resetMonitorState(this); - - // restart monitor - stateTransition(this, STATE_IDLE); - - // restart monitoring - const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; - const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; - this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), { - interval: heartbeatFrequencyMS, - minInterval: minHeartbeatFrequencyMS - }); - } - - close() { - if (isInCloseState(this)) { - return; - } - - stateTransition(this, STATE_CLOSING); - resetMonitorState(this); - - // close monitor - this.emit('close'); - stateTransition(this, STATE_CLOSED); - } -} - -function resetMonitorState(monitor) { - if (monitor[kMonitorId]) { - monitor[kMonitorId].stop(); - monitor[kMonitorId] = null; - } - - if (monitor[kRTTPinger]) { - monitor[kRTTPinger].close(); - monitor[kRTTPinger] = undefined; - } - - monitor[kCancellationToken].emit('cancel'); - if (monitor[kMonitorId]) { - clearTimeout(monitor[kMonitorId]); - monitor[kMonitorId] = undefined; - } - - if (monitor[kConnection]) { - monitor[kConnection].destroy({ force: true }); - } -} - -function checkServer(monitor, callback) { - let start = now(); - monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address)); - - function failureHandler(err) { - if (monitor[kConnection]) { - monitor[kConnection].destroy({ force: true }); - monitor[kConnection] = undefined; - } - - monitor.emit( - 'serverHeartbeatFailed', - new ServerHeartbeatFailedEvent(calculateDurationInMs(start), err, monitor.address) - ); - - monitor.emit('resetServer', err); - monitor.emit('resetConnectionPool'); - callback(err); - } - - if (monitor[kConnection] != null && !monitor[kConnection].closed) { - const connectTimeoutMS = monitor.options.connectTimeoutMS; - const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; - const topologyVersion = monitor[kServer].description.topologyVersion; - const isAwaitable = topologyVersion != null; - const serverApi = monitor[kConnection].serverApi; - const helloOk = monitor[kConnection].helloOk; - - const cmd = { - [serverApi || helloOk ? 'hello' : 'ismaster']: true - }; - - // written this way omit helloOk from the command if its false-y (do not want -> helloOk: null) - if (helloOk) cmd.helloOk = helloOk; - - const options = { socketTimeout: connectTimeoutMS }; - - if (isAwaitable) { - cmd.maxAwaitTimeMS = maxAwaitTimeMS; - cmd.topologyVersion = makeTopologyVersion(topologyVersion); - if (connectTimeoutMS) { - options.socketTimeout = connectTimeoutMS + maxAwaitTimeMS; - } - options.exhaustAllowed = true; - if (monitor[kRTTPinger] == null) { - monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], monitor.connectOptions); - } - } - - monitor[kConnection].command('admin.$cmd', cmd, options, (err, result) => { - if (err) { - failureHandler(err); - return; - } - - const isMaster = result.result; - const rttPinger = monitor[kRTTPinger]; - - if ('isWritablePrimary' in isMaster) { - // Provide pre-hello-style response document. - isMaster.ismaster = isMaster.isWritablePrimary; - } - - const duration = - isAwaitable && rttPinger ? rttPinger.roundTripTime : calculateDurationInMs(start); - - monitor.emit( - 'serverHeartbeatSucceeded', - new ServerHeartbeatSucceededEvent(duration, isMaster, monitor.address) - ); - - // if we are using the streaming protocol then we immediately issue another `started` - // event, otherwise the "check" is complete and return to the main monitor loop - if (isAwaitable && isMaster.topologyVersion) { - monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address)); - start = now(); - } else { - if (monitor[kRTTPinger]) { - monitor[kRTTPinger].close(); - monitor[kRTTPinger] = undefined; - } - - callback(undefined, isMaster); - } - }); - - return; - } - - // connecting does an implicit `ismaster` - connect(monitor.connectOptions, monitor[kCancellationToken], (err, conn) => { - if (conn && isInCloseState(monitor)) { - conn.destroy({ force: true }); - return; - } - - if (err) { - monitor[kConnection] = undefined; - - // we already reset the connection pool on network errors in all cases - if (!(err instanceof MongoNetworkError)) { - monitor.emit('resetConnectionPool'); - } - - failureHandler(err); - return; - } - - monitor[kConnection] = conn; - monitor.emit( - 'serverHeartbeatSucceeded', - new ServerHeartbeatSucceededEvent( - calculateDurationInMs(start), - conn.ismaster, - monitor.address - ) - ); - - callback(undefined, conn.ismaster); - }); -} - -function monitorServer(monitor) { - return callback => { - stateTransition(monitor, STATE_MONITORING); - function done() { - if (!isInCloseState(monitor)) { - stateTransition(monitor, STATE_IDLE); - } - - callback(); - } - - // TODO: the next line is a legacy event, remove in v4 - process.nextTick(() => monitor.emit('monitoring', monitor[kServer])); - - checkServer(monitor, (err, isMaster) => { - if (err) { - // otherwise an error occured on initial discovery, also bail - if (monitor[kServer].description.type === ServerType.Unknown) { - monitor.emit('resetServer', err); - return done(); - } - } - - // if the check indicates streaming is supported, immediately reschedule monitoring - if (isMaster && isMaster.topologyVersion) { - setTimeout(() => { - if (!isInCloseState(monitor)) { - monitor[kMonitorId].wake(); - } - }); - } - - done(); - }); - }; -} - -function makeTopologyVersion(tv) { - return { - processId: tv.processId, - counter: BSON.Long.fromNumber(tv.counter) - }; -} - -class RTTPinger { - constructor(cancellationToken, options) { - this[kConnection] = null; - this[kCancellationToken] = cancellationToken; - this[kRoundTripTime] = 0; - this.closed = false; - - const heartbeatFrequencyMS = options.heartbeatFrequencyMS; - this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); - } - - get roundTripTime() { - return this[kRoundTripTime]; - } - - close() { - this.closed = true; - - clearTimeout(this[kMonitorId]); - this[kMonitorId] = undefined; - - if (this[kConnection]) { - this[kConnection].destroy({ force: true }); - } - } -} - -function measureRoundTripTime(rttPinger, options) { - const start = now(); - const cancellationToken = rttPinger[kCancellationToken]; - const heartbeatFrequencyMS = options.heartbeatFrequencyMS; - if (rttPinger.closed) { - return; - } - - function measureAndReschedule(conn) { - if (rttPinger.closed) { - conn.destroy({ force: true }); - return; - } - - if (rttPinger[kConnection] == null) { - rttPinger[kConnection] = conn; - } - - rttPinger[kRoundTripTime] = calculateDurationInMs(start); - rttPinger[kMonitorId] = setTimeout( - () => measureRoundTripTime(rttPinger, options), - heartbeatFrequencyMS - ); - } - - if (rttPinger[kConnection] == null) { - connect(options, cancellationToken, (err, conn) => { - if (err) { - rttPinger[kConnection] = undefined; - rttPinger[kRoundTripTime] = 0; - return; - } - - measureAndReschedule(conn); - }); - - return; - } - - rttPinger[kConnection].command('admin.$cmd', { ismaster: 1 }, err => { - if (err) { - rttPinger[kConnection] = undefined; - rttPinger[kRoundTripTime] = 0; - return; - } - - measureAndReschedule(); - }); -} - -module.exports = { - Monitor -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/server.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/server.js deleted file mode 100644 index c160178..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/server.js +++ /dev/null @@ -1,573 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const ConnectionPool = require('../../cmap/connection_pool').ConnectionPool; -const CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES; -const MongoError = require('../error').MongoError; -const relayEvents = require('../utils').relayEvents; -const BSON = require('../connection/utils').retrieveBSON(); -const Logger = require('../connection/logger'); -const ServerDescription = require('./server_description').ServerDescription; -const compareTopologyVersion = require('./server_description').compareTopologyVersion; -const ReadPreference = require('../topologies/read_preference'); -const Monitor = require('./monitor').Monitor; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError; -const collationNotSupported = require('../utils').collationNotSupported; -const debugOptions = require('../connection/utils').debugOptions; -const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; -const isRetryableWriteError = require('../error').isRetryableWriteError; -const isNodeShuttingDownError = require('../error').isNodeShuttingDownError; -const isNetworkErrorBeforeHandshake = require('../error').isNetworkErrorBeforeHandshake; -const maxWireVersion = require('../utils').maxWireVersion; -const makeStateMachine = require('../utils').makeStateMachine; -const extractCommand = require('../../command_utils').extractCommand; -const common = require('./common'); -const ServerType = common.ServerType; -const isTransactionCommand = require('../transactions').isTransactionCommand; - -// Used for filtering out fields for logging -const DEBUG_FIELDS = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'servername' -]; - -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CONNECTING = common.STATE_CONNECTING; -const STATE_CONNECTED = common.STATE_CONNECTED; -const stateTransition = makeStateMachine({ - [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], - [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], - [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] -}); - -const kMonitor = Symbol('monitor'); - -/** - * - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - */ -class Server extends EventEmitter { - /** - * Create a server - * - * @param {ServerDescription} description - * @param {Object} options - */ - constructor(description, options, topology) { - super(); - - this.s = { - // the server description - description, - // a saved copy of the incoming options - options, - // the server logger - logger: Logger('Server', options), - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // the server state - state: STATE_CLOSED, - credentials: options.credentials, - topology - }; - this.serverApi = options.serverApi; - - // create the connection pool - // NOTE: this used to happen in `connect`, we supported overriding pool options there - const poolOptions = Object.assign( - { host: this.description.host, port: this.description.port, bson: this.s.bson }, - options - ); - - this.s.pool = new ConnectionPool(poolOptions); - relayEvents( - this.s.pool, - this, - ['commandStarted', 'commandSucceeded', 'commandFailed'].concat(CMAP_EVENT_NAMES) - ); - - this.s.pool.on('clusterTimeReceived', clusterTime => { - this.clusterTime = clusterTime; - }); - - // create the monitor - this[kMonitor] = new Monitor(this, this.s.options); - relayEvents(this[kMonitor], this, [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - - // legacy events - 'monitoring' - ]); - - this[kMonitor].on('resetConnectionPool', () => { - this.s.pool.clear(); - }); - - this[kMonitor].on('resetServer', error => markServerUnknown(this, error)); - this[kMonitor].on('serverHeartbeatSucceeded', event => { - this.emit( - 'descriptionReceived', - new ServerDescription(this.description.address, event.reply, { - roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) - }) - ); - - if (this.s.state === STATE_CONNECTING) { - stateTransition(this, STATE_CONNECTED); - this.emit('connect', this); - } - }); - } - - get description() { - return this.s.description; - } - - get supportsRetryableWrites() { - return supportsRetryableWrites(this); - } - - get name() { - return this.s.description.address; - } - - get autoEncrypter() { - if (this.s.options && this.s.options.autoEncrypter) { - return this.s.options.autoEncrypter; - } - return null; - } - - /** - * Initiate server connect - */ - connect() { - if (this.s.state !== STATE_CLOSED) { - return; - } - - stateTransition(this, STATE_CONNECTING); - this[kMonitor].connect(); - } - - /** - * Destroy the server connection - * - * @param {object} [options] Optional settings - * @param {Boolean} [options.force=false] Force destroy the pool - */ - destroy(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { force: false }, options); - - if (this.s.state === STATE_CLOSED) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CLOSING); - - this[kMonitor].close(); - this.s.pool.close(options, err => { - stateTransition(this, STATE_CLOSED); - this.emit('closed'); - if (typeof callback === 'function') { - callback(err); - } - }); - } - - /** - * Immediately schedule monitoring of this server. If there already an attempt being made - * this will be a no-op. - */ - requestCheck() { - this[kMonitor].requestCheck(); - } - - /** - * Execute a command - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {object} [options] Optional settings - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - options.serverApi = this.serverApi; - - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - const error = basicReadValidations(this, options); - if (error) { - return callback(error); - } - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (this.s.logger.isDebug()) { - const extractedCommand = extractCommand(cmd); - this.s.logger.debug( - `executing command [${JSON.stringify({ - ns, - cmd: extractedCommand.shouldRedact ? `${extractedCommand.name} details REDACTED` : cmd, - options: debugOptions(DEBUG_FIELDS, options) - })}] against ${this.name}` - ); - } - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - callback(new MongoError(`server ${this.name} does not support collation`)); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.command(ns, cmd, options, makeOperationHandler(this, conn, cmd, options, cb)); - }, callback); - } - - /** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ - query(ns, cmd, cursorState, options, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.query(ns, cmd, cursorState, options, makeOperationHandler(this, conn, cmd, options, cb)); - }, callback); - } - - /** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ - getMore(ns, cursorState, batchSize, options, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.getMore( - ns, - cursorState, - batchSize, - options, - makeOperationHandler(this, conn, null, options, cb) - ); - }, callback); - } - - /** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ - killCursors(ns, cursorState, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - if (typeof callback === 'function') { - callback(new MongoError('server is closed')); - } - - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.killCursors(ns, cursorState, makeOperationHandler(this, conn, null, undefined, cb)); - }, callback); - } - - /** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); - } -} - -Object.defineProperty(Server.prototype, 'clusterTime', { - get: function() { - return this.s.topology.clusterTime; - }, - set: function(clusterTime) { - this.s.topology.clusterTime = clusterTime; - } -}); - -function supportsRetryableWrites(server) { - return ( - server.description.maxWireVersion >= 6 && - server.description.logicalSessionTimeoutMinutes && - server.description.type !== ServerType.Standalone - ); -} - -function calculateRoundTripTime(oldRtt, duration) { - if (oldRtt === -1) { - return duration; - } - - const alpha = 0.2; - return alpha * duration + (1 - alpha) * oldRtt; -} - -function basicReadValidations(server, options) { - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - return new MongoError('readPreference must be an instance of ReadPreference'); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const server = args.server; - const op = args.op; - const ns = args.ns; - const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; - - if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - if (collationNotSupported(server, options)) { - callback(new MongoError(`server ${server.name} does not support collation`)); - return; - } - const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0; - if (unacknowledgedWrite || maxWireVersion(server) < 5) { - if ((op === 'update' || op === 'remove') && ops.find(o => o.hint)) { - callback(new MongoError(`servers < 3.4 do not support hint on ${op}`)); - return; - } - } - - server.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(server, err); - return cb(err); - } - - conn[op](ns, ops, options, makeOperationHandler(server, conn, ops, options, cb)); - }, callback); -} - -function markServerUnknown(server, error) { - if (error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError)) { - server[kMonitor].reset(); - } - - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, null, { - error, - topologyVersion: - error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion - }) - ); -} - -function connectionIsStale(pool, connection) { - return connection.generation !== pool.generation; -} - -function shouldHandleStateChangeError(server, err) { - const etv = err.topologyVersion; - const stv = server.description.topologyVersion; - - return compareTopologyVersion(stv, etv) < 0; -} - -function inActiveTransaction(session, cmd) { - return session && session.inTransaction() && !isTransactionCommand(cmd); -} - -function makeOperationHandler(server, connection, cmd, options, callback) { - const session = options && options.session; - - return function handleOperationResult(err, result) { - if (err && !connectionIsStale(server.s.pool, connection)) { - if (err instanceof MongoNetworkError) { - if (session && !session.hasEnded) { - session.serverSession.isDirty = true; - } - - if (supportsRetryableWrites(server) && !inActiveTransaction(session, cmd)) { - err.addErrorLabel('RetryableWriteError'); - } - - if (!(err instanceof MongoNetworkTimeoutError) || isNetworkErrorBeforeHandshake(err)) { - markServerUnknown(server, err); - server.s.pool.clear(); - } - } else { - // if pre-4.4 server, then add error label if its a retryable write error - if ( - maxWireVersion(server) < 9 && - isRetryableWriteError(err) && - !inActiveTransaction(session, cmd) - ) { - err.addErrorLabel('RetryableWriteError'); - } - - if (isSDAMUnrecoverableError(err)) { - if (shouldHandleStateChangeError(server, err)) { - if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(err)) { - server.s.pool.clear(); - } - - markServerUnknown(server, err); - process.nextTick(() => server.requestCheck()); - } - } - } - } - - callback(err, result); - }; -} - -module.exports = { - Server -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/server_description.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/server_description.js deleted file mode 100644 index 262cafe..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/server_description.js +++ /dev/null @@ -1,231 +0,0 @@ -'use strict'; - -const arrayStrictEqual = require('../utils').arrayStrictEqual; -const tagsStrictEqual = require('../utils').tagsStrictEqual; -const errorStrictEqual = require('../utils').errorStrictEqual; -const ServerType = require('./common').ServerType; -const now = require('../../utils').now; - -const WRITABLE_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.Standalone, - ServerType.Mongos -]); - -const DATA_BEARING_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.RSSecondary, - ServerType.Mongos, - ServerType.Standalone -]); - -const ISMASTER_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - 'compression', - 'me', - 'hosts', - 'passives', - 'arbiters', - 'tags', - 'setName', - 'setVersion', - 'electionId', - 'primary', - 'logicalSessionTimeoutMinutes', - 'saslSupportedMechs', - '__nodejs_mock_server__', - '$clusterTime' -]; - -/** - * The client's view of a single server, based on the most recent ismaster outcome. - * - * Internal type, not meant to be directly instantiated - */ -class ServerDescription { - /** - * Create a ServerDescription - * @param {String} address The address of the server - * @param {Object} [ismaster] An optional ismaster response for this server - * @param {Object} [options] Optional settings - * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) - * @param {Error} [options.error] An Error used for better reporting debugging - * @param {any} [options.topologyVersion] The topologyVersion - */ - constructor(address, ismaster, options) { - options = options || {}; - ismaster = Object.assign( - { - minWireVersion: 0, - maxWireVersion: 0, - hosts: [], - passives: [], - arbiters: [], - tags: [] - }, - ismaster - ); - - if (ismaster.isWritablePrimary != null) { - ismaster.ismaster = ismaster.isWritablePrimary; - } - - this.address = address; - this.error = options.error; - this.roundTripTime = options.roundTripTime || -1; - this.lastUpdateTime = now(); - this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; - this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; - this.type = parseServerType(ismaster); - this.topologyVersion = options.topologyVersion || ismaster.topologyVersion; - - // direct mappings - ISMASTER_FIELDS.forEach(field => { - if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; - }); - - // normalize case for hosts - if (this.me) this.me = this.me.toLowerCase(); - this.hosts = this.hosts.map(host => host.toLowerCase()); - this.passives = this.passives.map(host => host.toLowerCase()); - this.arbiters = this.arbiters.map(host => host.toLowerCase()); - } - - get allHosts() { - return this.hosts.concat(this.arbiters).concat(this.passives); - } - - /** - * @return {Boolean} Is this server available for reads - */ - get isReadable() { - return this.type === ServerType.RSSecondary || this.isWritable; - } - - /** - * @return {Boolean} Is this server data bearing - */ - get isDataBearing() { - return DATA_BEARING_SERVER_TYPES.has(this.type); - } - - /** - * @return {Boolean} Is this server available for writes - */ - get isWritable() { - return WRITABLE_SERVER_TYPES.has(this.type); - } - - get host() { - const chopLength = `:${this.port}`.length; - return this.address.slice(0, -chopLength); - } - - get port() { - const port = this.address.split(':').pop(); - return port ? Number.parseInt(port, 10) : port; - } - - /** - * Determines if another `ServerDescription` is equal to this one per the rules defined - * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} - * - * @param {ServerDescription} other - * @return {Boolean} - */ - equals(other) { - const topologyVersionsEqual = - this.topologyVersion === other.topologyVersion || - compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0; - - return ( - other != null && - errorStrictEqual(this.error, other.error) && - this.type === other.type && - this.minWireVersion === other.minWireVersion && - this.me === other.me && - arrayStrictEqual(this.hosts, other.hosts) && - tagsStrictEqual(this.tags, other.tags) && - this.setName === other.setName && - this.setVersion === other.setVersion && - (this.electionId - ? other.electionId && this.electionId.equals(other.electionId) - : this.electionId === other.electionId) && - this.primary === other.primary && - this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && - topologyVersionsEqual - ); - } -} - -/** - * Parses an `ismaster` message and determines the server type - * - * @param {Object} ismaster The `ismaster` message to parse - * @return {ServerType} - */ -function parseServerType(ismaster) { - if (!ismaster || !ismaster.ok) { - return ServerType.Unknown; - } - - if (ismaster.isreplicaset) { - return ServerType.RSGhost; - } - - if (ismaster.msg && ismaster.msg === 'isdbgrid') { - return ServerType.Mongos; - } - - if (ismaster.setName) { - if (ismaster.hidden) { - return ServerType.RSOther; - } else if (ismaster.ismaster) { - return ServerType.RSPrimary; - } else if (ismaster.secondary) { - return ServerType.RSSecondary; - } else if (ismaster.arbiterOnly) { - return ServerType.RSArbiter; - } else { - return ServerType.RSOther; - } - } - - return ServerType.Standalone; -} - -/** - * Compares two topology versions. - * - * @param {object} lhs - * @param {object} rhs - * @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent. - */ -function compareTopologyVersion(lhs, rhs) { - if (lhs == null || rhs == null) { - return -1; - } - - if (lhs.processId.equals(rhs.processId)) { - // TODO: handle counters as Longs - if (lhs.counter === rhs.counter) { - return 0; - } else if (lhs.counter < rhs.counter) { - return -1; - } - - return 1; - } - - return -1; -} - -module.exports = { - ServerDescription, - parseServerType, - compareTopologyVersion -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/server_selection.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/server_selection.js deleted file mode 100644 index 80d86ec..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/server_selection.js +++ /dev/null @@ -1,238 +0,0 @@ -'use strict'; -const ServerType = require('./common').ServerType; -const TopologyType = require('./common').TopologyType; -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; - -// max staleness constants -const IDLE_WRITE_PERIOD = 10000; -const SMALLEST_MAX_STALENESS_SECONDS = 90; - -/** - * Returns a server selector that selects for writable servers - */ -function writableServerSelector() { - return function(topologyDescription, servers) { - return latencyWindowReducer( - topologyDescription, - servers.filter(s => s.isWritable) - ); - }; -} - -/** - * Reduces the passed in array of servers by the rules of the "Max Staleness" specification - * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst - * - * @param {ReadPreference} readPreference The read preference providing max staleness guidance - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of server descriptions to be reduced - * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness - */ -function maxStalenessReducer(readPreference, topologyDescription, servers) { - if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { - return servers; - } - - const maxStaleness = readPreference.maxStalenessSeconds; - const maxStalenessVariance = - (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; - if (maxStaleness < maxStalenessVariance) { - throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); - } - - if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { - throw new MongoError( - `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` - ); - } - - if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { - const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; - return servers.reduce((result, server) => { - const stalenessMS = - server.lastUpdateTime - - server.lastWriteDate - - (primary.lastUpdateTime - primary.lastWriteDate) + - topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } - - if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { - if (servers.length === 0) { - return servers; - } - - const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); - return servers.reduce((result, server) => { - const stalenessMS = - sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } - - return servers; -} - -/** - * Determines whether a server's tags match a given set of tags - * - * @param {String[]} tagSet The requested tag set to match - * @param {String[]} serverTags The server's tags - */ -function tagSetMatch(tagSet, serverTags) { - const keys = Object.keys(tagSet); - const serverTagKeys = Object.keys(serverTags); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { - return false; - } - } - - return true; -} - -/** - * Reduces a set of server descriptions based on tags requested by the read preference - * - * @param {ReadPreference} readPreference The read preference providing the requested tags - * @param {ServerDescription[]} servers The list of server descriptions to reduce - * @return {ServerDescription[]} The list of servers matching the requested tags - */ -function tagSetReducer(readPreference, servers) { - if ( - readPreference.tags == null || - (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) - ) { - return servers; - } - - for (let i = 0; i < readPreference.tags.length; ++i) { - const tagSet = readPreference.tags[i]; - const serversMatchingTagset = servers.reduce((matched, server) => { - if (tagSetMatch(tagSet, server.tags)) matched.push(server); - return matched; - }, []); - - if (serversMatchingTagset.length) { - return serversMatchingTagset; - } - } - - return []; -} - -/** - * Reduces a list of servers to ensure they fall within an acceptable latency window. This is - * further specified in the "Server Selection" specification, found here: - * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst - * - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of servers to reduce - * @returns {ServerDescription[]} The servers which fall within an acceptable latency window - */ -function latencyWindowReducer(topologyDescription, servers) { - const low = servers.reduce( - (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), - -1 - ); - - const high = low + topologyDescription.localThresholdMS; - - return servers.reduce((result, server) => { - if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); - return result; - }, []); -} - -// filters -function primaryFilter(server) { - return server.type === ServerType.RSPrimary; -} - -function secondaryFilter(server) { - return server.type === ServerType.RSSecondary; -} - -function nearestFilter(server) { - return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; -} - -function knownFilter(server) { - return server.type !== ServerType.Unknown; -} - -/** - * Returns a function which selects servers based on a provided read preference - * - * @param {ReadPreference} readPreference The read preference to select with - */ -function readPreferenceServerSelector(readPreference) { - if (!readPreference.isValid()) { - throw new TypeError('Invalid read preference specified'); - } - - return function(topologyDescription, servers) { - const commonWireVersion = topologyDescription.commonWireVersion; - if ( - commonWireVersion && - readPreference.minWireVersion && - readPreference.minWireVersion > commonWireVersion - ) { - throw new MongoError( - `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'` - ); - } - - if (topologyDescription.type === TopologyType.Unknown) { - return []; - } - - if ( - topologyDescription.type === TopologyType.Single || - topologyDescription.type === TopologyType.Sharded - ) { - return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); - } - - const mode = readPreference.mode; - if (mode === ReadPreference.PRIMARY) { - return servers.filter(primaryFilter); - } - - if (mode === ReadPreference.PRIMARY_PREFERRED) { - const result = servers.filter(primaryFilter); - if (result.length) { - return result; - } - } - - const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter; - const selectedServers = latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)) - ) - ); - - if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { - return servers.filter(primaryFilter); - } - - return selectedServers; - }; -} - -module.exports = { - writableServerSelector, - readPreferenceServerSelector -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/srv_polling.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/srv_polling.js deleted file mode 100644 index 2c0b6ee..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/srv_polling.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; - -const Logger = require('../connection/logger'); -const EventEmitter = require('events').EventEmitter; -const dns = require('dns'); -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -class SrvPollingEvent { - constructor(srvRecords) { - this.srvRecords = srvRecords; - } - - addresses() { - return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); - } -} - -class SrvPoller extends EventEmitter { - /** - * @param {object} options - * @param {string} options.srvHost - * @param {number} [options.heartbeatFrequencyMS] - * @param {function} [options.logger] - * @param {string} [options.loggerLevel] - */ - constructor(options) { - super(); - - if (!options || !options.srvHost) { - throw new TypeError('options for SrvPoller must exist and include srvHost'); - } - - this.srvHost = options.srvHost; - this.rescanSrvIntervalMS = 60000; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - this.logger = Logger('srvPoller', options); - - this.haMode = false; - this.generation = 0; - - this._timeout = null; - } - - get srvAddress() { - return `_mongodb._tcp.${this.srvHost}`; - } - - get intervalMS() { - return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; - } - - start() { - if (!this._timeout) { - this.schedule(); - } - } - - stop() { - if (this._timeout) { - clearTimeout(this._timeout); - this.generation += 1; - this._timeout = null; - } - } - - schedule() { - clearTimeout(this._timeout); - this._timeout = setTimeout(() => this._poll(), this.intervalMS); - } - - success(srvRecords) { - this.haMode = false; - this.schedule(); - this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); - } - - failure(message, obj) { - this.logger.warn(message, obj); - this.haMode = true; - this.schedule(); - } - - parentDomainMismatch(srvRecord) { - this.logger.warn( - `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, - srvRecord - ); - } - - _poll() { - const generation = this.generation; - dns.resolveSrv(this.srvAddress, (err, srvRecords) => { - if (generation !== this.generation) { - return; - } - - if (err) { - this.failure('DNS error', err); - return; - } - - const finalAddresses = []; - srvRecords.forEach(record => { - if (matchesParentDomain(record.name, this.srvHost)) { - finalAddresses.push(record); - } else { - this.parentDomainMismatch(record); - } - }); - - if (!finalAddresses.length) { - this.failure('No valid addresses found at host'); - return; - } - - this.success(finalAddresses); - }); - } -} - -module.exports.SrvPollingEvent = SrvPollingEvent; -module.exports.SrvPoller = SrvPoller; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/topology.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/topology.js deleted file mode 100644 index 49401f7..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/topology.js +++ /dev/null @@ -1,1161 +0,0 @@ -'use strict'; -const Denque = require('denque'); -const EventEmitter = require('events'); -const ServerDescription = require('./server_description').ServerDescription; -const ServerType = require('./common').ServerType; -const TopologyDescription = require('./topology_description').TopologyDescription; -const TopologyType = require('./common').TopologyType; -const events = require('./events'); -const Server = require('./server').Server; -const relayEvents = require('../utils').relayEvents; -const ReadPreference = require('../topologies/read_preference'); -const CoreCursor = require('../cursor').CoreCursor; -const deprecate = require('util').deprecate; -const BSON = require('../connection/utils').retrieveBSON(); -const createCompressionInfo = require('../topologies/shared').createCompressionInfo; -const ClientSession = require('../sessions').ClientSession; -const MongoError = require('../error').MongoError; -const MongoServerSelectionError = require('../error').MongoServerSelectionError; -const resolveClusterTime = require('../topologies/shared').resolveClusterTime; -const SrvPoller = require('./srv_polling').SrvPoller; -const getMMAPError = require('../topologies/shared').getMMAPError; -const makeStateMachine = require('../utils').makeStateMachine; -const eachAsync = require('../utils').eachAsync; -const emitDeprecationWarning = require('../../utils').emitDeprecationWarning; -const ServerSessionPool = require('../sessions').ServerSessionPool; -const makeClientMetadata = require('../utils').makeClientMetadata; -const CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES; -const compareTopologyVersion = require('./server_description').compareTopologyVersion; -const emitWarning = require('../../utils').emitWarning; - -const common = require('./common'); -const drainTimerQueue = common.drainTimerQueue; -const clearAndRemoveTimerFrom = common.clearAndRemoveTimerFrom; - -const serverSelection = require('./server_selection'); -const readPreferenceServerSelector = serverSelection.readPreferenceServerSelector; -const writableServerSelector = serverSelection.writableServerSelector; - -// Global state -let globalTopologyCounter = 0; - -// events that we relay to the `Topology` -const SERVER_RELAY_EVENTS = [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // NOTE: Legacy events - 'monitoring' -].concat(CMAP_EVENT_NAMES); - -// all events we listen to from `Server` instances -const LOCAL_SERVER_EVENTS = ['connect', 'descriptionReceived', 'close', 'ended']; - -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CONNECTING = common.STATE_CONNECTING; -const STATE_CONNECTED = common.STATE_CONNECTED; -const stateTransition = makeStateMachine({ - [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], - [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], - [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] -}); - -const DEPRECATED_OPTIONS = new Set([ - 'autoReconnect', - 'reconnectTries', - 'reconnectInterval', - 'bufferMaxEntries' -]); - -const kCancelled = Symbol('cancelled'); -const kWaitQueue = Symbol('waitQueue'); - -/** - * A container of server instances representing a connection to a MongoDB topology. - * - * @fires Topology#serverOpening - * @fires Topology#serverClosed - * @fires Topology#serverDescriptionChanged - * @fires Topology#topologyOpening - * @fires Topology#topologyClosed - * @fires Topology#topologyDescriptionChanged - * @fires Topology#serverHeartbeatStarted - * @fires Topology#serverHeartbeatSucceeded - * @fires Topology#serverHeartbeatFailed - */ -class Topology extends EventEmitter { - /** - * Create a topology - * - * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to - * @param {Object} [options] Optional settings - * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled - */ - constructor(seedlist, options) { - super(); - if (typeof options === 'undefined' && typeof seedlist !== 'string') { - options = seedlist; - seedlist = []; - - // this is for legacy single server constructor support - if (options.host) { - seedlist.push({ host: options.host, port: options.port }); - } - } - - seedlist = seedlist || []; - if (typeof seedlist === 'string') { - seedlist = parseStringSeedlist(seedlist); - } - - options = Object.assign({}, common.TOPOLOGY_DEFAULTS, options); - options = Object.freeze( - Object.assign(options, { - metadata: makeClientMetadata(options), - compression: { compressors: createCompressionInfo(options) } - }) - ); - - DEPRECATED_OPTIONS.forEach(optionName => { - if (options[optionName]) { - emitDeprecationWarning( - `The option \`${optionName}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, - 'DeprecationWarning' - ); - } - }); - - const topologyType = topologyTypeFromSeedlist(seedlist, options); - const topologyId = globalTopologyCounter++; - const serverDescriptions = seedlist.reduce((result, seed) => { - if (seed.domain_socket) seed.host = seed.domain_socket; - const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; - result.set(address, new ServerDescription(address)); - return result; - }, new Map()); - - this[kWaitQueue] = new Denque(); - this.s = { - // the id of this topology - id: topologyId, - // passed in options - options, - // initial seedlist of servers to connect to - seedlist: seedlist, - // initial state - state: STATE_CLOSED, - // the topology description - description: new TopologyDescription( - topologyType, - serverDescriptions, - options.replicaSet, - null, - null, - null, - options - ), - serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, - heartbeatFrequencyMS: options.heartbeatFrequencyMS, - minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, - // allow users to override the cursor factory - Cursor: options.cursorFactory || CoreCursor, - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // a map of server instances to normalized addresses - servers: new Map(), - // Server Session Pool - sessionPool: new ServerSessionPool(this), - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise, - credentials: options.credentials, - clusterTime: null, - - // timer management - connectionTimers: new Set() - }; - this.serverApi = options.serverApi; - - if (options.srvHost) { - this.s.srvPoller = - options.srvPoller || - new SrvPoller({ - heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, - srvHost: options.srvHost, // TODO: GET THIS - logger: options.logger, - loggerLevel: options.loggerLevel - }); - this.s.detectTopologyDescriptionChange = ev => { - const previousType = ev.previousDescription.type; - const newType = ev.newDescription.type; - - if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { - this.s.handleSrvPolling = srvPollingHandler(this); - this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); - this.s.srvPoller.start(); - } - }; - - this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - } - - // NOTE: remove this when NODE-1709 is resolved - this.setMaxListeners(Infinity); - } - - /** - * @return A `TopologyDescription` for this topology - */ - get description() { - return this.s.description; - } - - get parserType() { - return BSON.native ? 'c++' : 'js'; - } - - /** - * Initiate server connect - * - * @param {Object} [options] Optional settings - * @param {Array} [options.auth=null] Array of auth options to apply on connect - * @param {function} [callback] An optional callback called once on the first connected server - */ - connect(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - if (this.s.state === STATE_CONNECTED) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CONNECTING); - - // emit SDAM monitoring events - this.emit('topologyOpening', new events.TopologyOpeningEvent(this.s.id)); - - // emit an event for the topology change - this.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - this.s.id, - new TopologyDescription(TopologyType.Unknown), // initial is always Unknown - this.s.description - ) - ); - - // connect all known servers, then attempt server selection to connect - connectServers(this, Array.from(this.s.description.servers.values())); - - ReadPreference.translate(options); - const readPreference = options.readPreference || ReadPreference.primary; - const connectHandler = err => { - if (err) { - this.close(); - - if (typeof callback === 'function') { - callback(err); - } else { - this.emit('error', err); - } - - return; - } - - stateTransition(this, STATE_CONNECTED); - this.emit('open', err, this); - this.emit('connect', this); - - if (typeof callback === 'function') callback(err, this); - }; - - // TODO: NODE-2471 - if (this.s.credentials) { - this.command('admin.$cmd', { ping: 1 }, { readPreference }, connectHandler); - return; - } - - this.selectServer(readPreferenceServerSelector(readPreference), options, connectHandler); - } - - /** - * Close this topology - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - if (typeof options === 'boolean') { - options = { force: options }; - } - - options = options || {}; - if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CLOSING); - - drainWaitQueue(this[kWaitQueue], new MongoError('Topology closed')); - drainTimerQueue(this.s.connectionTimers); - - if (this.s.srvPoller) { - this.s.srvPoller.stop(); - if (this.s.handleSrvPolling) { - this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); - delete this.s.handleSrvPolling; - } - } - - if (this.s.detectTopologyDescriptionChange) { - this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - delete this.s.detectTopologyDescriptionChange; - } - - this.s.sessions.forEach(session => session.endSession()); - this.s.sessionPool.endAllPooledSessions(() => { - eachAsync( - Array.from(this.s.servers.values()), - (server, cb) => destroyServer(server, this, options, cb), - err => { - this.s.servers.clear(); - - // emit an event for close - this.emit('topologyClosed', new events.TopologyClosedEvent(this.s.id)); - - stateTransition(this, STATE_CLOSED); - - if (typeof callback === 'function') { - callback(err); - } - } - ); - }); - } - - /** - * Selects a server according to the selection predicate provided - * - * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window - * @param {object} [options] Optional settings related to server selection - * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error - * @param {function} callback The callback used to indicate success or failure - * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided - */ - selectServer(selector, options, callback) { - if (typeof options === 'function') { - callback = options; - if (typeof selector !== 'function') { - options = selector; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else if (typeof selector === 'string') { - readPreference = new ReadPreference(selector); - } else { - ReadPreference.translate(options); - readPreference = options.readPreference || ReadPreference.primary; - } - - selector = readPreferenceServerSelector(readPreference); - } else { - options = {}; - } - } - - options = Object.assign( - {}, - { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, - options - ); - - const isSharded = this.description.type === TopologyType.Sharded; - const session = options.session; - const transaction = session && session.transaction; - - if (isSharded && transaction && transaction.server) { - callback(undefined, transaction.server); - return; - } - - // support server selection by options with readPreference - let serverSelector = selector; - if (typeof selector === 'object') { - const readPreference = selector.readPreference - ? selector.readPreference - : ReadPreference.primary; - - serverSelector = readPreferenceServerSelector(readPreference); - } - - const waitQueueMember = { - serverSelector, - transaction, - callback - }; - - const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; - if (serverSelectionTimeoutMS) { - waitQueueMember.timer = setTimeout(() => { - waitQueueMember[kCancelled] = true; - waitQueueMember.timer = undefined; - const timeoutError = new MongoServerSelectionError( - `Server selection timed out after ${serverSelectionTimeoutMS} ms`, - this.description - ); - - waitQueueMember.callback(timeoutError); - }, serverSelectionTimeoutMS); - } - - this[kWaitQueue].push(waitQueueMember); - processWaitQueue(this); - } - - // Sessions related methods - - /** - * @return Whether the topology should initiate selection to determine session support - */ - shouldCheckForSessionSupport() { - if (this.description.type === TopologyType.Single) { - return !this.description.hasKnownServers; - } - - return !this.description.hasDataBearingServers; - } - - /** - * @return Whether sessions are supported on the current topology - */ - hasSessionSupport() { - return this.description.logicalSessionTimeoutMinutes != null; - } - - /** - * Start a logical session - */ - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - /** - * Send endSessions command(s) with the given session ids - * - * @param {Array} sessions The sessions to end - * @param {function} [callback] - */ - endSessions(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { - readPreference: ReadPreference.primaryPreferred, - noResponse: true, - serverApi: this.serverApi - }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } - - /** - * Update the internal TopologyDescription with a ServerDescription - * - * @param {object} serverDescription The server to update in the internal list of server descriptions - */ - serverUpdateHandler(serverDescription) { - if (!this.s.description.hasServer(serverDescription.address)) { - return; - } - - // ignore this server update if its from an outdated topologyVersion - if (isStaleServerDescription(this.s.description, serverDescription)) { - return; - } - - // these will be used for monitoring events later - const previousTopologyDescription = this.s.description; - const previousServerDescription = this.s.description.servers.get(serverDescription.address); - - // Driver Sessions Spec: "Whenever a driver receives a cluster time from - // a server it MUST compare it to the current highest seen cluster time - // for the deployment. If the new cluster time is higher than the - // highest seen cluster time it MUST become the new highest seen cluster - // time. Two cluster times are compared using only the BsonTimestamp - // value of the clusterTime embedded field." - const clusterTime = serverDescription.$clusterTime; - if (clusterTime) { - resolveClusterTime(this, clusterTime); - } - - // If we already know all the information contained in this updated description, then - // we don't need to emit SDAM events, but still need to update the description, in order - // to keep client-tracked attributes like last update time and round trip time up to date - const equalDescriptions = - previousServerDescription && previousServerDescription.equals(serverDescription); - - // first update the TopologyDescription - this.s.description = this.s.description.update(serverDescription); - if (this.s.description.compatibilityError) { - this.emit('error', new MongoError(this.s.description.compatibilityError)); - return; - } - - // emit monitoring events for this change - if (!equalDescriptions) { - this.emit( - 'serverDescriptionChanged', - new events.ServerDescriptionChangedEvent( - this.s.id, - serverDescription.address, - previousServerDescription, - this.s.description.servers.get(serverDescription.address) - ) - ); - } - - // update server list from updated descriptions - updateServers(this, serverDescription); - - // attempt to resolve any outstanding server selection attempts - if (this[kWaitQueue].length > 0) { - processWaitQueue(this); - } - - if (!equalDescriptions) { - this.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - this.s.id, - previousTopologyDescription, - this.s.description - ) - ); - } - } - - auth(credentials, callback) { - if (typeof credentials === 'function') (callback = credentials), (credentials = null); - if (typeof callback === 'function') callback(null, true); - } - - logout(callback) { - if (typeof callback === 'function') callback(null, true); - } - - // Basic operation support. Eventually this should be moved into command construction - // during the command refactor. - - /** - * Insert one or more documents - * - * @param {String} ns The full qualified namespace for this operation - * @param {Array} ops An array of documents to insert - * @param {Boolean} [options.ordered=true] Execute in order or out of order - * @param {Object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * - * @param {string} ns The fully qualified namespace for this operation - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); - } - - /** - * Execute a command - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - ReadPreference.translate(options); - const readPreference = options.readPreference || ReadPreference.primary; - - this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { - if (err) { - callback(err); - return; - } - - const notAlreadyRetrying = !options.retrying; - const retryWrites = !!options.retryWrites; - const hasSession = !!options.session; - const supportsRetryableWrites = server.supportsRetryableWrites; - const notInTransaction = !hasSession || !options.session.inTransaction(); - const willRetryWrite = - notAlreadyRetrying && - retryWrites && - hasSession && - supportsRetryableWrites && - notInTransaction && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!shouldRetryOperation(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - server.command(ns, cmd, options, cb); - }); - } - - /** - * Create a new cursor - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ - cursor(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - const CursorClass = options.cursorFactory || this.s.Cursor; - ReadPreference.translate(options); - - return new CursorClass(topology, ns, cmd, options); - } - - get clientMetadata() { - return this.s.options.metadata; - } - - isConnected() { - return this.s.state === STATE_CONNECTED; - } - - isDestroyed() { - return this.s.state === STATE_CLOSED; - } - - /** - * @deprecated This function is deprecated and will be removed in the next major version. - */ - unref() { - emitWarning('`unref` is a noop and will be removed in the next major version'); - } - - // NOTE: There are many places in code where we explicitly check the last isMaster - // to do feature support detection. This should be done any other way, but for - // now we will just return the first isMaster seen, which should suffice. - lastIsMaster() { - const serverDescriptions = Array.from(this.description.servers.values()); - if (serverDescriptions.length === 0) return {}; - - const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; - const result = sd || { maxWireVersion: this.description.commonWireVersion }; - return result; - } - - get logicalSessionTimeoutMinutes() { - return this.description.logicalSessionTimeoutMinutes; - } - - get bson() { - return this.s.bson; - } -} - -Object.defineProperty(Topology.prototype, 'clusterTime', { - enumerable: true, - get: function() { - return this.s.clusterTime; - }, - set: function(clusterTime) { - this.s.clusterTime = clusterTime; - } -}); - -// legacy aliases -Topology.prototype.destroy = deprecate( - Topology.prototype.close, - 'destroy() is deprecated, please use close() instead' -); - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -function isStaleServerDescription(topologyDescription, incomingServerDescription) { - const currentServerDescription = topologyDescription.servers.get( - incomingServerDescription.address - ); - const currentTopologyVersion = currentServerDescription.topologyVersion; - return ( - compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0 - ); -} - -/** - * Destroys a server, and removes all event listeners from the instance - * - * @param {Server} server - */ -function destroyServer(server, topology, options, callback) { - options = options || {}; - LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - - server.destroy(options, () => { - topology.emit( - 'serverClosed', - new events.ServerClosedEvent(topology.s.id, server.description.address) - ); - - SERVER_RELAY_EVENTS.forEach(event => server.removeAllListeners(event)); - if (typeof callback === 'function') { - callback(); - } - }); -} - -/** - * Parses a basic seedlist in string form - * - * @param {string} seedlist The seedlist to parse - */ -function parseStringSeedlist(seedlist) { - return seedlist.split(',').map(seed => ({ - host: seed.split(':')[0], - port: seed.split(':')[1] || 27017 - })); -} - -function topologyTypeFromSeedlist(seedlist, options) { - if (options.directConnection) { - return TopologyType.Single; - } - - const replicaSet = options.replicaSet || options.setName || options.rs_name; - if (replicaSet == null) { - return TopologyType.Unknown; - } - - return TopologyType.ReplicaSetNoPrimary; -} - -function randomSelection(array) { - return array[Math.floor(Math.random() * array.length)]; -} - -function createAndConnectServer(topology, serverDescription, connectDelay) { - topology.emit( - 'serverOpening', - new events.ServerOpeningEvent(topology.s.id, serverDescription.address) - ); - - const server = new Server(serverDescription, topology.s.options, topology); - relayEvents(server, topology, SERVER_RELAY_EVENTS); - - server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); - - if (connectDelay) { - const connectTimer = setTimeout(() => { - clearAndRemoveTimerFrom(connectTimer, topology.s.connectionTimers); - server.connect(); - }, connectDelay); - - topology.s.connectionTimers.add(connectTimer); - return server; - } - - server.connect(); - return server; -} - -/** - * Create `Server` instances for all initially known servers, connect them, and assign - * them to the passed in `Topology`. - * - * @param {Topology} topology The topology responsible for the servers - * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect - */ -function connectServers(topology, serverDescriptions) { - topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { - const server = createAndConnectServer(topology, serverDescription); - servers.set(serverDescription.address, server); - return servers; - }, new Map()); -} - -function updateServers(topology, incomingServerDescription) { - // update the internal server's description - if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { - const server = topology.s.servers.get(incomingServerDescription.address); - server.s.description = incomingServerDescription; - } - - // add new servers for all descriptions we currently don't know about locally - for (const serverDescription of topology.description.servers.values()) { - if (!topology.s.servers.has(serverDescription.address)) { - const server = createAndConnectServer(topology, serverDescription); - topology.s.servers.set(serverDescription.address, server); - } - } - - // for all servers no longer known, remove their descriptions and destroy their instances - for (const entry of topology.s.servers) { - const serverAddress = entry[0]; - if (topology.description.hasServer(serverAddress)) { - continue; - } - - const server = topology.s.servers.get(serverAddress); - topology.s.servers.delete(serverAddress); - - // prepare server for garbage collection - destroyServer(server, topology); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const topology = args.topology; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - topology.selectServer(writableServerSelector(), options, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const notAlreadyRetrying = !args.retrying; - const retryWrites = !!options.retryWrites; - const hasSession = !!options.session; - const supportsRetryableWrites = server.supportsRetryableWrites; - const notInTransaction = !hasSession || !options.session.inTransaction(); - const notExplaining = options.explain === undefined; - const willRetryWrite = - notAlreadyRetrying && - retryWrites && - hasSession && - supportsRetryableWrites && - notInTransaction && - notExplaining; - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!shouldRetryOperation(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // execute the write operation - server[op](ns, ops, options, handler); - }); -} - -function shouldRetryOperation(err) { - return err instanceof MongoError && err.hasErrorLabel('RetryableWriteError'); -} - -function srvPollingHandler(topology) { - return function handleSrvPolling(ev) { - const previousTopologyDescription = topology.s.description; - topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); - if (topology.s.description === previousTopologyDescription) { - // Nothing changed, so return - return; - } - - updateServers(topology); - - topology.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - topology.s.id, - previousTopologyDescription, - topology.s.description - ) - ); - }; -} - -function drainWaitQueue(queue, err) { - while (queue.length) { - const waitQueueMember = queue.shift(); - clearTimeout(waitQueueMember.timer); - if (!waitQueueMember[kCancelled]) { - waitQueueMember.callback(err); - } - } -} - -function processWaitQueue(topology) { - if (topology.s.state === STATE_CLOSED) { - drainWaitQueue(topology[kWaitQueue], new MongoError('Topology is closed, please connect')); - return; - } - - const serverDescriptions = Array.from(topology.description.servers.values()); - const membersToProcess = topology[kWaitQueue].length; - for (let i = 0; i < membersToProcess && topology[kWaitQueue].length; ++i) { - const waitQueueMember = topology[kWaitQueue].shift(); - if (waitQueueMember[kCancelled]) { - continue; - } - - let selectedDescriptions; - try { - const serverSelector = waitQueueMember.serverSelector; - selectedDescriptions = serverSelector - ? serverSelector(topology.description, serverDescriptions) - : serverDescriptions; - } catch (e) { - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(e); - continue; - } - - if (selectedDescriptions.length === 0) { - topology[kWaitQueue].push(waitQueueMember); - continue; - } - - const selectedServerDescription = randomSelection(selectedDescriptions); - const selectedServer = topology.s.servers.get(selectedServerDescription.address); - const transaction = waitQueueMember.transaction; - const isSharded = topology.description.type === TopologyType.Sharded; - if (isSharded && transaction && transaction.isActive) { - transaction.pinServer(selectedServer); - } - - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(undefined, selectedServer); - } - - if (topology[kWaitQueue].length > 0) { - // ensure all server monitors attempt monitoring soon - topology.s.servers.forEach(server => process.nextTick(() => server.requestCheck())); - } -} - -/** - * A server opening SDAM monitoring event - * - * @event Topology#serverOpening - * @type {ServerOpeningEvent} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Topology#serverClosed - * @type {ServerClosedEvent} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Topology#serverDescriptionChanged - * @type {ServerDescriptionChangedEvent} - */ - -/** - * A topology open SDAM event - * - * @event Topology#topologyOpening - * @type {TopologyOpeningEvent} - */ - -/** - * A topology closed SDAM event - * - * @event Topology#topologyClosed - * @type {TopologyClosedEvent} - */ - -/** - * A topology structure SDAM change event - * - * @event Topology#topologyDescriptionChanged - * @type {TopologyDescriptionChangedEvent} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Topology#serverHeartbeatStarted - * @type {ServerHeartbeatStartedEvent} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Topology#serverHeartbeatFailed - * @type {ServerHearbeatFailedEvent} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Topology#serverHeartbeatSucceeded - * @type {ServerHeartbeatSucceededEvent} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Topology#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Topology#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Topology#commandFailed - * @type {object} - */ - -module.exports = { - Topology -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sdam/topology_description.js b/reverse_engineering/node_modules/mongodb/lib/core/sdam/topology_description.js deleted file mode 100644 index 6e01d65..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sdam/topology_description.js +++ /dev/null @@ -1,460 +0,0 @@ -'use strict'; -const ServerType = require('./common').ServerType; -const ServerDescription = require('./server_description').ServerDescription; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const TopologyType = require('./common').TopologyType; - -// contstants related to compatability checks -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; - -// Representation of a deployment of servers -class TopologyDescription { - /** - * Create a TopologyDescription - * - * @param {string} topologyType - * @param {Map} serverDescriptions the a map of address to ServerDescription - * @param {string} setName - * @param {number} maxSetVersion - * @param {ObjectId} maxElectionId - */ - constructor( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - options - ) { - options = options || {}; - - // TODO: consider assigning all these values to a temporary value `s` which - // we use `Object.freeze` on, ensuring the internal state of this type - // is immutable. - this.type = topologyType || TopologyType.Unknown; - this.setName = setName || null; - this.maxSetVersion = maxSetVersion || null; - this.maxElectionId = maxElectionId || null; - this.servers = serverDescriptions || new Map(); - this.stale = false; - this.compatible = true; - this.compatibilityError = null; - this.logicalSessionTimeoutMinutes = null; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; - this.localThresholdMS = options.localThresholdMS || 0; - this.commonWireVersion = commonWireVersion || null; - - // save this locally, but don't display when printing the instance out - Object.defineProperty(this, 'options', { value: options, enumberable: false }); - - // determine server compatibility - for (const serverDescription of this.servers.values()) { - if (serverDescription.type === ServerType.Unknown) continue; - - if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - } - - if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; - break; - } - } - - // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set - // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes - // value among ServerDescriptions of all data-bearing server types. If any have a null - // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be - // set to null. - this.logicalSessionTimeoutMinutes = null; - for (const addressServerTuple of this.servers) { - const server = addressServerTuple[1]; - if (server.isReadable) { - if (server.logicalSessionTimeoutMinutes == null) { - // If any of the servers have a null logicalSessionsTimeout, then the whole topology does - this.logicalSessionTimeoutMinutes = null; - break; - } - - if (this.logicalSessionTimeoutMinutes == null) { - // First server with a non null logicalSessionsTimeout - this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; - continue; - } - - // Always select the smaller of the: - // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout - this.logicalSessionTimeoutMinutes = Math.min( - this.logicalSessionTimeoutMinutes, - server.logicalSessionTimeoutMinutes - ); - } - } - } - - /** - * Returns a new TopologyDescription based on the SrvPollingEvent - * @param {SrvPollingEvent} ev The event - */ - updateFromSrvPollingEvent(ev) { - const newAddresses = ev.addresses(); - const serverDescriptions = new Map(this.servers); - for (const server of this.servers) { - if (newAddresses.has(server[0])) { - newAddresses.delete(server[0]); - } else { - serverDescriptions.delete(server[0]); - } - } - - if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { - return this; - } - - for (const address of newAddresses) { - serverDescriptions.set(address, new ServerDescription(address)); - } - - return new TopologyDescription( - this.type, - serverDescriptions, - this.setName, - this.maxSetVersion, - this.maxElectionId, - this.commonWireVersion, - this.options, - null - ); - } - - /** - * Returns a copy of this description updated with a given ServerDescription - * - * @param {ServerDescription} serverDescription - */ - update(serverDescription) { - const address = serverDescription.address; - // NOTE: there are a number of prime targets for refactoring here - // once we support destructuring assignments - - // potentially mutated values - let topologyType = this.type; - let setName = this.setName; - let maxSetVersion = this.maxSetVersion; - let maxElectionId = this.maxElectionId; - let commonWireVersion = this.commonWireVersion; - - if (serverDescription.setName && setName && serverDescription.setName !== setName) { - serverDescription = new ServerDescription(address, null); - } - - const serverType = serverDescription.type; - let serverDescriptions = new Map(this.servers); - - // update common wire version - if (serverDescription.maxWireVersion !== 0) { - if (commonWireVersion == null) { - commonWireVersion = serverDescription.maxWireVersion; - } else { - commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); - } - } - - // update the actual server description - serverDescriptions.set(address, serverDescription); - - if (topologyType === TopologyType.Single) { - // once we are defined as single, that never changes - return new TopologyDescription( - TopologyType.Single, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options - ); - } - - if (topologyType === TopologyType.Unknown) { - if (serverType === ServerType.Standalone && this.servers.size !== 1) { - serverDescriptions.delete(address); - } else { - topologyType = topologyTypeForServerType(serverType); - } - } - - if (topologyType === TopologyType.Sharded) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { - serverDescriptions.delete(address); - } - } - - if (topologyType === TopologyType.ReplicaSetNoPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - } - - if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); - (topologyType = result[0]), (setName = result[1]); - } - } - - if (topologyType === TopologyType.ReplicaSetWithPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - topologyType = checkHasPrimary(serverDescriptions); - } else if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - topologyType = updateRsWithPrimaryFromMember( - serverDescriptions, - setName, - serverDescription - ); - } else { - topologyType = checkHasPrimary(serverDescriptions); - } - } - - return new TopologyDescription( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options - ); - } - - get error() { - const descriptionsWithError = Array.from(this.servers.values()).filter(sd => sd.error); - if (descriptionsWithError.length > 0) { - return descriptionsWithError[0].error; - } - return undefined; - } - - /** - * Determines if the topology description has any known servers - */ - get hasKnownServers() { - return Array.from(this.servers.values()).some(sd => sd.type !== ServerType.Unknown); - } - - /** - * Determines if this topology description has a data-bearing server available. - */ - get hasDataBearingServers() { - return Array.from(this.servers.values()).some(sd => sd.isDataBearing); - } - - /** - * Determines if the topology has a definition for the provided address - * - * @param {String} address - * @return {Boolean} Whether the topology knows about this server - */ - hasServer(address) { - return this.servers.has(address); - } -} - -function topologyTypeForServerType(serverType) { - if (serverType === ServerType.Standalone) { - return TopologyType.Single; - } - - if (serverType === ServerType.Mongos) { - return TopologyType.Sharded; - } - - if (serverType === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } - - if (serverType === ServerType.RSGhost || serverType === ServerType.Unknown) { - return TopologyType.Unknown; - } - - return TopologyType.ReplicaSetNoPrimary; -} - -function compareObjectId(oid1, oid2) { - if (oid1 == null) { - return -1; - } - - if (oid2 == null) { - return 1; - } - - if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { - const oid1Buffer = oid1.id; - const oid2Buffer = oid2.id; - return oid1Buffer.compare(oid2Buffer); - } - - const oid1String = oid1.toString(); - const oid2String = oid2.toString(); - return oid1String.localeCompare(oid2String); -} - -function updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId -) { - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - - const electionId = serverDescription.electionId ? serverDescription.electionId : null; - if (serverDescription.setVersion && electionId) { - if (maxSetVersion && maxElectionId) { - if ( - maxSetVersion > serverDescription.setVersion || - compareObjectId(maxElectionId, electionId) > 0 - ) { - // this primary is stale, we must remove it - serverDescriptions.set( - serverDescription.address, - new ServerDescription(serverDescription.address) - ); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - } - - maxElectionId = serverDescription.electionId; - } - - if ( - serverDescription.setVersion != null && - (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) - ) { - maxSetVersion = serverDescription.setVersion; - } - - // We've heard from the primary. Is it the same primary as before? - for (const address of serverDescriptions.keys()) { - const server = serverDescriptions.get(address); - - if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { - // Reset old primary's type to Unknown. - serverDescriptions.set(address, new ServerDescription(server.address)); - - // There can only be one primary - break; - } - } - - // Discover new hosts from this primary's response. - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - // Remove hosts not in the response. - const currentAddresses = Array.from(serverDescriptions.keys()); - const responseAddresses = serverDescription.allHosts; - currentAddresses - .filter(addr => responseAddresses.indexOf(addr) === -1) - .forEach(address => { - serverDescriptions.delete(address); - }); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; -} - -function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { - if (setName == null) { - throw new TypeError('setName is required'); - } - - if ( - setName !== serverDescription.setName || - (serverDescription.me && serverDescription.address !== serverDescription.me) - ) { - serverDescriptions.delete(serverDescription.address); - } - - return checkHasPrimary(serverDescriptions); -} - -function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { - let topologyType = TopologyType.ReplicaSetNoPrimary; - - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [topologyType, setName]; - } - - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - if (serverDescription.me && serverDescription.address !== serverDescription.me) { - serverDescriptions.delete(serverDescription.address); - } - - return [topologyType, setName]; -} - -function checkHasPrimary(serverDescriptions) { - for (const addr of serverDescriptions.keys()) { - if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } - } - - return TopologyType.ReplicaSetNoPrimary; -} - -module.exports = { - TopologyDescription -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/sessions.js b/reverse_engineering/node_modules/mongodb/lib/core/sessions.js deleted file mode 100644 index 6865171..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/sessions.js +++ /dev/null @@ -1,783 +0,0 @@ -'use strict'; - -const retrieveBSON = require('./connection/utils').retrieveBSON; -const EventEmitter = require('events'); -const BSON = retrieveBSON(); -const Binary = BSON.Binary; -const uuidV4 = require('./utils').uuidV4; -const MongoError = require('./error').MongoError; -const isRetryableError = require('././error').isRetryableError; -const MongoNetworkError = require('./error').MongoNetworkError; -const MongoWriteConcernError = require('./error').MongoWriteConcernError; -const Transaction = require('./transactions').Transaction; -const TxnState = require('./transactions').TxnState; -const isPromiseLike = require('./utils').isPromiseLike; -const ReadPreference = require('./topologies/read_preference'); -const maybePromise = require('../utils').maybePromise; -const isTransactionCommand = require('./transactions').isTransactionCommand; -const resolveClusterTime = require('./topologies/shared').resolveClusterTime; -const isSharded = require('./wireprotocol/shared').isSharded; -const maxWireVersion = require('./utils').maxWireVersion; -const now = require('./../utils').now; -const calculateDurationInMs = require('./../utils').calculateDurationInMs; -const minWireVersionForShardedTransactions = 8; - -function assertAlive(session, callback) { - if (session.serverSession == null) { - const error = new MongoError('Cannot use a session that has ended'); - if (typeof callback === 'function') { - callback(error, null); - return false; - } - - throw error; - } - - return true; -} - -/** - * Options to pass when creating a Client Session - * @typedef {Object} SessionOptions - * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session - * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. - */ - -/** - * A BSON document reflecting the lsid of a {@link ClientSession} - * @typedef {Object} SessionId - */ - -const kServerSession = Symbol('serverSession'); - -/** - * A class representing a client session on the server - * WARNING: not meant to be instantiated directly. - * @class - * @hideconstructor - */ -class ClientSession extends EventEmitter { - /** - * Create a client session. - * WARNING: not meant to be instantiated directly - * - * @param {Topology} topology The current client's topology (Internal Class) - * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) - * @param {SessionOptions} [options] Optional settings - * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver - */ - constructor(topology, sessionPool, options, clientOptions) { - super(); - - if (topology == null) { - throw new Error('ClientSession requires a topology'); - } - - if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { - throw new Error('ClientSession requires a ServerSessionPool'); - } - - options = options || {}; - clientOptions = clientOptions || {}; - - this.topology = topology; - this.sessionPool = sessionPool; - this.hasEnded = false; - this.clientOptions = clientOptions; - this[kServerSession] = undefined; - - this.supports = { - causalConsistency: - typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true - }; - - this.clusterTime = options.initialClusterTime; - - this.operationTime = null; - this.explicit = !!options.explicit; - this.owner = options.owner; - this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); - this.transaction = new Transaction(); - } - - /** - * The server id associated with this session - * @type {SessionId} - */ - get id() { - return this.serverSession.id; - } - - get serverSession() { - if (this[kServerSession] == null) { - this[kServerSession] = this.sessionPool.acquire(); - } - - return this[kServerSession]; - } - - /** - * Ends this session on the server - * - * @param {Object} [options] Optional settings. Currently reserved for future use - * @param {Function} [callback] Optional callback for completion of this operation - */ - endSession(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const session = this; - return maybePromise(this, callback, done => { - if (session.hasEnded) { - return done(); - } - - function completeEndSession() { - // release the server session back to the pool - session.sessionPool.release(session.serverSession); - session[kServerSession] = undefined; - - // mark the session as ended, and emit a signal - session.hasEnded = true; - session.emit('ended', session); - - // spec indicates that we should ignore all errors for `endSessions` - done(); - } - - if (session.serverSession && session.inTransaction()) { - session.abortTransaction(err => { - if (err) return done(err); - completeEndSession(); - }); - - return; - } - - completeEndSession(); - }); - } - - /** - * Advances the operationTime for a ClientSession. - * - * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to - */ - advanceOperationTime(operationTime) { - if (this.operationTime == null) { - this.operationTime = operationTime; - return; - } - - if (operationTime.greaterThan(this.operationTime)) { - this.operationTime = operationTime; - } - } - - /** - * Used to determine if this session equals another - * @param {ClientSession} session - * @return {boolean} true if the sessions are equal - */ - equals(session) { - if (!(session instanceof ClientSession)) { - return false; - } - - return this.id.id.buffer.equals(session.id.id.buffer); - } - - /** - * Increment the transaction number on the internal ServerSession - */ - incrementTransactionNumber() { - this.serverSession.txnNumber++; - } - - /** - * @returns {boolean} whether this session is currently in a transaction or not - */ - inTransaction() { - return this.transaction.isActive; - } - - /** - * Starts a new transaction with the given options. - * - * @param {TransactionOptions} options Options for the transaction - */ - startTransaction(options) { - assertAlive(this); - if (this.inTransaction()) { - throw new MongoError('Transaction already in progress'); - } - - const topologyMaxWireVersion = maxWireVersion(this.topology); - if ( - isSharded(this.topology) && - topologyMaxWireVersion != null && - topologyMaxWireVersion < minWireVersionForShardedTransactions - ) { - throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); - } - - // increment txnNumber - this.incrementTransactionNumber(); - - // create transaction state - this.transaction = new Transaction( - Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) - ); - - this.transaction.transition(TxnState.STARTING_TRANSACTION); - } - - /** - * Commits the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - commitTransaction(callback) { - return maybePromise(this, callback, done => endTransaction(this, 'commitTransaction', done)); - } - - /** - * Aborts the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - abortTransaction(callback) { - return maybePromise(this, callback, done => endTransaction(this, 'abortTransaction', done)); - } - - /** - * This is here to ensure that ClientSession is never serialized to BSON. - * @ignore - */ - toBSON() { - throw new Error('ClientSession cannot be serialized to BSON.'); - } - - /** - * A user provided function to be run within a transaction - * - * @callback WithTransactionCallback - * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. - * @returns {Promise} The resulting Promise of operations run within this transaction - */ - - /** - * Runs a provided lambda within a transaction, retrying either the commit operation - * or entire transaction as needed (and when the error permits) to better ensure that - * the transaction can complete successfully. - * - * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not - * return a Promise will result in undefined behavior. - * - * @param {WithTransactionCallback} fn - * @param {TransactionOptions} [options] Optional settings for the transaction - */ - withTransaction(fn, options) { - const startTime = now(); - return attemptTransaction(this, startTime, fn, options); - } -} - -const MAX_WITH_TRANSACTION_TIMEOUT = 120000; -const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; -const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; -const MAX_TIME_MS_EXPIRED_CODE = 50; -const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ - 'CannotSatisfyWriteConcern', - 'UnknownReplWriteConcern', - 'UnsatisfiableWriteConcern' -]); - -function hasNotTimedOut(startTime, max) { - return calculateDurationInMs(startTime) < max; -} - -function isUnknownTransactionCommitResult(err) { - return ( - isMaxTimeMSExpiredError(err) || - (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && - err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && - err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) - ); -} - -function isMaxTimeMSExpiredError(err) { - if (err == null) return false; - return ( - err.code === MAX_TIME_MS_EXPIRED_CODE || - (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) - ); -} - -function attemptTransactionCommit(session, startTime, fn, options) { - return session.commitTransaction().catch(err => { - if ( - err instanceof MongoError && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && - !isMaxTimeMSExpiredError(err) - ) { - if (err.hasErrorLabel('UnknownTransactionCommitResult')) { - return attemptTransactionCommit(session, startTime, fn, options); - } - - if (err.hasErrorLabel('TransientTransactionError')) { - return attemptTransaction(session, startTime, fn, options); - } - } - - throw err; - }); -} - -const USER_EXPLICIT_TXN_END_STATES = new Set([ - TxnState.NO_TRANSACTION, - TxnState.TRANSACTION_COMMITTED, - TxnState.TRANSACTION_ABORTED -]); - -function userExplicitlyEndedTransaction(session) { - return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); -} - -function attemptTransaction(session, startTime, fn, options) { - session.startTransaction(options); - - let promise; - try { - promise = fn(session); - } catch (err) { - promise = Promise.reject(err); - } - - if (!isPromiseLike(promise)) { - session.abortTransaction(); - throw new TypeError('Function provided to `withTransaction` must return a Promise'); - } - - return promise - .then(() => { - if (userExplicitlyEndedTransaction(session)) { - return; - } - - return attemptTransactionCommit(session, startTime, fn, options); - }) - .catch(err => { - function maybeRetryOrThrow(err) { - if ( - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) - ) { - return attemptTransaction(session, startTime, fn, options); - } - - if (isMaxTimeMSExpiredError(err)) { - err.addErrorLabel('UnknownTransactionCommitResult'); - } - - throw err; - } - - if (session.transaction.isActive) { - return session.abortTransaction().then(() => maybeRetryOrThrow(err)); - } - - return maybeRetryOrThrow(err); - }); -} - -function endTransaction(session, commandName, callback) { - if (!assertAlive(session, callback)) { - // checking result in case callback was called - return; - } - - // handle any initial problematic cases - let txnState = session.transaction.state; - - if (txnState === TxnState.NO_TRANSACTION) { - callback(new MongoError('No transaction started')); - return; - } - - if (commandName === 'commitTransaction') { - if ( - txnState === TxnState.STARTING_TRANSACTION || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); - return; - } - } else { - if (txnState === TxnState.STARTING_TRANSACTION) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call abortTransaction twice')); - return; - } - - if ( - txnState === TxnState.TRANSACTION_COMMITTED || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); - return; - } - } - - // construct and send the command - const command = { [commandName]: 1 }; - - // apply a writeConcern if specified - let writeConcern; - if (session.transaction.options.writeConcern) { - writeConcern = Object.assign({}, session.transaction.options.writeConcern); - } else if (session.clientOptions && session.clientOptions.w) { - writeConcern = { w: session.clientOptions.w }; - } - - if (txnState === TxnState.TRANSACTION_COMMITTED) { - writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); - } - - if (writeConcern) { - Object.assign(command, { writeConcern }); - } - - if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { - Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); - } - - function commandHandler(e, r) { - if (commandName === 'commitTransaction') { - session.transaction.transition(TxnState.TRANSACTION_COMMITTED); - - if (e) { - if ( - e instanceof MongoNetworkError || - e instanceof MongoWriteConcernError || - isRetryableError(e) || - isMaxTimeMSExpiredError(e) - ) { - if (isUnknownTransactionCommitResult(e)) { - e.addErrorLabel('UnknownTransactionCommitResult'); - - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - } - } else if (e.hasErrorLabel('TransientTransactionError')) { - session.transaction.unpinServer(); - } - } - } else { - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - } - - callback(e, r); - } - - // The spec indicates that we should ignore all errors on `abortTransaction` - function transactionError(err) { - return commandName === 'commitTransaction' ? err : null; - } - - if ( - // Assumption here that commandName is "commitTransaction" or "abortTransaction" - session.transaction.recoveryToken && - supportsRecoveryToken(session) - ) { - command.recoveryToken = session.transaction.recoveryToken; - } - - // send the command - session.topology.command('admin.$cmd', command, { session }, (err, reply) => { - if (err && isRetryableError(err)) { - // SPEC-1185: apply majority write concern when retrying commitTransaction - if (command.commitTransaction) { - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - - command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { - w: 'majority' - }); - } - - return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => - commandHandler(transactionError(_err), _reply) - ); - } - - commandHandler(transactionError(err), reply); - }); -} - -function supportsRecoveryToken(session) { - const topology = session.topology; - return !!topology.s.options.useRecoveryToken; -} - -/** - * Reflects the existence of a session on the server. Can be reused by the session pool. - * WARNING: not meant to be instantiated directly. For internal use only. - * @ignore - */ -class ServerSession { - constructor() { - this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; - this.lastUse = now(); - this.txnNumber = 0; - this.isDirty = false; - } - - /** - * Determines if the server session has timed out. - * @ignore - * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" - * @return {boolean} true if the session has timed out. - */ - hasTimedOut(sessionTimeoutMinutes) { - // Take the difference of the lastUse timestamp and now, which will result in a value in - // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` - const idleTimeMinutes = Math.round( - ((calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000 - ); - - return idleTimeMinutes > sessionTimeoutMinutes - 1; - } -} - -/** - * Maintains a pool of Server Sessions. - * For internal use only - * @ignore - */ -class ServerSessionPool { - constructor(topology) { - if (topology == null) { - throw new Error('ServerSessionPool requires a topology'); - } - - this.topology = topology; - this.sessions = []; - } - - /** - * Ends all sessions in the session pool. - * @ignore - */ - endAllPooledSessions(callback) { - if (this.sessions.length) { - this.topology.endSessions( - this.sessions.map(session => session.id), - () => { - this.sessions = []; - if (typeof callback === 'function') { - callback(); - } - } - ); - - return; - } - - if (typeof callback === 'function') { - callback(); - } - } - - /** - * Acquire a Server Session from the pool. - * Iterates through each session in the pool, removing any stale sessions - * along the way. The first non-stale session found is removed from the - * pool and returned. If no non-stale session is found, a new ServerSession - * is created. - * @ignore - * @returns {ServerSession} - */ - acquire() { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const session = this.sessions.shift(); - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - return session; - } - } - - return new ServerSession(); - } - - /** - * Release a session to the session pool - * Adds the session back to the session pool if the session has not timed out yet. - * This method also removes any stale sessions from the pool. - * @ignore - * @param {ServerSession} session The session to release to the pool - */ - release(session) { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const pooledSession = this.sessions[this.sessions.length - 1]; - if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { - this.sessions.pop(); - } else { - break; - } - } - - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - if (session.isDirty) { - return; - } - - // otherwise, readd this session to the session pool - this.sessions.unshift(session); - } - } -} - -// TODO: this should be codified in command construction -// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern -function commandSupportsReadConcern(command, options) { - if ( - command.aggregate || - command.count || - command.distinct || - command.find || - command.parallelCollectionScan || - command.geoNear || - command.geoSearch - ) { - return true; - } - - if ( - command.mapReduce && - options && - options.out && - (options.out.inline === 1 || options.out === 'inline') - ) { - return true; - } - - return false; -} - -/** - * Optionally decorate a command with sessions specific keys - * - * @ignore - * @param {ClientSession} session the session tracking transaction state - * @param {Object} command the command to decorate - * @param {Object} topology the topology for tracking the cluster time - * @param {Object} [options] Optional settings passed to calling operation - * @return {MongoError|null} An error, if some error condition was met - */ -function applySession(session, command, options) { - if (session.hasEnded) { - // TODO: merge this with `assertAlive`, did not want to throw a try/catch here - return new MongoError('Cannot use a session that has ended'); - } - - // SPEC-1019: silently ignore explicit session with unacknowledged write for backwards compatibility - if (options && options.writeConcern && options.writeConcern.w === 0) { - return; - } - - const serverSession = session.serverSession; - serverSession.lastUse = now(); - command.lsid = serverSession.id; - - // first apply non-transaction-specific sessions data - const inTransaction = session.inTransaction() || isTransactionCommand(command); - const isRetryableWrite = options.willRetryWrite; - const shouldApplyReadConcern = commandSupportsReadConcern(command, options); - - if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { - command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); - } - - // now attempt to apply transaction-specific sessions data - if (!inTransaction) { - if (session.transaction.state !== TxnState.NO_TRANSACTION) { - session.transaction.transition(TxnState.NO_TRANSACTION); - } - - // TODO: the following should only be applied to read operation per spec. - // for causal consistency - if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - - return; - } - - if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { - return new MongoError( - `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` - ); - } - - // `autocommit` must always be false to differentiate from retryable writes - command.autocommit = false; - - if (session.transaction.state === TxnState.STARTING_TRANSACTION) { - session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); - command.startTransaction = true; - - const readConcern = - session.transaction.options.readConcern || session.clientOptions.readConcern; - if (readConcern) { - command.readConcern = readConcern; - } - - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - } -} - -function updateSessionFromResponse(session, document) { - if (document.$clusterTime) { - resolveClusterTime(session, document.$clusterTime); - } - - if (document.operationTime && session && session.supports.causalConsistency) { - session.advanceOperationTime(document.operationTime); - } - - if (document.recoveryToken && session && session.inTransaction()) { - session.transaction._recoveryToken = document.recoveryToken; - } -} - -module.exports = { - ClientSession, - ServerSession, - ServerSessionPool, - TxnState, - applySession, - updateSessionFromResponse, - commandSupportsReadConcern -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/tools/smoke_plugin.js b/reverse_engineering/node_modules/mongodb/lib/core/tools/smoke_plugin.js deleted file mode 100644 index 7488f0f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/tools/smoke_plugin.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results: [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: '' - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: 'fail', - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: '' - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - // eslint-disable-next-line no-console - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/topologies/mongos.js b/reverse_engineering/node_modules/mongodb/lib/core/topologies/mongos.js deleted file mode 100644 index 27eb237..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/topologies/mongos.js +++ /dev/null @@ -1,1398 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const CoreCursor = require('../cursor').CoreCursor; -const Logger = require('../connection/logger'); -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const diff = require('./shared').diff; -const cloneOptions = require('./shared').cloneOptions; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const BSON = retrieveBSON(); -const getMMAPError = require('./shared').getMMAPError; -const makeClientMetadata = require('../utils').makeClientMetadata; -const legacyIsRetryableWriteError = require('./shared').legacyIsRetryableWriteError; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - */ - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#reconnect - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#failed - * @fires Mongos#fullsetup - * @fires Mongos#all - * @fires Mongos#serverHeartbeatStarted - * @fires Mongos#serverHeartbeatSucceeded - * @fires Mongos#serverHeartbeatFailed - * @fires Mongos#topologyOpening - * @fires Mongos#topologyClosed - * @fires Mongos#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Mongos = function(seedlist, options) { - options = options || {}; - - // Get replSet Id - this.id = id++; - - // deduplicate seedlist - if (Array.isArray(seedlist)) { - seedlist = seedlist.reduce((seeds, seed) => { - if (seeds.find(s => s.host === seed.host && s.port === seed.port)) { - return seeds; - } - - seeds.push(seed); - return seeds; - }, []); - } - - // Internal state - this.s = { - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: Logger('Mongos', options), - // Seedlist - seedlist: seedlist, - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // localThresholdMS - localThresholdMS: options.localThresholdMS || 15 - }; - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Disconnected state - this.state = DISCONNECTED; - - // Current proxies we are connecting to - this.connectingProxies = []; - // Currently connected proxies - this.connectedProxies = []; - // Disconnected proxies - this.disconnectedProxies = []; - // Index of proxy to run operations against - this.index = 0; - // High availability timeout id - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - - // Description of the Replicaset - this.topologyDescription = { - topologyType: 'Unknown', - servers: [] - }; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; - - // Add event listener - EventEmitter.call(this); -}; - -inherits(Mongos, EventEmitter); -Object.assign(Mongos.prototype, SessionMixins); - -Object.defineProperty(Mongos.prototype, 'type', { - enumerable: true, - get: function() { - return 'mongos'; - } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; -function destroyServer(server, options, callback) { - options = options || {}; - SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - server.destroy(options, callback); -} - -/** - * Initiate server connect - */ -Mongos.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - const server = new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self - }) - ); - - relayEvents(server, self, ['serverDescriptionChanged']); - return server; - }); - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - - // Start all server connections - connectProxies(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -function handleEvent(self) { - return function() { - if (self.state === DESTROYED || self.state === DESTROYING) { - return; - } - - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Emit the left signal - self.emit('left', 'mongos', this); - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: this.name - }); - }; -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - - // Destroy the instance - if (self.state === DESTROYED) { - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - return this.destroy(); - } - - // Check the type of server - if (event === 'connect') { - // Get last known ismaster - self.ismaster = _this.lastIsMaster(); - - // Is this not a proxy, remove t - if (self.ismaster.msg === 'isdbgrid') { - // Add to the connectd list - for (let i = 0; i < self.connectedProxies.length; i++) { - if (self.connectedProxies[i].name === _this.name) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - _this.destroy(); - return self.emit('failed', _this); - } - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Move from connecting proxies connected - moveServerFrom(self.connectingProxies, self.connectedProxies, _this); - // Emit the joined event - self.emit('joined', 'mongos', _this); - } else { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; - // We have a standalone server - if (!self.ismaster.hosts) { - message = 'expected mongos proxy, but found standalone mongod for server %s'; - } - - self.s.logger.warn(f(message, _this.name)); - } - - // This is not a mongos proxy, destroy and remove it completely - _this.destroy(true); - removeProxyFrom(self.connectingProxies, _this); - // Emit the left event - self.emit('left', 'server', _this); - // Emit failed event - self.emit('failed', _this); - } - } else { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - // Emit the left event - self.emit('left', 'mongos', this); - // Emit failed event - self.emit('failed', this); - } - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Trigger topologyMonitor - if (self.connectingProxies.length === 0) { - // Emit connected if we are connected - if (self.connectedProxies.length > 0 && self.state === CONNECTING) { - // Set the state to connected - stateTransition(self, CONNECTED); - // Emit the connect event - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.disconnectedProxies.length === 0) { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - self.s.logger.warn( - f('no mongos proxies found in seed list, did you mean to connect to a replicaset') - ); - } - - // Emit the error that no proxies were found - return self.emit('error', new MongoError('no mongos proxies found in seed list')); - } - - // Topology monitor - topologyMonitor(self, { firstConnect: true }); - } - }; -} - -function connectProxies(self, servers) { - // Update connectingProxies - self.connectingProxies = self.connectingProxies.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.id, - address: server.name - }); - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - servers.forEach(server => connect(server, timeoutInterval++)); -} - -function pickProxy(self, session) { - // TODO: Destructure :) - const transaction = session && session.transaction; - - if (transaction && transaction.server) { - if (transaction.server.isConnected()) { - return transaction.server; - } else { - transaction.unpinServer(); - } - } - - // Get the currently connected Proxies - var connectedProxies = self.connectedProxies.slice(0); - - // Set lower bound - var lowerBoundLatency = Number.MAX_VALUE; - - // Determine the lower bound for the Proxies - for (var i = 0; i < connectedProxies.length; i++) { - if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { - lowerBoundLatency = connectedProxies[i].lastIsMasterMS; - } - } - - // Filter out the possible servers - connectedProxies = connectedProxies.filter(function(server) { - if ( - server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && - server.isConnected() - ) { - return true; - } - }); - - let proxy; - - // We have no connectedProxies pick first of the connected ones - if (connectedProxies.length === 0) { - proxy = self.connectedProxies[0]; - } else { - // Get proxy - proxy = connectedProxies[self.index % connectedProxies.length]; - // Update the index - self.index = (self.index + 1) % connectedProxies.length; - } - - if (transaction && transaction.isActive && proxy && proxy.isConnected()) { - transaction.pinServer(proxy); - } - - // Return the proxy - return proxy; -} - -function moveServerFrom(from, to, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } - - for (i = 0; i < to.length; i++) { - if (to[i].name === proxy.name) { - to.splice(i, 1); - } - } - - to.push(proxy); -} - -function removeProxyFrom(from, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } -} - -function reconnectProxies(self, proxies, callback) { - // Count lefts - var count = proxies.length; - - // Handle events - var _handleEvent = function(self, event) { - return function() { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return this.destroy(); - } - - if (event === 'connect') { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return _self.destroy(); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Move to the connected servers - moveServerFrom(self.connectingProxies, self.connectedProxies, _self); - // Emit topology Change - emitTopologyDescriptionChanged(self); - // Emit joined event - self.emit('joined', 'mongos', _self); - } else { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - this.destroy(); - } - - // Are we done finish up callback - if (count === 0) { - callback(); - } - }; - }; - - // No new servers - if (count === 0) { - return callback(); - } - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.name.split(':')[0], - port: parseInt(_server.name.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self - }) - ); - - destroyServer(_server, { force: true }); - removeProxyFrom(self.disconnectedProxies, _server); - - // Relay the server description change - relayEvents(server, self, ['serverDescriptionChanged']); - - // Emit opening server event - self.emit('serverOpening', { - topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, - address: server.name - }); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Connect to proxy - self.connectingProxies.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < proxies.length; i++) { - execute(proxies[i], i); - } -} - -function topologyMonitor(self, options) { - options = options || {}; - - // no need to set up the monitor if we're already closed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Set momitoring timeout - self.haTimeoutId = setTimeout(function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.isConnected() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } - - // Get the connectingServers - var proxies = self.connectedProxies.slice(0); - // Get the count - var count = proxies.length; - - // If the count is zero schedule a new fast - function pingServer(_self, _server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); - - // Execute ismaster - _server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - // Move from connectingProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - _server.destroy(); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: _server.name - }); - // Move from connected proxies to disconnected proxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - } else { - // Update the server ismaster - _server.ismaster = r.result; - _server.lastIsMasterMS = latencyMS; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: _server.name - }); - } - - cb(err, r); - } - ); - } - - // No proxies initiate monitor again - if (proxies.length === 0) { - // Emit close event if any listeners registered - if (self.listeners('close').length > 0 && self.state === CONNECTING) { - self.emit('error', new MongoError('no mongos proxy available')); - } else { - self.emit('close', self); - } - - // Attempt to connect to any unknown servers - return reconnectProxies(self, self.disconnectedProxies, function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Are we connected ? emit connect event - if (self.state === CONNECTING && options.firstConnect) { - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.isConnected()) { - self.emit('reconnect', self); - } else if (!self.isConnected() && self.listeners('close').length > 0) { - self.emit('close', self); - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - - // Ping all servers - for (var i = 0; i < proxies.length; i++) { - pingServer(self, proxies[i], function() { - count = count - 1; - - if (count === 0) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Attempt to connect to any unknown servers - reconnectProxies(self, self.disconnectedProxies, function() { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - }); - } - }, self.s.haInterval); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Mongos.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - proxies.forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -Mongos.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - stateTransition(this, DESTROYING); - if (this.haTimeoutId) { - clearTimeout(this.haTimeoutId); - } - - const proxies = this.connectedProxies.concat(this.connectingProxies); - let serverCount = proxies.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - emitTopologyDescriptionChanged(this); - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - stateTransition(this, DESTROYED); - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - // Destroy all connecting servers - proxies.forEach(server => { - // Emit the sdam event - this.emit('serverClosed', { - topologyId: this.id, - address: server.name - }); - - destroyServer(server, options, serverDestroyed); - moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); - }); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.connectedProxies.length > 0; -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -// -// Operations -// - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - // Pick a server - let server = pickProxy(self, options.session); - // No server found error out - if (!server) return callback(new MongoError('no mongos proxy available')); - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - options.explain === undefined; - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!legacyIsRetryableWriteError(err, self) || !willRetryWrite) { - err = getMMAPError(err); - return callback(err); - } - - // Pick another server - server = pickProxy(self, options.session); - - // No server found error out with original error - if (!server) { - return callback(err); - } - - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // rerun the operation - server[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - var self = this; - - // Pick a proxy - var server = pickProxy(self, options.session); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // No server returned we had an error - if (server == null) { - return callback(new MongoError('no mongos proxy available')); - } - - // Cloned options - var clonedOptions = cloneOptions(options); - clonedOptions.topology = self; - - const willRetryWrite = - !options.retrying && - options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!legacyIsRetryableWriteError(err, self)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, clonedOptions, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - clonedOptions.session.incrementTransactionNumber(); - clonedOptions.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, clonedOptions, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Mongos.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Specify a session if it is being used - * @param {function} callback - */ -Mongos.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - options = options || {}; - - const server = pickProxy(this, options.session); - if (server == null) { - callback(new MongoError('server selection failed')); - return; - } - - if (this.s.debug) this.emit('pickedServer', null, server); - callback(null, server); -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - var connections = []; - - for (var i = 0; i < this.connectedProxies.length; i++) { - connections = connections.concat(this.connectedProxies[i].connections()); - } - - return connections; -}; - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - if (self.connectedProxies.length > 0) { - topology = 'Sharded'; - } - - // Generate description - var description = { - topologyType: topology, - servers: [] - }; - - // All proxies - var proxies = self.disconnectedProxies.concat(self.connectingProxies); - - // Add all the disconnected proxies - description.servers = description.servers.concat( - proxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Unknown'; - return description; - }) - ); - - // Add all the connected proxies - description.servers = description.servers.concat( - self.connectedProxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Mongos'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.topologyDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.topologyDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - if (diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - } - - // Set the new description - self.topologyDescription = description; - } -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A mongos reconnect event, used to verify that the mongos topology has reconnected - * - * @event Mongos#reconnect - * @type {Mongos} - */ - -/** - * A mongos fullsetup event, used to signal that all topology members have been contacted. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * A mongos all event, used to signal that all topology members have been contacted. - * - * @event Mongos#all - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event Mongos#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Mongos#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Mongos#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Mongos#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Mongos#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Mongos#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Mongos#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Mongos#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Mongos#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/topologies/read_preference.js b/reverse_engineering/node_modules/mongodb/lib/core/topologies/read_preference.js deleted file mode 100644 index afd2362..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/topologies/read_preference.js +++ /dev/null @@ -1,267 +0,0 @@ -'use strict'; -const emitWarningOnce = require('../../utils').emitWarningOnce; - -/** - * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * @class - * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {array} tags The tags object - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. - * @param {object} [options.hedge] Server mode in which the same query is dispatched in parallel to multiple replica set members. - * @param {boolean} [options.hedge.enabled] Explicitly enable or disable hedged reads. - * @see https://docs.mongodb.com/manual/core/read-preference/ - * @return {ReadPreference} - */ -const ReadPreference = function(mode, tags, options) { - if (!ReadPreference.isValid(mode)) { - throw new TypeError(`Invalid read preference mode ${mode}`); - } - - // TODO(major): tags MUST be an array of tagsets - if (tags && !Array.isArray(tags)) { - emitWarningOnce( - 'ReadPreference tags must be an array, this will change in the next major version' - ); - - const tagsHasMaxStalenessSeconds = typeof tags.maxStalenessSeconds !== 'undefined'; - const tagsHasHedge = typeof tags.hedge !== 'undefined'; - const tagsHasOptions = tagsHasMaxStalenessSeconds || tagsHasHedge; - if (tagsHasOptions) { - // this is likely an options object - options = tags; - tags = undefined; - } else { - tags = [tags]; - } - } - - this.mode = mode; - this.tags = tags; - this.hedge = options && options.hedge; - - options = options || {}; - if (options.maxStalenessSeconds != null) { - if (options.maxStalenessSeconds <= 0) { - throw new TypeError('maxStalenessSeconds must be a positive integer'); - } - - this.maxStalenessSeconds = options.maxStalenessSeconds; - - // NOTE: The minimum required wire version is 5 for this read preference. If the existing - // topology has a lower value then a MongoError will be thrown during server selection. - this.minWireVersion = 5; - } - - if (this.mode === ReadPreference.PRIMARY) { - if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { - throw new TypeError('Primary read preference cannot be combined with tags'); - } - - if (this.maxStalenessSeconds) { - throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); - } - - if (this.hedge) { - throw new TypeError('Primary read preference cannot be combined with hedge'); - } - } -}; - -// Support the deprecated `preference` property introduced in the porcelain layer -Object.defineProperty(ReadPreference.prototype, 'preference', { - enumerable: true, - get: function() { - return this.mode; - } -}); - -/* - * Read preference mode constants - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest'; - -const VALID_MODES = [ - ReadPreference.PRIMARY, - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST, - null -]; - -/** - * Construct a ReadPreference given an options object. - * - * @param {object} options The options object from which to extract the read preference. - * @return {ReadPreference} - */ -ReadPreference.fromOptions = function(options) { - if (!options) return null; - const readPreference = options.readPreference; - if (!readPreference) return null; - const readPreferenceTags = options.readPreferenceTags; - const maxStalenessSeconds = options.maxStalenessSeconds; - if (typeof readPreference === 'string') { - return new ReadPreference(readPreference, readPreferenceTags); - } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { - const mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode === 'string') { - return new ReadPreference(mode, readPreference.tags, { - maxStalenessSeconds: readPreference.maxStalenessSeconds || maxStalenessSeconds, - hedge: readPreference.hedge - }); - } - } - - return readPreference; -}; - -/** - * Resolves a read preference based on well-defined inheritance rules. This method will not only - * determine the read preference (if there is one), but will also ensure the returned value is a - * properly constructed instance of `ReadPreference`. - * - * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read - * preference, used for determining the inherited read preference. - * @param {object} options The options passed into the method, potentially containing a read preference - * @returns {(ReadPreference|null)} The resolved read preference - */ -ReadPreference.resolve = function(parent, options) { - options = options || {}; - const session = options.session; - - const inheritedReadPreference = parent && parent.readPreference; - - let readPreference; - if (options.readPreference) { - readPreference = ReadPreference.fromOptions(options); - } else if (session && session.inTransaction() && session.transaction.options.readPreference) { - // The transaction’s read preference MUST override all other user configurable read preferences. - readPreference = session.transaction.options.readPreference; - } else if (inheritedReadPreference != null) { - readPreference = inheritedReadPreference; - } else { - readPreference = ReadPreference.primary; - } - - return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; -}; - -/** - * Replaces options.readPreference with a ReadPreference instance - */ -ReadPreference.translate = function(options) { - if (options.readPreference == null) return options; - const r = options.readPreference; - - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.isValid = function(mode) { - return VALID_MODES.indexOf(mode) !== -1; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.prototype.isValid = function(mode) { - return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); -}; - -const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire - * @method - * @return {boolean} - * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.mode) !== -1; -}; - -/** - * Are the two read preference equal - * @method - * @param {ReadPreference} readPreference The read preference with which to check equality - * @return {boolean} True if the two ReadPreferences are equivalent - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.mode === this.mode; -}; - -/** - * Return JSON representation - * @method - * @return {Object} A JSON representation of the ReadPreference - */ -ReadPreference.prototype.toJSON = function() { - const readPreference = { mode: this.mode }; - if (Array.isArray(this.tags)) readPreference.tags = this.tags; - if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - if (this.hedge) readPreference.hedge = this.hedge; - return readPreference; -}; - -/** - * Primary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/topologies/replset.js b/reverse_engineering/node_modules/mongodb/lib/core/topologies/replset.js deleted file mode 100644 index 02c2148..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/topologies/replset.js +++ /dev/null @@ -1,1566 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const ReadPreference = require('./read_preference'); -const CoreCursor = require('../cursor').CoreCursor; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const Logger = require('../connection/logger'); -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const ReplSetState = require('./replset_state'); -const Timeout = require('./shared').Timeout; -const Interval = require('./shared').Interval; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const BSON = retrieveBSON(); -const getMMAPError = require('./shared').getMMAPError; -const makeClientMetadata = require('../utils').makeClientMetadata; -const legacyIsRetryableWriteError = require('./shared').legacyIsRetryableWriteError; -const now = require('../../utils').now; -const calculateDurationInMs = require('../../utils').calculateDurationInMs; - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#failed - * @fires ReplSet#fullsetup - * @fires ReplSet#all - * @fires ReplSet#error - * @fires ReplSet#serverHeartbeatStarted - * @fires ReplSet#serverHeartbeatSucceeded - * @fires ReplSet#serverHeartbeatFailed - * @fires ReplSet#topologyOpening - * @fires ReplSet#topologyClosed - * @fires ReplSet#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); - // Validate list - if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); - // Validate entries - seedlist.forEach(function(e) { - if (typeof e.host !== 'string' || typeof e.port !== 'number') - throw new MongoError('seedlist entry must contain a host and port'); - }); - - // Add event listener - EventEmitter.call(this); - - // Get replSet Id - this.id = id++; - - // Get the localThresholdMS - var localThresholdMS = options.localThresholdMS || 15; - // Backward compatibility - if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; - - // Create a logger - var logger = Logger('ReplSet', options); - - // Internal state - this.s = { - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: logger, - // Seedlist - seedlist: seedlist, - // Replicaset state - replicaSetState: new ReplSetState({ - id: this.id, - setName: options.setName, - acceptableLatency: localThresholdMS, - heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, - logger: logger - }), - // Current servers we are connecting to - connectingServers: [], - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Minimum heartbeat frequency used if we detect a server close - minHeartbeatFrequencyMS: 500, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false - }; - - // Add handler for topology change - this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { - self.emit('topologyDescriptionChanged', r); - }); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Add forwarding of events from state handler - var types = ['joined', 'left']; - types.forEach(function(x) { - self.s.replicaSetState.on(x, function(t, s) { - self.emit(x, t, s); - }); - }); - - // Connect stat - this.initialConnectState = { - connect: false, - fullsetup: false, - all: false - }; - - // Disconnected state - this.state = DISCONNECTED; - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - // Contains the intervalId - this.intervalIds = []; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; -}; - -inherits(ReplSet, EventEmitter); -Object.assign(ReplSet.prototype, SessionMixins); - -Object.defineProperty(ReplSet.prototype, 'type', { - enumerable: true, - get: function() { - return 'replset'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; - } -}); - -function rexecuteOperations(self) { - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executePrimary: true }); - } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executeSecondary: true }); - } -} - -function connectNewServers(self, servers, callback) { - // No new servers - if (servers.length === 0) { - return callback(); - } - - // Count lefts - var count = servers.length; - var error = null; - - function done() { - count = count - 1; - if (count === 0) { - callback(error); - } - } - - // Handle events - var _handleEvent = function(self, event) { - return function(err) { - var _self = this; - - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - this.destroy({ force: true }); - return done(); - } - - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_self); - // Update the state with the new server - if (result) { - // Primary lastIsMaster store it - if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { - self.ismaster = _self.lastIsMaster(); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Enalbe the monitoring of the new server - monitorServer(_self.lastIsMaster().me, self, {}); - - // Rexecute any stalled operation - rexecuteOperations(self); - } else { - _self.destroy({ force: true }); - } - } else if (event === 'error') { - error = err; - } - - // Rexecute any stalled operation - rexecuteOperations(self); - done(); - }; - }; - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - // remove existing connecting server if it's failed to connect, otherwise - // wait for that server to connect - const existingServerIdx = self.s.connectingServers.findIndex(s => s.name === _server); - if (existingServerIdx >= 0) { - const connectingServer = self.s.connectingServers[existingServerIdx]; - connectingServer.destroy({ force: true }); - - self.s.connectingServers.splice(existingServerIdx, 1); - return done(); - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.split(':')[0], - port: parseInt(_server.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self - }) - ); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - self.s.connectingServers.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < servers.length; i++) { - execute(servers[i], i); - } -} - -// Ping the server -var pingServer = function(self, server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); - - // Execute ismaster - // Set the socketTimeout for a monitoring message to a low number - // Ensuring ismaster calls are timed out quickly - server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - server.destroy({ force: true }); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // Set the last updatedTime - server.lastUpdateTime = now(); - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: server.name - }); - - // Remove server from the state - self.s.replicaSetState.remove(server); - } else { - // Update the server ismaster - server.ismaster = r.result; - - // Check if we have a lastWriteDate convert it to MS - // and store on the server instance for later use - if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { - server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); - } - - // Do we have a brand new server - if (server.lastIsMasterMS === -1) { - server.lastIsMasterMS = latencyMS; - } else if (server.lastIsMasterMS) { - // After the first measurement, average RTT MUST be computed using an - // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. - // If the prior average is denoted old_rtt, then the new average (new_rtt) is - // computed from a new RTT measurement (x) using the following formula: - // alpha = 0.2 - // new_rtt = alpha * x + (1 - alpha) * old_rtt - server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; - } - - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: server.name - }); - } - - // Calculate the staleness for this server - self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); - - // Callback - cb(err, r); - } - ); -}; - -// Each server is monitored in parallel in their own timeout loop -var monitorServer = function(host, self, options) { - // If this is not the initial scan - // Is this server already being monitoried, then skip monitoring - if (!options.haInterval) { - for (var i = 0; i < self.intervalIds.length; i++) { - if (self.intervalIds[i].__host === host) { - return; - } - } - } - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - // Create the interval - var intervalId = new _process(function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - // clearInterval(intervalId); - intervalId.stop(); - return; - } - - // Do we already have server connection available for this host - var _server = self.s.replicaSetState.get(host); - - // Check if we have a known server connection and reuse - if (_server) { - // Ping the server - return pingServer(self, _server, function(err) { - if (err) { - // NOTE: should something happen here? - return; - } - - if (self.state === DESTROYED || self.state === UNREFERENCED) { - intervalId.stop(); - return; - } - - // Filter out all called intervaliIds - self.intervalIds = self.intervalIds.filter(function(intervalId) { - return intervalId.isRunning(); - }); - - // Initial sweep - if (_process === Timeout) { - if ( - self.state === CONNECTING && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - stateTransition(self, CONNECTED); - - // Emit connected sign - process.nextTick(function() { - self.emit('connect', self); - }); - - // Start topology interval check - topologyMonitor(self, {}); - } - } else { - if ( - self.state === DISCONNECTED && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - stateTransition(self, CONNECTING); - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function() { - self.emit('reconnect', self); - }); - } - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - }); - } - }, _haInterval); - - // Start the interval - intervalId.start(); - // Add the intervalId host name - intervalId.__host = host; - // Add the intervalId to our list of intervalIds - self.intervalIds.push(intervalId); -}; - -function topologyMonitor(self, options) { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - options = options || {}; - - // Get the servers - var servers = Object.keys(self.s.replicaSetState.set); - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - if (_process === Timeout) { - return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { - // Don't emit errors if the connection was already - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no primary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } else if ( - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no secondary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } - - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - }); - } else { - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - } - - // Run the reconnect process - function executeReconnect(self) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - connectNewServers(self, self.s.replicaSetState.unknownServers, function() { - var monitoringFrequencey = self.s.replicaSetState.hasPrimary() - ? _haInterval - : self.s.minHeartbeatFrequencyMS; - - // Create a timeout - self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); - }); - }; - } - - // Decide what kind of interval to use - var intervalTime = !self.s.replicaSetState.hasPrimary() - ? self.s.minHeartbeatFrequencyMS - : _haInterval; - - self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); -} - -function addServerToList(list, server) { - for (var i = 0; i < list.length; i++) { - if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; - } - - list.push(server); -} - -function handleEvent(self, event) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) - ); - } - - // Remove from the replicaset state - self.s.replicaSetState.remove(this); - - // Are we in a destroyed state return - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // If no primary and secondary available - if ( - !self.s.replicaSetState.hasPrimary() && - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - stateTransition(self, DISCONNECTED); - } else if (!self.s.replicaSetState.hasPrimary()) { - stateTransition(self, DISCONNECTED); - } - - addServerToList(self.s.connectingServers, this); - }; -} - -function shouldTriggerConnect(self) { - const isConnecting = self.state === CONNECTING; - const hasPrimary = self.s.replicaSetState.hasPrimary(); - const hasSecondary = self.s.replicaSetState.hasSecondary(); - const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; - const readPreferenceSecondary = - self.s.connectOptions.readPreference && - self.s.connectOptions.readPreference.equals(ReadPreference.secondary); - - return ( - (isConnecting && - ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || - (hasSecondary && secondaryOnlyConnectionAllowed) - ); -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s', - event, - this.name, - self.id - ) - ); - } - - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - // Check the type of server - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_this); - if (result === true) { - // Primary lastIsMaster store it - if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { - self.ismaster = _this.lastIsMaster(); - } - - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', - event, - _this.name, - self.id, - JSON.stringify(self.s.replicaSetState.set) - ) - ); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Do we have a primary or primaryAndSecondary - if (shouldTriggerConnect(self)) { - // We are connected - stateTransition(self, CONNECTED); - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function() { - self.emit('connect', self); - }); - - topologyMonitor(self, {}); - } - } else if (result instanceof MongoError) { - _this.destroy({ force: true }); - self.destroy({ force: true }); - return self.emit('error', result); - } else { - _this.destroy({ force: true }); - } - } else { - // Emit failure to connect - self.emit('failed', this); - - addServerToList(self.s.connectingServers, this); - // Remove from the state - self.s.replicaSetState.remove(this); - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - - // Remove from the list from connectingServers - for (var i = 0; i < self.s.connectingServers.length; i++) { - if (self.s.connectingServers[i].equals(this)) { - self.s.connectingServers.splice(i, 1); - } - } - - // Trigger topologyMonitor - if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { - topologyMonitor(self, { haInterval: 1 }); - } - }; -} - -function connectServers(self, servers) { - // Update connectingServers - self.s.connectingServers = self.s.connectingServers.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Add the server to the state - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - */ -ReplSet.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self - }) - ); - }); - - // Error out as high availability interval must be < than socketTimeout - if ( - this.s.options.socketTimeout > 0 && - this.s.options.socketTimeout <= this.s.options.haInterval - ) { - return self.emit( - 'error', - new MongoError( - f( - 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', - this.s.options.haInterval, - this.s.options.socketTimeout - ) - ) - ); - } - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - // Start all server connections - connectServers(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -ReplSet.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` - const serverDestroyed = () => { - destroyCount--; - if (destroyCount > 0) { - return; - } - - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (this.state === DESTROYED) { - if (typeof callback === 'function') callback(null, null); - return; - } - - // Transition state - stateTransition(this, DESTROYED); - - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); - - // Clear out all monitoring - for (var i = 0; i < this.intervalIds.length; i++) { - this.intervalIds[i].stop(); - } - - // Reset list of intervalIds - this.intervalIds = []; - - if (destroyCount === 0) { - serverDestroyed(); - return; - } - - // Destroy the replicaset - this.s.replicaSetState.destroy(options, serverDestroyed); - - // Destroy all connecting servers - this.s.connectingServers.forEach(function(x) { - x.destroy(options, serverDestroyed); - }); -}; - -/** - * Unref all connections belong to this server - * @method - */ -ReplSet.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - - this.s.replicaSetState.allServers().forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - // If secondaryOnlyConnectionAllowed and no primary but secondary - // return the secondaries ismaster result. - if ( - this.s.options.secondaryOnlyConnectionAllowed && - !this.s.replicaSetState.hasPrimary() && - this.s.replicaSetState.hasSecondary() - ) { - return this.s.replicaSetState.secondaries[0].lastIsMaster(); - } - - return this.s.replicaSetState.primary - ? this.s.replicaSetState.primary.lastIsMaster() - : this.ismaster; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - var servers = this.s.replicaSetState.allServers(); - var connections = []; - for (var i = 0; i < servers.length; i++) { - connections = connections.concat(servers[i].connections()); - } - - return connections; -}; - -/** - * Figure out if the server is connected - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we specified a read preference check if we are connected to something - // than can satisfy this - if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { - return this.s.replicaSetState.hasSecondary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { - return this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { - return true; - } - - return this.s.replicaSetState.hasPrimary(); -}; - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology -const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {ClientSession} [options.session] Unused - * @param {function} callback - */ -ReplSet.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') (callback = options), (options = selector); - options = options || {}; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else { - readPreference = options.readPreference || ReadPreference.primary; - } - - let lastError; - const start = now(); - const _selectServer = () => { - if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { - if (lastError != null) { - callback(lastError, null); - } else { - callback(new MongoError('Server selection timed out')); - } - - return; - } - - const server = this.s.replicaSetState.pickServer(readPreference); - if (server == null) { - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (!(server instanceof Server)) { - lastError = server; - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (this.s.debug) this.emit('pickedServer', options.readPreference, server); - callback(null, server); - }; - - _selectServer(); -}; - -/** - * Get all connected servers - * @method - * @return {Server[]} - */ -ReplSet.prototype.getServers = function() { - return this.s.replicaSetState.allServers(); -}; - -// -// Execute write operation -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - if (self.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - options.explain === undefined; - - if (!self.s.replicaSetState.hasPrimary()) { - if (self.s.disconnectHandler) { - // Not connected but we have a disconnecthandler - return self.s.disconnectHandler.add(op, ns, ops, options, callback); - } else if (!willRetryWrite) { - // No server returned we had an error - return callback(new MongoError('no primary server found')); - } - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!legacyIsRetryableWriteError(err, self)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - // Per SDAM, remove primary from replicaset - if (self.s.replicaSetState.primary) { - self.s.replicaSetState.primary.destroy(); - self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - self.s.replicaSetState.primary[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Establish readPreference - var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - - // If the readPreference is primary and we have no primary, store it - if ( - readPreference.preference === 'primary' && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference === 'secondary' && - !this.s.replicaSetState.hasSecondary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference !== 'primary' && - !this.s.replicaSetState.hasSecondary() && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // Pick a server - var server = this.s.replicaSetState.pickServer(readPreference); - // We received an error, return it - if (!(server instanceof Server)) return callback(server); - // Emit debug event - if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - - // No server returned we had an error - if (server == null) { - return callback( - new MongoError( - f('no server found that matches the provided readPreference %s', readPreference) - ) - ); - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!legacyIsRetryableWriteError(err, self)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - // Per SDAM, remove primary from replicaset - if (this.s.replicaSetState.primary) { - this.s.replicaSetState.primary.destroy(); - this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, options, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * A replset reconnect event, used to verify that the topology reconnected - * - * @event ReplSet#reconnect - * @type {ReplSet} - */ - -/** - * A replset fullsetup event, used to signal that all topology members have been contacted. - * - * @event ReplSet#fullsetup - * @type {ReplSet} - */ - -/** - * A replset all event, used to signal that all topology members have been contacted. - * - * @event ReplSet#all - * @type {ReplSet} - */ - -/** - * A replset failed event, used to signal that initial replset connection failed. - * - * @event ReplSet#failed - * @type {ReplSet} - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event ReplSet#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event ReplSet#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event ReplSet#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event ReplSet#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event ReplSet#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event ReplSet#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event ReplSet#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event ReplSet#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event ReplSet#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/topologies/replset_state.js b/reverse_engineering/node_modules/mongodb/lib/core/topologies/replset_state.js deleted file mode 100644 index 7edb791..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/topologies/replset_state.js +++ /dev/null @@ -1,1123 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - diff = require('./shared').diff, - EventEmitter = require('events').EventEmitter, - Logger = require('../connection/logger'), - ReadPreference = require('./read_preference'), - MongoError = require('../error').MongoError, - Buffer = require('safe-buffer').Buffer; - -var TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -var ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -var ReplSetState = function(options) { - options = options || {}; - // Add event listener - EventEmitter.call(this); - // Topology state - this.topologyType = options.setName ? TopologyType.ReplicaSetNoPrimary : TopologyType.Unknown; - this.setName = options.setName; - - // Server set - this.set = {}; - - // Unpacked options - this.id = options.id; - this.setName = options.setName; - - // Replicaset logger - this.logger = options.logger || Logger('ReplSet', options); - - // Server selection index - this.index = 0; - // Acceptable latency - this.acceptableLatency = options.acceptableLatency || 15; - - // heartbeatFrequencyMS - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - // Server side - this.primary = null; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - // Current unknown hosts - this.unknownServers = []; - // In set status - this.set = {}; - // Status - this.maxElectionId = null; - this.maxSetVersion = 0; - // Description of the Replicaset - this.replicasetDescription = { - topologyType: 'Unknown', - servers: [] - }; - - this.logicalSessionTimeoutMinutes = undefined; -}; - -inherits(ReplSetState, EventEmitter); - -ReplSetState.prototype.hasPrimaryAndSecondary = function() { - return this.primary != null && this.secondaries.length > 0; -}; - -ReplSetState.prototype.hasPrimaryOrSecondary = function() { - return this.hasPrimary() || this.hasSecondary(); -}; - -ReplSetState.prototype.hasPrimary = function() { - return this.primary != null; -}; - -ReplSetState.prototype.hasSecondary = function() { - return this.secondaries.length > 0; -}; - -ReplSetState.prototype.get = function(host) { - var servers = this.allServers(); - - for (var i = 0; i < servers.length; i++) { - if (servers[i].name.toLowerCase() === host.toLowerCase()) { - return servers[i]; - } - } - - return null; -}; - -ReplSetState.prototype.allServers = function(options) { - options = options || {}; - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - return servers; -}; - -ReplSetState.prototype.destroy = function(options, callback) { - const serversToDestroy = this.secondaries - .concat(this.arbiters) - .concat(this.passives) - .concat(this.ghosts); - if (this.primary) serversToDestroy.push(this.primary); - - let serverCount = serversToDestroy.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - // Clear out the complete state - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - this.unknownServers = []; - this.set = {}; - this.primary = null; - - // Emit the topology changed - emitTopologyDescriptionChanged(this); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); -}; - -ReplSetState.prototype.remove = function(server, options) { - options = options || {}; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // Only remove if the current server is not connected - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - - // Check if it's active and this is just a failed connection attempt - for (var i = 0; i < servers.length; i++) { - if ( - !options.force && - servers[i].equals(server) && - servers[i].isConnected && - servers[i].isConnected() - ) { - return; - } - } - - // If we have it in the set remove it - if (this.set[serverName]) { - this.set[serverName].type = ServerType.Unknown; - this.set[serverName].electionId = null; - this.set[serverName].setName = null; - this.set[serverName].setVersion = null; - } - - // Remove type - var removeType = null; - - // Remove from any lists - if (this.primary && this.primary.equals(server)) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - removeType = 'primary'; - } - - // Remove from any other server lists - removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; - removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; - removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; - removeFrom(server, this.ghosts); - removeFrom(server, this.unknownServers); - - // Push to unknownServers - this.unknownServers.push(serverName); - - // Do we have a removeType - if (removeType) { - this.emit('left', removeType, server); - } -}; - -const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; - -ReplSetState.prototype.update = function(server) { - var self = this; - // Get the current ismaster - const ismaster = server.lastIsMaster(); - if (ismaster && ismaster.isWritablePrimary) ismaster.ismaster = ismaster.isWritablePrimary; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // - // Add any hosts - // - if (ismaster) { - // Join all the possible new hosts - var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; - hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); - hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); - hosts = hosts.map(function(s) { - return s.toLowerCase(); - }); - - // Add all hosts as unknownServers - for (var i = 0; i < hosts.length; i++) { - // Add to the list of unknown server - if ( - this.unknownServers.indexOf(hosts[i]) === -1 && - (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) - ) { - this.unknownServers.push(hosts[i].toLowerCase()); - } - - if (!this.set[hosts[i]]) { - this.set[hosts[i]] = { - type: ServerType.Unknown, - electionId: null, - setName: null, - setVersion: null - }; - } - } - } - - // - // Unknown server - // - if (!ismaster && !inList(ismaster, server, this.unknownServers)) { - self.set[serverName] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - // Update set information about the server instance - self.set[serverName].type = ServerType.Unknown; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - - if (self.unknownServers.indexOf(server.name) === -1) { - self.unknownServers.push(serverName); - } - - // Set the topology - return false; - } - - // Update logicalSessionTimeoutMinutes - if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { - if ( - self.logicalSessionTimeoutMinutes === undefined || - ismaster.logicalSessionTimeoutMinutes === null - ) { - self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; - } else { - self.logicalSessionTimeoutMinutes = Math.min( - self.logicalSessionTimeoutMinutes, - ismaster.logicalSessionTimeoutMinutes - ); - } - } - - // - // Is this a mongos - // - if (ismaster && ismaster.msg === 'isdbgrid') { - if (this.primary && this.primary.name === serverName) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // A RSGhost instance - if (ismaster.isreplicaset) { - self.set[serverName] = { - type: ServerType.RSGhost, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - if (this.primary && this.primary.name === serverName) { - this.primary = null; - } - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - - // Set the topology - return false; - } - - // A RSOther instance - if ( - (ismaster.setName && ismaster.hidden) || - (ismaster.setName && - !ismaster.ismaster && - !ismaster.secondary && - !ismaster.arbiterOnly && - !ismaster.passive) - ) { - self.set[serverName] = { - type: ServerType.RSOther, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - return false; - } - - // - // Standalone server, destroy and return - // - if (ismaster && ismaster.ismaster && !ismaster.setName) { - // We should not mark the topology as Unknown because of one standalone - // we should just remove this server from the set - this.remove(server, { force: true }); - return false; - } - - // - // Server in maintanance mode - // - if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - this.remove(server, { force: true }); - return false; - } - - // - // If the .me field does not match the passed in server - // - if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { - if (this.logger.isWarn()) { - this.logger.warn( - f( - 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', - server.name, - ismaster.me - ) - ); - } - - // Delete from the set - delete this.set[serverName]; - // Delete unknown servers - removeFrom(server, self.unknownServers); - - // Destroy the instance - server.destroy({ force: true }); - - // Set the type of topology we have - if (this.primary && !this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - // - // We have a potential primary - // - if (!this.primary && ismaster.primary) { - this.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setName: null, - electionId: null, - setVersion: null - }; - } - - return false; - } - - // - // Primary handling - // - if (!this.primary && ismaster.ismaster && ismaster.setName) { - var ismasterElectionId = server.lastIsMaster().electionId; - if (this.setName && this.setName !== ismaster.setName) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return new MongoError( - f( - 'setName from ismaster does not match provided connection setName [%s] != [%s]', - ismaster.setName, - this.setName - ) - ); - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - var result = compareObjectIds(this.maxElectionId, ismasterElectionId); - // Get the electionIds - var ismasterSetVersion = server.lastIsMaster().setVersion; - - if (result === 1) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } else if (result === 0 && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - } - - this.maxSetVersion = ismasterSetVersion; - this.maxElectionId = ismasterElectionId; - } - - // Hande normalization of server names - var normalizedHosts = ismaster.hosts.map(function(x) { - return x.toLowerCase(); - }); - var locationIndex = normalizedHosts.indexOf(serverName); - - // Validate that the server exists in the host list - if (locationIndex !== -1) { - self.primary = server; - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - emitTopologyDescriptionChanged(self); - return true; - } else if (ismaster.ismaster && ismaster.setName) { - // Get the electionIds - var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; - var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; - var currentSetName = self.set[self.primary.name.toLowerCase()].setName; - ismasterElectionId = server.lastIsMaster().electionId; - ismasterSetVersion = server.lastIsMaster().setVersion; - var ismasterSetName = server.lastIsMaster().setName; - - // Is it the same server instance - if (this.primary.equals(server) && currentSetName === ismasterSetName) { - return false; - } - - // If we do not have the same rs name - if (currentSetName && currentSetName !== ismasterSetName) { - if (!this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // Check if we need to replace the server - if (currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion > ismasterSetVersion) { - return false; - } - } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - result = compareObjectIds(this.maxElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } else { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - this.maxElectionId = ismasterElectionId; - this.maxSetVersion = ismasterSetVersion; - } else { - this.maxSetVersion = ismasterSetVersion; - } - - // Modify the entry to unknown - self.set[self.primary.name.toLowerCase()] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - - // Signal primary left - self.emit('left', 'primary', this.primary); - // Destroy the instance - self.primary.destroy({ force: true }); - // Set the new instance - self.primary = server; - // Set the set information - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // A possible instance - if (!this.primary && ismaster.primary) { - self.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setVersion: null, - electionId: null, - setName: null - }; - } - - // - // Secondary handling - // - if ( - ismaster.secondary && - ismaster.setName && - !inList(ismaster, server, this.secondaries) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - // Emit secondary joined replicaset - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Arbiter handling - // - if ( - isArbiter(ismaster) && - !inList(ismaster, server, this.arbiters) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - self.emit('joined', 'arbiter', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Passive handling - // - if ( - ismaster.passive && - ismaster.setName && - !inList(ismaster, server, this.passives) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Remove the primary - // - if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { - self.emit('left', 'primary', this.primary); - this.primary.destroy({ force: true }); - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - return false; -}; - -/** - * Recalculate single server max staleness - * @method - */ -ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { - // Locate the max secondary lastwrite - var max = 0; - // Go over all secondaries - for (var i = 0; i < this.secondaries.length; i++) { - max = Math.max(max, this.secondaries[i].lastWriteDate); - } - - // Perform this servers staleness calculation - if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { - server.staleness = - server.lastUpdateTime - - server.lastWriteDate - - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + - haInterval; - } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { - server.staleness = max - server.lastWriteDate + haInterval; - } -}; - -/** - * Recalculate all the staleness values for secodaries - * @method - */ -ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { - for (var i = 0; i < this.secondaries.length; i++) { - this.updateServerMaxStaleness(this.secondaries[i], haInterval); - } -}; - -/** - * Pick a server by the passed in ReadPreference - * @method - * @param {ReadPreference} readPreference The ReadPreference instance to use - */ -ReplSetState.prototype.pickServer = function(readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // maxStalenessSeconds is not allowed with a primary read - if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { - return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); - } - - // Check if we have any non compatible servers for maxStalenessSeconds - var allservers = this.primary ? [this.primary] : []; - allservers = allservers.concat(this.secondaries); - - // Does any of the servers not support the right wire protocol version - // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out - if (readPreference.maxStalenessSeconds != null) { - for (var i = 0; i < allservers.length; i++) { - if (allservers[i].ismaster.maxWireVersion < 5) { - return new MongoError( - 'maxStalenessSeconds not supported by at least one of the replicaset members' - ); - } - } - } - - // Do we have the nearest readPreference - if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { - return pickNearest(this, readPreference); - } else if ( - readPreference.preference === 'nearest' && - readPreference.maxStalenessSeconds != null - ) { - return pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Get all the secondaries - var secondaries = this.secondaries; - - // Check if we can satisfy and of the basic read Preferences - if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { - return new MongoError('no secondary server available'); - } - - if ( - readPreference.equals(ReadPreference.secondaryPreferred) && - secondaries.length === 0 && - this.primary == null - ) { - return new MongoError('no secondary or primary server available'); - } - - if (readPreference.equals(ReadPreference.primary) && this.primary == null) { - return new MongoError('no primary server available'); - } - - // Secondary preferred or just secondaries - if ( - readPreference.equals(ReadPreference.secondaryPreferred) || - readPreference.equals(ReadPreference.secondary) - ) { - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - // Pick nearest of any other servers available - var server = pickNearest(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - // Pick nearest of any other servers available - server = pickNearestMaxStalenessSeconds(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } - - if (readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.primary; - } - - return null; - } - - // Primary preferred - if (readPreference.equals(ReadPreference.primaryPreferred)) { - server = null; - - // We prefer the primary if it's available - if (this.primary) { - return this.primary; - } - - // Pick a secondary - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - server = pickNearest(this, readPreference); - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - server = pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Did we find a server - if (server) return server; - } - - // Return the primary - return this.primary; -}; - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if (readPreference.tags == null) return servers; - var filteredServers = []; - var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; - - // Iterate over the tags - for (var j = 0; j < tagsArray.length; j++) { - var tags = tagsArray[j]; - - // Iterate over all the servers - for (var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - - // Did we find the a matching server - var found = true; - // Check if the server is valid - for (var name in tags) { - if (serverTag[name] !== tags[name]) { - found = false; - } - } - - // Add to candidate list - if (found) { - filteredServers.push(servers[i]); - } - } - } - - // Returned filtered servers - return filteredServers; -}; - -function pickNearestMaxStalenessSeconds(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Get the maxStalenessMS - var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; - - // Check if the maxStalenessMS > 90 seconds - if (maxStalenessMS < 90 * 1000) { - return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); - } - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Filter by latency - servers = servers.filter(function(s) { - return s.staleness <= maxStalenessMS; - }); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.lastIsMasterMS <= lowest + self.acceptableLatency; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function inList(ismaster, server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) - return true; - } - - return false; -} - -function addToList(self, type, ismaster, server, list) { - var serverName = server.name.toLowerCase(); - // Update set information about the server instance - self.set[serverName].type = type; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - // Add to the list - list.push(server); -} - -function compareObjectIds(id1, id2) { - var a = Buffer.from(id1.toHexString(), 'hex'); - var b = Buffer.from(id2.toHexString(), 'hex'); - - if (a === b) { - return 0; - } - - if (typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -function removeFrom(server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i].equals && list[i].equals(server)) { - list.splice(i, 1); - return true; - } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { - list.splice(i, 1); - return true; - } - } - - return false; -} - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if (self.hasPrimaryAndSecondary()) { - topology = 'ReplicaSetWithPrimary'; - } else if (!self.hasPrimary() && self.hasSecondary()) { - topology = 'ReplicaSetNoPrimary'; - } - - // Generate description - var description = { - topologyType: topology, - setName: setName, - servers: [] - }; - - // Add the primary to the list - if (self.hasPrimary()) { - var desc = self.primary.getDescription(); - desc.type = 'RSPrimary'; - description.servers.push(desc); - } - - // Add all the secondaries - description.servers = description.servers.concat( - self.secondaries.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Add all the arbiters - description.servers = description.servers.concat( - self.arbiters.map(function(x) { - var description = x.getDescription(); - description.type = 'RSArbiter'; - return description; - }) - ); - - // Add all the passives - description.servers = description.servers.concat( - self.passives.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.replicasetDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.replicasetDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - // if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - // } - - // Set the new description - self.replicasetDescription = description; - } -} - -module.exports = ReplSetState; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/topologies/server.js b/reverse_engineering/node_modules/mongodb/lib/core/topologies/server.js deleted file mode 100644 index ebc7087..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/topologies/server.js +++ /dev/null @@ -1,996 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - Logger = require('../connection/logger'), - debugOptions = require('../connection/utils').debugOptions, - retrieveBSON = require('../connection/utils').retrieveBSON, - Pool = require('../connection/pool'), - MongoError = require('../error').MongoError, - MongoNetworkError = require('../error').MongoNetworkError, - wireProtocol = require('../wireprotocol'), - CoreCursor = require('../cursor').CoreCursor, - sdam = require('./shared'), - createCompressionInfo = require('./shared').createCompressionInfo, - resolveClusterTime = require('./shared').resolveClusterTime, - SessionMixins = require('./shared').SessionMixins, - extractCommand = require('../../command_utils').extractCommand, - relayEvents = require('../utils').relayEvents; - -const collationNotSupported = require('../utils').collationNotSupported; -const makeClientMetadata = require('../utils').makeClientMetadata; - -// Used for filtering out fields for loggin -var debugFields = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'servername' -]; - -// Server instance id -var id = 0; -var serverAccounting = false; -var servers = {}; -var BSON = retrieveBSON(); - -function topologyId(server) { - return server.s.parent == null ? server.id : server.s.parent.id; -} - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) - * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#reconnectFailed - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - * @fires Server#topologyOpening - * @fires Server#topologyClosed - * @fires Server#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Server = function(options) { - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Server instance id - this.id = id++; - - // Internal state - this.s = { - // Options - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // Logger - logger: Logger('Server', options), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Pool - pool: null, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Monitor thread (keeps the connection alive) - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, - // Is the server in a topology - inTopology: !!options.parent, - // Monitoring timeout - monitoringInterval: - typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, - compression: { compressors: createCompressionInfo(options) }, - // Optional parent topology - parent: options.parent - }; - - // If this is a single deployment we need to track the clusterTime here - if (!this.s.parent) { - this.s.clusterTime = null; - } - - // Curent ismaster - this.ismaster = null; - // Current ping time - this.lastIsMasterMS = -1; - // The monitoringProcessId - this.monitoringProcessId = null; - // Initial connection - this.initialConnect = true; - // Default type - this._type = 'server'; - - // Max Stalleness values - // last time we updated the ismaster state - this.lastUpdateTime = 0; - // Last write time - this.lastWriteDate = 0; - // Stalleness - this.staleness = 0; -}; - -inherits(Server, EventEmitter); -Object.assign(Server.prototype, SessionMixins); - -Object.defineProperty(Server.prototype, 'type', { - enumerable: true, - get: function() { - return this._type; - } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -Object.defineProperty(Server.prototype, 'clientMetadata', { - enumerable: true, - get: function() { - return this.s.options.metadata; - } -}); - -// In single server deployments we track the clusterTime directly on the topology, however -// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the -// tracking objects so we can ensure we are gossiping the maximum time received from the -// server. -Object.defineProperty(Server.prototype, 'clusterTime', { - enumerable: true, - set: function(clusterTime) { - const settings = this.s.parent ? this.s.parent : this.s; - resolveClusterTime(settings, clusterTime); - }, - get: function() { - const settings = this.s.parent ? this.s.parent : this.s; - return settings.clusterTime || null; - } -}); - -Server.enableServerAccounting = function() { - serverAccounting = true; - servers = {}; -}; - -Server.disableServerAccounting = function() { - serverAccounting = false; -}; - -Server.servers = function() { - return servers; -}; - -Object.defineProperty(Server.prototype, 'name', { - enumerable: true, - get: function() { - return this.s.options.host + ':' + this.s.options.port; - } -}); - -function disconnectHandler(self, type, ns, cmd, options, callback) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ( - !self.s.pool.isConnected() && - self.s.options.reconnect && - self.s.disconnectHandler != null && - !options.monitoring - ) { - self.s.disconnectHandler.add(type, ns, cmd, options, callback); - return true; - } - - // If we have no connection error - if (!self.s.pool.isConnected()) { - callback(new MongoError(f('no connection available to server %s', self.name))); - return true; - } -} - -function monitoringProcess(self) { - return function() { - // Pool was destroyed do not continue process - if (self.s.pool.isDestroyed()) return; - // Emit monitoring Process event - self.emit('monitoring', self); - // Perform ismaster call - // Get start time - var start = new Date().getTime(); - - // Execute the ismaster query - self.command( - 'admin.$cmd', - { ismaster: true }, - { - socketTimeout: - typeof self.s.options.connectionTimeout !== 'number' - ? 2000 - : self.s.options.connectionTimeout, - monitoring: true - }, - (err, result) => { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if (self.s.pool.isDestroyed()) return; - // Update the ismaster view if we have a result - if (result) { - self.ismaster = result.result; - } - // Re-schedule the monitoring process - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - ); - }; -} - -var eventHandler = function(self, event) { - return function(err, conn) { - // Log information of received information if in info mode - if (self.s.logger.isInfo()) { - var object = err instanceof MongoError ? JSON.stringify(err) : {}; - self.s.logger.info( - f('server %s fired event %s out with message %s', self.name, event, object) - ); - } - - // Handle connect event - if (event === 'connect') { - self.initialConnect = false; - self.ismaster = conn.ismaster; - self.lastIsMasterMS = conn.lastIsMasterMS; - if (conn.agreedCompressor) { - self.s.pool.options.agreedCompressor = conn.agreedCompressor; - } - - if (conn.zlibCompressionLevel) { - self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; - } - - if (conn.ismaster.$clusterTime) { - const $clusterTime = conn.ismaster.$clusterTime; - self.clusterTime = $clusterTime; - } - - // It's a proxy change the type so - // the wireprotocol will send $readPreference - if (self.ismaster.msg === 'isdbgrid') { - self._type = 'mongos'; - } - - // Have we defined self monitoring - if (self.s.monitoring) { - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - - // Emit server description changed if something listening - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - - if (!self.s.inTopology) { - // Emit topology description changed if something listening - sdam.emitTopologyDescriptionChanged(self, { - topologyType: 'Single', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - } - ] - }); - } - - // Log the ismaster if available - if (self.s.logger.isInfo()) { - self.s.logger.info( - f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) - ); - } - - // Emit connect - self.emit('connect', self); - } else if ( - event === 'error' || - event === 'parseError' || - event === 'close' || - event === 'timeout' || - event === 'reconnect' || - event === 'attemptReconnect' || - event === 'reconnectFailed' - ) { - // Remove server instance from accounting - if ( - serverAccounting && - ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 - ) { - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - self.emit('topologyOpening', { topologyId: self.id }); - } - - delete servers[self.id]; - } - - if (event === 'close') { - // Closing emits a server description changed event going to unknown. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }); - } - - // Reconnect failed return error - if (event === 'reconnectFailed') { - self.emit('reconnectFailed', err); - // Emit error if any listeners - if (self.listeners('error').length > 0) { - self.emit('error', err); - } - // Terminate - return; - } - - // On first connect fail - if ( - ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && - self.initialConnect && - ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 - ) { - self.initialConnect = false; - return self.emit( - 'error', - new MongoNetworkError( - f('failed to connect to server [%s] on first connect [%s]', self.name, err) - ) - ); - } - - // Reconnect event, emit the server - if (event === 'reconnect') { - // Reconnecting emits a server description changed event going from unknown to the - // current server type. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - return self.emit(event, self); - } - - // Emit the event - self.emit(event, err); - } - }; -}; - -/** - * Initiate server connect - */ -Server.prototype.connect = function(options) { - var self = this; - options = options || {}; - - // Set the connections - if (serverAccounting) servers[this.id] = this; - - // Do not allow connect to be called on anything that's not disconnected - if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { - throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); - } - - // Create a pool - self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); - - // Set up listeners - self.s.pool.on('close', eventHandler(self, 'close')); - self.s.pool.on('error', eventHandler(self, 'error')); - self.s.pool.on('timeout', eventHandler(self, 'timeout')); - self.s.pool.on('parseError', eventHandler(self, 'parseError')); - self.s.pool.on('connect', eventHandler(self, 'connect')); - self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); - self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); - - // Set up listeners for command monitoring - relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - this.emit('topologyOpening', { topologyId: topologyId(self) }); - } - - // Emit opening server event - self.emit('serverOpening', { topologyId: topologyId(self), address: self.name }); - - self.s.pool.connect(); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Get the server description - * @method - * @return {object} - */ -Server.prototype.getDescription = function() { - var ismaster = this.ismaster || {}; - var description = { - type: sdam.getTopologyType(this), - address: this.name - }; - - // Add fields if available - if (ismaster.hosts) description.hosts = ismaster.hosts; - if (ismaster.arbiters) description.arbiters = ismaster.arbiters; - if (ismaster.passives) description.passives = ismaster.passives; - if (ismaster.setName) description.setName = ismaster.setName; - return description; -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Server.prototype.unref = function() { - this.s.pool.unref(); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - if (!this.s.pool) return false; - return this.s.pool.isConnected(); -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - if (!this.s.pool) return false; - return this.s.pool.isDestroyed(); -}; - -function basicWriteValidations(self) { - if (!self.s.pool) return new MongoError('server instance is not connected'); - if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); -} - -function basicReadValidations(self, options) { - basicWriteValidations(self, options); - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error('readPreference must be an instance of ReadPreference'); - } -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicReadValidations(self, options); - if (result) return callback(result); - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (self.s.logger.isDebug()) { - const extractedCommand = extractCommand(cmd); - self.s.logger.debug( - f( - 'executing command [%s] against %s', - JSON.stringify({ - ns: ns, - cmd: extractedCommand.shouldRedact ? `${extractedCommand.name} details REDACTED` : cmd, - options: debugOptions(debugFields, options) - }), - self.name - ) - ); - } - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - wireProtocol.command(self, ns, cmd, options, callback); -}; - -/** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.query = function(ns, cmd, cursorState, options, callback) { - wireProtocol.query(this, ns, cmd, cursorState, options, callback); -}; - -/** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { - wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); -}; - -/** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ -Server.prototype.killCursors = function(ns, cursorState, callback) { - wireProtocol.killCursors(this, ns, cursorState, callback); -}; - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - - // Execute write - return wireProtocol.insert(self, ns, ops, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.update(self, ns, ops, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.remove(self, ns, ops, options, callback); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Server.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); - if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); - return false; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.allConnections(); -}; - -/** - * Selects a server - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Unused - * @return {Server} - */ -Server.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - - callback(null, this); -}; - -var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; - -/** - * Destroy the server connection - * @method - * @param {boolean} [options.emitClose=false] Emit close event on destroy - * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {boolean} [options.force=false] Force destroy the pool - */ -Server.prototype.destroy = function(options, callback) { - if (this._destroyed) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - var self = this; - - // Set the connections - if (serverAccounting) delete servers[this.id]; - - // Destroy the monitoring process if any - if (this.monitoringProcessId) { - clearTimeout(this.monitoringProcessId); - } - - // No pool, return - if (!self.s.pool || this._destroyed) { - this._destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - this._destroyed = true; - - // Emit close event - if (options.emitClose) { - self.emit('close', self); - } - - // Emit destroy event - if (options.emitDestroy) { - self.emit('destroy', self); - } - - // Remove all listeners - listeners.forEach(function(event) { - self.s.pool.removeAllListeners(event); - }); - - // Emit opening server event - if (self.listeners('serverClosed').length > 0) - self.emit('serverClosed', { topologyId: topologyId(self), address: self.name }); - - // Emit toplogy opening event if not in topology - if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { - self.emit('topologyClosed', { topologyId: topologyId(self) }); - } - - if (self.s.logger.isDebug()) { - self.s.logger.debug(f('destroy called on server %s', self.name)); - } - - // Destroy the pool - this.s.pool.destroy(options.force, callback); -}; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * A server reconnect event, used to verify that the server topology has reconnected - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * A server opening SDAM monitoring event - * - * @event Server#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Server#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Server#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Server#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Server#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Server#topologyDescriptionChanged - * @type {object} - */ - -/** - * Server reconnect failed - * - * @event Server#reconnectFailed - * @type {Error} - */ - -/** - * Server connection pool closed - * - * @event Server#close - * @type {object} - */ - -/** - * Server connection pool caused an error - * - * @event Server#error - * @type {Error} - */ - -/** - * Server destroyed was called - * - * @event Server#destroy - * @type {Server} - */ - -module.exports = Server; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/topologies/shared.js b/reverse_engineering/node_modules/mongodb/lib/core/topologies/shared.js deleted file mode 100644 index dff35a5..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/topologies/shared.js +++ /dev/null @@ -1,459 +0,0 @@ -'use strict'; - -const MONGODB_ERROR_CODES = require('../../error_codes').MONGODB_ERROR_CODES; -const ReadPreference = require('./read_preference'); -const TopologyType = require('../sdam/common').TopologyType; -const MongoError = require('../error').MongoError; -const isRetryableWriteError = require('../error').isRetryableWriteError; -const maxWireVersion = require('../utils').maxWireVersion; -const MongoNetworkError = require('../error').MongoNetworkError; - -const MMAPv1_RETRY_WRITES_ERROR_CODE = MONGODB_ERROR_CODES.IllegalOperation; - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -function createCompressionInfo(options) { - if (!options.compression || !options.compression.compressors) { - return []; - } - - // Check that all supplied compressors are valid - options.compression.compressors.forEach(function(compressor) { - if (compressor !== 'snappy' && compressor !== 'zlib') { - throw new Error('compressors must be at least one of snappy or zlib'); - } - }); - - return options.compression.compressors; -} - -function clone(object) { - return JSON.parse(JSON.stringify(object)); -} - -var getPreviousDescription = function(self) { - if (!self.s.serverDescription) { - self.s.serverDescription = { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }; - } - - return self.s.serverDescription; -}; - -var emitServerDescriptionChanged = function(self, description) { - if (self.listeners('serverDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('serverDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var getPreviousTopologyDescription = function(self) { - if (!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: 'Unknown', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - } - ] - }; - } - - return self.s.topologyDescription; -}; - -var emitTopologyDescriptionChanged = function(self, description) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('topologyDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousTopologyDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var changedIsMaster = function(self, currentIsmaster, ismaster) { - var currentType = getTopologyType(self, currentIsmaster); - var newType = getTopologyType(self, ismaster); - if (newType !== currentType) return true; - return false; -}; - -var getTopologyType = function(self, ismaster) { - if (!ismaster) { - ismaster = self.ismaster; - } - - if (!ismaster) return 'Unknown'; - if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; - if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; - if (ismaster.ismaster) return 'RSPrimary'; - if (ismaster.secondary) return 'RSSecondary'; - if (ismaster.arbiterOnly) return 'RSArbiter'; - return 'Unknown'; -}; - -var inquireServerState = function(self) { - return function(callback) { - if (self.s.state === 'destroyed') return; - // Record response time - var start = new Date().getTime(); - - // emitSDAMEvent - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); - - // Attempt to execute ismaster command - self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { - if (!err) { - // Legacy event sender - self.emit('ismaster', r, self); - - // Calculate latencyMS - var latencyMS = new Date().getTime() - start; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: self.name - }); - - // Did the server change - if (changedIsMaster(self, self.s.ismaster, r.result)) { - // Emit server description changed if something listening - emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) - }); - } - - // Updat ismaster view - self.s.ismaster = r.result; - - // Set server response time - self.s.isMasterLatencyMS = latencyMS; - } else { - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: self.name - }); - } - - // Peforming an ismaster monitoring callback operation - if (typeof callback === 'function') { - return callback(err, r); - } - - // Perform another sweep - self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); - }); - }; -}; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for (var name in options) { - opts[name] = options[name]; - } - return opts; -}; - -function Interval(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setInterval(fn, time); - } - - return this; - }; - - this.stop = function() { - clearInterval(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function Timeout(fn, time) { - var timer = false; - var func = () => { - if (timer) { - clearTimeout(timer); - timer = false; - - fn(); - } - }; - - this.start = function() { - if (!this.isRunning()) { - timer = setTimeout(func, time); - } - return this; - }; - - this.stop = function() { - clearTimeout(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function diff(previous, current) { - // Difference document - var diff = { - servers: [] - }; - - // Previous entry - if (!previous) { - previous = { servers: [] }; - } - - // Check if we have any previous servers missing in the current ones - for (var i = 0; i < previous.servers.length; i++) { - var found = false; - - for (var j = 0; j < current.servers.length; j++) { - if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { - found = true; - break; - } - } - - if (!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: 'Unknown' - }); - } - } - - // Check if there are any severs that don't exist - for (j = 0; j < current.servers.length; j++) { - found = false; - - // Go over all the previous servers - for (i = 0; i < previous.servers.length; i++) { - if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { - found = true; - break; - } - } - - // Add the server to the diff - if (!found) { - diff.servers.push({ - address: current.servers[j].address, - from: 'Unknown', - to: current.servers[j].type - }); - } - } - - // Got through all the servers - for (i = 0; i < previous.servers.length; i++) { - var prevServer = previous.servers[i]; - - // Go through all current servers - for (j = 0; j < current.servers.length; j++) { - var currServer = current.servers[j]; - - // Matching server - if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { - // We had a change in state - if (prevServer.type !== currServer.type) { - diff.servers.push({ - address: prevServer.address, - from: prevServer.type, - to: currServer.type - }); - } - } - } - } - - // Return difference - return diff; -} - -/** - * Shared function to determine clusterTime for a given topology - * - * @param {*} topology - * @param {*} clusterTime - */ -function resolveClusterTime(topology, $clusterTime) { - if (topology.clusterTime == null) { - topology.clusterTime = $clusterTime; - } else { - if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { - topology.clusterTime = $clusterTime; - } - } -} - -// NOTE: this is a temporary move until the topologies can be more formally refactored -// to share code. -const SessionMixins = { - endSessions: function(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - // TODO: - // When connected to a sharded cluster the endSessions command - // can be sent to any mongos. When connected to a replica set the - // endSessions command MUST be sent to the primary if the primary - // is available, otherwise it MUST be sent to any available secondary. - // Is it enough to use: ReadPreference.primaryPreferred ? - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } -}; - -function topologyType(topology) { - if (topology.description) { - return topology.description.type; - } - - if (topology.type === 'mongos') { - return TopologyType.Sharded; - } else if (topology.type === 'replset') { - return TopologyType.ReplicaSetWithPrimary; - } - - return TopologyType.Single; -} - -const RETRYABLE_WIRE_VERSION = 6; - -/** - * Determines whether the provided topology supports retryable writes - * - * @param {Mongos|Replset} topology - */ -const isRetryableWritesSupported = function(topology) { - const maxWireVersion = topology.lastIsMaster().maxWireVersion; - if (maxWireVersion < RETRYABLE_WIRE_VERSION) { - return false; - } - - if (!topology.logicalSessionTimeoutMinutes) { - return false; - } - - if (topologyType(topology) === TopologyType.Single) { - return false; - } - - return true; -}; - -const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = - 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; - -function getMMAPError(err) { - if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { - return err; - } - - // According to the retryable writes spec, we must replace the error message in this case. - // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. - const newErr = new MongoError({ - message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - originalError: err - }); - return newErr; -} - -// NOTE: only used for legacy topology types -function legacyIsRetryableWriteError(err, topology) { - if (!(err instanceof MongoError)) { - return false; - } - - // if pre-4.4 server, then add error label if its a retryable write error - if ( - isRetryableWritesSupported(topology) && - (err instanceof MongoNetworkError || - (maxWireVersion(topology) < 9 && isRetryableWriteError(err))) - ) { - err.addErrorLabel('RetryableWriteError'); - } - - return err.hasErrorLabel('RetryableWriteError'); -} - -module.exports = { - SessionMixins, - resolveClusterTime, - inquireServerState, - getTopologyType, - emitServerDescriptionChanged, - emitTopologyDescriptionChanged, - cloneOptions, - createCompressionInfo, - clone, - diff, - Interval, - Timeout, - isRetryableWritesSupported, - getMMAPError, - topologyType, - legacyIsRetryableWriteError -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/transactions.js b/reverse_engineering/node_modules/mongodb/lib/core/transactions.js deleted file mode 100644 index 3752c27..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/transactions.js +++ /dev/null @@ -1,183 +0,0 @@ -'use strict'; -const MongoError = require('./error').MongoError; -const ReadPreference = require('./topologies/read_preference'); -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); - -let TxnState; -let stateMachine; - -(() => { - const NO_TRANSACTION = 'NO_TRANSACTION'; - const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; - const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; - const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; - const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; - const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; - - TxnState = { - NO_TRANSACTION, - STARTING_TRANSACTION, - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - }; - - stateMachine = { - [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], - [STARTING_TRANSACTION]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - ], - [TRANSACTION_IN_PROGRESS]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_ABORTED - ], - [TRANSACTION_COMMITTED]: [ - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - STARTING_TRANSACTION, - NO_TRANSACTION - ], - [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], - [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] - }; -})(); - -/** - * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties - * of the data read from replica sets and replica set shards. - * @typedef {Object} ReadConcern - * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level - * @see https://docs.mongodb.com/manual/reference/read-concern/ - */ - -/** - * A MongoDB WriteConcern, which describes the level of acknowledgement - * requested from MongoDB for write operations. - * @typedef {Object} WriteConcern - * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has - * propagated to a specified number of mongod hosts - * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has - * been written to the journal - * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/ - */ - -/** - * Configuration options for a transaction. - * @typedef {Object} TransactionOptions - * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction - * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction - * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction - */ - -/** - * A class maintaining state related to a server transaction. Internal Only - * @ignore - */ -class Transaction { - /** - * Create a transaction - * - * @ignore - * @param {TransactionOptions} [options] Optional settings - */ - constructor(options) { - options = options || {}; - - this.state = TxnState.NO_TRANSACTION; - this.options = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - if (writeConcern.w <= 0) { - throw new MongoError('Transactions do not support unacknowledged write concern'); - } - - this.options.writeConcern = writeConcern; - } - - if (options.readConcern) { - this.options.readConcern = ReadConcern.fromOptions(options); - } - - if (options.readPreference) { - this.options.readPreference = ReadPreference.fromOptions(options); - } - - if (options.maxCommitTimeMS) { - this.options.maxTimeMS = options.maxCommitTimeMS; - } - - // TODO: This isn't technically necessary - this._pinnedServer = undefined; - this._recoveryToken = undefined; - } - - get server() { - return this._pinnedServer; - } - - get recoveryToken() { - return this._recoveryToken; - } - - get isPinned() { - return !!this.server; - } - - /** - * @ignore - * @return Whether this session is presently in a transaction - */ - get isActive() { - return ( - [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 - ); - } - - /** - * Transition the transaction in the state machine - * @ignore - * @param {TxnState} state The new state to transition to - */ - transition(nextState) { - const nextStates = stateMachine[this.state]; - if (nextStates && nextStates.indexOf(nextState) !== -1) { - this.state = nextState; - if ( - this.state === TxnState.NO_TRANSACTION || - this.state === TxnState.STARTING_TRANSACTION || - this.state === TxnState.TRANSACTION_ABORTED - ) { - this.unpinServer(); - } - return; - } - - throw new MongoError( - `Attempted illegal state transition from [${this.state}] to [${nextState}]` - ); - } - - pinServer(server) { - if (this.isActive) { - this._pinnedServer = server; - } - } - - unpinServer() { - this._pinnedServer = undefined; - } -} - -function isTransactionCommand(command) { - return !!(command.commitTransaction || command.abortTransaction); -} - -module.exports = { TxnState, Transaction, isTransactionCommand }; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/uri_parser.js b/reverse_engineering/node_modules/mongodb/lib/core/uri_parser.js deleted file mode 100644 index 434a836..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/uri_parser.js +++ /dev/null @@ -1,747 +0,0 @@ -'use strict'; -const URL = require('url'); -const qs = require('querystring'); -const dns = require('dns'); -const MongoParseError = require('./error').MongoParseError; -const ReadPreference = require('./topologies/read_preference'); -const emitWarningOnce = require('../utils').emitWarningOnce; - -/** - * The following regular expression validates a connection string and breaks the - * provide string into the following capture groups: [protocol, username, password, hosts] - */ -const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; - -// Options that reference file paths should not be parsed -const FILE_PATH_OPTIONS = new Set( - ['sslCA', 'sslCert', 'sslKey', 'tlsCAFile', 'tlsCertificateKeyFile'].map(key => key.toLowerCase()) -); - -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -/** - * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal - * connection string. - * - * @param {string} uri The connection string to parse - * @param {object} options Optional user provided connection string options - * @param {function} callback - */ -function parseSrvConnectionString(uri, options, callback) { - const result = URL.parse(uri, true); - - if (options.directConnection || options.directconnection) { - return callback(new MongoParseError('directConnection not supported with SRV URI')); - } - - if (result.hostname.split('.').length < 3) { - return callback(new MongoParseError('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - - const hostname = uri.substring('mongodb+srv://'.length).split('/')[0]; - if (hostname.match(',')) { - return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); - } - - // Resolve the SRV record and use the result as the list of hosts to connect to. - const lookupAddress = result.host; - dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new MongoParseError('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback( - new MongoParseError('Server record does not share hostname with parent URI') - ); - } - } - - // Convert the original URL to a non-SRV URL. - result.protocol = 'mongodb'; - result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); - - // Default to SSL true if it's not specified. - if ( - !('ssl' in options) && - (!result.search || !('ssl' in result.query) || result.query.ssl === null) - ) { - result.query.ssl = true; - } - - // Resolve TXT record and add options from there if they exist. - dns.resolveTxt(lookupAddress, (err, record) => { - if (err) { - if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') { - return callback(err); - } - record = null; - } - - if (record) { - if (record.length > 1) { - return callback(new MongoParseError('Multiple text records not allowed')); - } - - record = qs.parse(record[0].join('')); - - if (Object.keys(record).some(k => k.toLowerCase() === 'loadbalanced')) { - return callback(new MongoParseError('Load balancer mode requires driver version 4+')); - } - - if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { - return callback( - new MongoParseError('Text record must only set `authSource` or `replicaSet`') - ); - } - - result.query = Object.assign({}, record, result.query); - } - - // Set completed options back into the URL object. - result.search = qs.stringify(result.query); - - const finalString = URL.format(result); - parseConnectionString(finalString, options, (err, ret) => { - if (err) { - callback(err); - return; - } - - callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); - }); - }); - }); -} - -/** - * Parses a query string item according to the connection string spec - * - * @param {string} key The key for the parsed value - * @param {Array|String} value The value to parse - * @return {Array|Object|String} The parsed value - */ -function parseQueryStringItemValue(key, value) { - if (Array.isArray(value)) { - // deduplicate and simplify arrays - value = value.filter((v, idx) => value.indexOf(v) === idx); - if (value.length === 1) value = value[0]; - } else if (value.indexOf(':') > 0) { - value = value.split(',').reduce((result, pair) => { - const parts = pair.split(':'); - result[parts[0]] = parseQueryStringItemValue(key, parts[1]); - return result; - }, {}); - } else if (value.indexOf(',') > 0) { - value = value.split(',').map(v => { - return parseQueryStringItemValue(key, v); - }); - } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { - value = value.toLowerCase() === 'true'; - } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { - const numericValue = parseFloat(value); - if (!Number.isNaN(numericValue)) { - value = parseFloat(value); - } - } - - return value; -} - -// Options that are known boolean types -const BOOLEAN_OPTIONS = new Set([ - 'slaveok', - 'slave_ok', - 'sslvalidate', - 'fsync', - 'safe', - 'retrywrites', - 'j' -]); - -// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` -const STRING_OPTIONS = new Set(['authsource', 'replicaset']); - -// Supported text representations of auth mechanisms -// NOTE: this list exists in native already, if it is merged here we should deduplicate -const AUTH_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-AWS', - 'MONGODB-X509', - 'MONGODB-CR', - 'DEFAULT', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'PLAIN' -]); - -// Lookup table used to translate normalized (lower-cased) forms of connection string -// options to their expected camelCase version -const CASE_TRANSLATION = { - replicaset: 'replicaSet', - connecttimeoutms: 'connectTimeoutMS', - sockettimeoutms: 'socketTimeoutMS', - maxpoolsize: 'maxPoolSize', - minpoolsize: 'minPoolSize', - maxidletimems: 'maxIdleTimeMS', - waitqueuemultiple: 'waitQueueMultiple', - waitqueuetimeoutms: 'waitQueueTimeoutMS', - wtimeoutms: 'wtimeoutMS', - readconcern: 'readConcern', - readconcernlevel: 'readConcernLevel', - readpreference: 'readPreference', - maxstalenessseconds: 'maxStalenessSeconds', - readpreferencetags: 'readPreferenceTags', - authsource: 'authSource', - authmechanism: 'authMechanism', - authmechanismproperties: 'authMechanismProperties', - gssapiservicename: 'gssapiServiceName', - localthresholdms: 'localThresholdMS', - serverselectiontimeoutms: 'serverSelectionTimeoutMS', - serverselectiontryonce: 'serverSelectionTryOnce', - heartbeatfrequencyms: 'heartbeatFrequencyMS', - retrywrites: 'retryWrites', - uuidrepresentation: 'uuidRepresentation', - zlibcompressionlevel: 'zlibCompressionLevel', - tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', - tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', - tlsinsecure: 'tlsInsecure', - tlscafile: 'tlsCAFile', - tlscertificatekeyfile: 'tlsCertificateKeyFile', - tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', - wtimeout: 'wTimeoutMS', - j: 'journal', - directconnection: 'directConnection' -}; - -/** - * Sets the value for `key`, allowing for any required translation - * - * @param {object} obj The object to set the key on - * @param {string} key The key to set the value for - * @param {*} value The value to set - * @param {object} options The options used for option parsing - */ -function applyConnectionStringOption(obj, key, value, options) { - // simple key translation - if (key === 'journal') { - key = 'j'; - } else if (key === 'wtimeoutms') { - key = 'wtimeout'; - } - - // more complicated translation - if (BOOLEAN_OPTIONS.has(key)) { - value = value === 'true' || value === true; - } else if (key === 'appname') { - value = decodeURIComponent(value); - } else if (key === 'readconcernlevel') { - obj['readConcernLevel'] = value; - key = 'readconcern'; - value = { level: value }; - } - - // simple validation - if (key === 'compressors') { - value = Array.isArray(value) ? value : [value]; - - if (!value.every(c => c === 'snappy' || c === 'zlib')) { - throw new MongoParseError( - 'Value for `compressors` must be at least one of: `snappy`, `zlib`' - ); - } - } - - if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { - throw new MongoParseError( - `Value for authMechanism must be one of: ${Array.from(AUTH_MECHANISMS).join( - ', ' - )}, found: ${value}` - ); - } - - if (key === 'readpreference' && !ReadPreference.isValid(value)) { - throw new MongoParseError( - 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' - ); - } - - if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { - throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); - } - - // special cases - if (key === 'compressors' || key === 'zlibcompressionlevel') { - obj.compression = obj.compression || {}; - obj = obj.compression; - } - - if (key === 'authmechanismproperties') { - if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; - if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; - if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { - obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; - } - } - - if (key === 'readpreferencetags') { - value = Array.isArray(value) ? splitArrayOfMultipleReadPreferenceTags(value) : [value]; - } - - // set the actual value - if (options.caseTranslate && CASE_TRANSLATION[key]) { - obj[CASE_TRANSLATION[key]] = value; - return; - } - - obj[key] = value; -} - -const USERNAME_REQUIRED_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-CR', - 'PLAIN', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256' -]); - -function splitArrayOfMultipleReadPreferenceTags(value) { - const parsedTags = []; - - for (let i = 0; i < value.length; i++) { - parsedTags[i] = {}; - value[i].split(',').forEach(individualTag => { - const splitTag = individualTag.split(':'); - parsedTags[i][splitTag[0]] = splitTag[1]; - }); - } - - return parsedTags; -} - -/** - * Modifies the parsed connection string object taking into account expectations we - * have for authentication-related options. - * - * @param {object} parsed The parsed connection string result - * @return The parsed connection string result possibly modified for auth expectations - */ -function applyAuthExpectations(parsed) { - if (parsed.options == null) { - return; - } - - const options = parsed.options; - const authSource = options.authsource || options.authSource; - if (authSource != null) { - parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); - } - - const authMechanism = options.authmechanism || options.authMechanism; - if (authMechanism != null) { - if ( - USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && - (!parsed.auth || parsed.auth.username == null) - ) { - throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); - } - - if (authMechanism === 'GSSAPI') { - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'MONGODB-AWS') { - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'MONGODB-X509') { - if (parsed.auth && parsed.auth.password != null) { - throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); - } - - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'PLAIN') { - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - } - } - - // default to `admin` if nothing else was resolved - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); - } - - return parsed; -} - -/** - * Parses a query string according the connection string spec. - * - * @param {String} query The query string to parse - * @param {object} [options] The options used for options parsing - * @return {Object|Error} The parsed query string as an object, or an error if one was encountered - */ -function parseQueryString(query, options) { - const result = {}; - let parsedQueryString = qs.parse(query); - - checkTLSOptions(parsedQueryString); - - for (const key in parsedQueryString) { - const value = parsedQueryString[key]; - if (value === '' || value == null) { - throw new MongoParseError('Incomplete key value pair for option'); - } - - const normalizedKey = key.toLowerCase(); - if (normalizedKey === 'serverapi') { - throw new MongoParseError( - 'URI cannot contain `serverApi`, it can only be passed to the client' - ); - } - const parsedValue = FILE_PATH_OPTIONS.has(normalizedKey) - ? value - : parseQueryStringItemValue(normalizedKey, value); - applyConnectionStringOption(result, normalizedKey, parsedValue, options); - } - - // special cases for known deprecated options - if (result.wtimeout && result.wtimeoutms) { - delete result.wtimeout; - emitWarningOnce('Unsupported option `wtimeout` specified'); - } - - return Object.keys(result).length ? result : null; -} - -/// Adds support for modern `tls` variants of out `ssl` options -function translateTLSOptions(queryString) { - if (queryString.tls) { - queryString.ssl = queryString.tls; - } - - if (queryString.tlsInsecure) { - queryString.checkServerIdentity = false; - queryString.sslValidate = false; - } else { - Object.assign(queryString, { - checkServerIdentity: queryString.tlsAllowInvalidHostnames ? false : true, - sslValidate: queryString.tlsAllowInvalidCertificates ? false : true - }); - } - - if (queryString.tlsCAFile) { - queryString.ssl = true; - queryString.sslCA = queryString.tlsCAFile; - } - - if (queryString.tlsCertificateKeyFile) { - queryString.ssl = true; - if (queryString.tlsCertificateFile) { - queryString.sslCert = queryString.tlsCertificateFile; - queryString.sslKey = queryString.tlsCertificateKeyFile; - } else { - queryString.sslKey = queryString.tlsCertificateKeyFile; - queryString.sslCert = queryString.tlsCertificateKeyFile; - } - } - - if (queryString.tlsCertificateKeyFilePassword) { - queryString.ssl = true; - queryString.sslPass = queryString.tlsCertificateKeyFilePassword; - } - - return queryString; -} - -/** - * Checks a query string for invalid tls options according to the URI options spec. - * - * @param {string} queryString The query string to check - * @throws {MongoParseError} - */ -function checkTLSOptions(queryString) { - const queryStringKeys = Object.keys(queryString); - if ( - queryStringKeys.indexOf('tlsInsecure') !== -1 && - (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || - queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) - ) { - throw new MongoParseError( - 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' - ); - } - - const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); - const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); - - if (tlsValue != null && sslValue != null) { - if (tlsValue !== sslValue) { - throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); - } - } -} - -/** - * Checks a query string to ensure all tls/ssl options are the same. - * - * @param {string} key The key (tls or ssl) to check - * @param {string} queryString The query string to check - * @throws {MongoParseError} - * @return The value of the tls/ssl option - */ -function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { - const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; - - let optionValue; - if (Array.isArray(queryString[optionName])) { - optionValue = queryString[optionName][0]; - } else { - optionValue = queryString[optionName]; - } - - if (queryStringHasTLSOption) { - if (Array.isArray(queryString[optionName])) { - const firstValue = queryString[optionName][0]; - queryString[optionName].forEach(tlsValue => { - if (tlsValue !== firstValue) { - throw new MongoParseError(`All values of ${optionName} must be the same.`); - } - }); - } - } - - return optionValue; -} - -const PROTOCOL_MONGODB = 'mongodb'; -const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; -const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; - -/** - * Parses a MongoDB connection string - * - * @param {*} uri the MongoDB connection string to parse - * @param {object} [options] Optional settings. - * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization - * @param {parseCallback} callback - */ -function parseConnectionString(uri, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { caseTranslate: true }, options); - - // Check for bad uris before we parse - try { - URL.parse(uri); - } catch (e) { - return callback(new MongoParseError('URI malformed, cannot be parsed')); - } - - const cap = uri.match(HOSTS_RX); - if (!cap) { - return callback(new MongoParseError('Invalid connection string')); - } - - const protocol = cap[1]; - if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { - return callback(new MongoParseError('Invalid protocol provided')); - } - - const dbAndQuery = cap[4].split('?'); - const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; - const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; - - let parsedOptions; - try { - parsedOptions = parseQueryString(query, options); - } catch (parseError) { - return callback(parseError); - } - - parsedOptions = Object.assign({}, parsedOptions, options); - - if (Object.keys(parsedOptions).some(k => k.toLowerCase() === 'loadbalanced')) { - return callback(new MongoParseError('Load balancer mode requires driver version 4+')); - } - - if (protocol === PROTOCOL_MONGODB_SRV) { - return parseSrvConnectionString(uri, parsedOptions, callback); - } - - const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; - if (parsedOptions.auth) { - // maintain support for legacy options passed into `MongoClient` - if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; - if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; - if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; - } else { - if (parsedOptions.username) auth.username = parsedOptions.username; - if (parsedOptions.user) auth.username = parsedOptions.user; - if (parsedOptions.password) auth.password = parsedOptions.password; - } - - if (cap[4].split('?')[0].indexOf('@') !== -1) { - return callback(new MongoParseError('Unescaped slash in userinfo section')); - } - - const authorityParts = cap[3].split('@'); - if (authorityParts.length > 2) { - return callback(new MongoParseError('Unescaped at-sign in authority section')); - } - - if (authorityParts[0] == null || authorityParts[0] === '') { - return callback(new MongoParseError('No username provided in authority section')); - } - - if (authorityParts.length > 1) { - const authParts = authorityParts.shift().split(':'); - if (authParts.length > 2) { - return callback(new MongoParseError('Unescaped colon in authority section')); - } - - if (authParts[0] === '') { - return callback(new MongoParseError('Invalid empty username provided')); - } - - if (!auth.username) auth.username = qs.unescape(authParts[0]); - if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; - } - - let hostParsingError = null; - const hosts = authorityParts - .shift() - .split(',') - .map(host => { - let parsedHost = URL.parse(`mongodb://${host}`); - if (parsedHost.path === '/:') { - hostParsingError = new MongoParseError('Double colon in host identifier'); - return null; - } - - // heuristically determine if we're working with a domain socket - if (host.match(/\.sock/)) { - parsedHost.hostname = qs.unescape(host); - parsedHost.port = null; - } - - if (Number.isNaN(parsedHost.port)) { - hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); - return; - } - - const result = { - host: parsedHost.hostname, - port: parsedHost.port ? parseInt(parsedHost.port) : 27017 - }; - - if (result.port === 0) { - hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); - return; - } - - if (result.port > 65535) { - hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); - return; - } - - if (result.port < 0) { - hostParsingError = new MongoParseError('Invalid port (negative number)'); - return; - } - - return result; - }) - .filter(host => !!host); - - if (hostParsingError) { - return callback(hostParsingError); - } - - if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { - return callback(new MongoParseError('No hostname or hostnames provided in connection string')); - } - - const directConnection = !!parsedOptions.directConnection; - if (directConnection && hosts.length !== 1) { - // If the option is set to true, the driver MUST validate that there is exactly one host given - // in the host list in the URI, and fail client creation otherwise. - return callback(new MongoParseError('directConnection option requires exactly one host')); - } - - // NOTE: this behavior will go away in v4.0, we will always auto discover there - if ( - parsedOptions.directConnection == null && - hosts.length === 1 && - parsedOptions.replicaSet == null - ) { - parsedOptions.directConnection = true; - } - - const result = { - hosts: hosts, - auth: auth.db || auth.username ? auth : null, - options: Object.keys(parsedOptions).length ? parsedOptions : null - }; - - if (result.auth && result.auth.db) { - result.defaultDatabase = result.auth.db; - } else { - result.defaultDatabase = 'test'; - } - - // support modern `tls` variants to SSL options - result.options = translateTLSOptions(result.options); - - try { - applyAuthExpectations(result); - } catch (authError) { - return callback(authError); - } - - callback(null, result); -} - -module.exports = parseConnectionString; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/utils.js b/reverse_engineering/node_modules/mongodb/lib/core/utils.js deleted file mode 100644 index 0940619..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/utils.js +++ /dev/null @@ -1,295 +0,0 @@ -'use strict'; -const os = require('os'); -const crypto = require('crypto'); -const requireOptional = require('optional-require')(require); - -/** - * Generate a UUIDv4 - */ -const uuidV4 = () => { - const result = crypto.randomBytes(16); - result[6] = (result[6] & 0x0f) | 0x40; - result[8] = (result[8] & 0x3f) | 0x80; - return result; -}; - -/** - * Relays events for a given listener and emitter - * - * @param {EventEmitter} listener the EventEmitter to listen to the events from - * @param {EventEmitter} emitter the EventEmitter to relay the events to - */ -function relayEvents(listener, emitter, events) { - events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); -} - -function retrieveKerberos() { - let kerberos; - - try { - // Ensure you always wrap an optional require in the try block NODE-3199 - kerberos = requireOptional('kerberos'); - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - throw new Error('The `kerberos` module was not found. Please install it and try again.'); - } - - throw err; - } - - return kerberos; -} - -// Throw an error if an attempt to use EJSON is made when it is not installed -const noEJSONError = function() { - throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); -}; - -// Facilitate loading EJSON optionally -function retrieveEJSON() { - let EJSON = requireOptional('mongodb-extjson'); - if (!EJSON) { - EJSON = { - parse: noEJSONError, - deserialize: noEJSONError, - serialize: noEJSONError, - stringify: noEJSONError, - setBSONModule: noEJSONError, - BSON: noEJSONError - }; - } - - return EJSON; -} - -/** - * A helper function for determining `maxWireVersion` between legacy and new topology - * instances - * - * @private - * @param {(Topology|Server)} topologyOrServer - */ -function maxWireVersion(topologyOrServer) { - if (topologyOrServer) { - if (topologyOrServer.ismaster) { - return topologyOrServer.ismaster.maxWireVersion; - } - - if (typeof topologyOrServer.lastIsMaster === 'function') { - const lastIsMaster = topologyOrServer.lastIsMaster(); - if (lastIsMaster) { - return lastIsMaster.maxWireVersion; - } - } - - if (topologyOrServer.description) { - return topologyOrServer.description.maxWireVersion; - } - } - - return 0; -} - -/* - * Checks that collation is supported by server. - * - * @param {Server} [server] to check against - * @param {object} [cmd] object where collation may be specified - * @param {function} [callback] callback function - * @return true if server does not support collation - */ -function collationNotSupported(server, cmd) { - return cmd && cmd.collation && maxWireVersion(server) < 5; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies the function `eachFn` to each item in `arr`, in parallel. - * - * @param {array} arr an array of items to asynchronusly iterate over - * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. - * @param {function} callback The callback called after every item has been iterated - */ -function eachAsync(arr, eachFn, callback) { - arr = arr || []; - - let idx = 0; - let awaiting = 0; - for (idx = 0; idx < arr.length; ++idx) { - awaiting++; - eachFn(arr[idx], eachCallback); - } - - if (awaiting === 0) { - callback(); - return; - } - - function eachCallback(err) { - awaiting--; - if (err) { - callback(err); - return; - } - - if (idx === arr.length && awaiting <= 0) { - callback(); - } - } -} - -function eachAsyncSeries(arr, eachFn, callback) { - arr = arr || []; - - let idx = 0; - let awaiting = arr.length; - if (awaiting === 0) { - callback(); - return; - } - - function eachCallback(err) { - idx++; - awaiting--; - if (err) { - callback(err); - return; - } - - if (idx === arr.length && awaiting <= 0) { - callback(); - return; - } - - eachFn(arr[idx], eachCallback); - } - - eachFn(arr[idx], eachCallback); -} - -function isUnifiedTopology(topology) { - return topology.description != null; -} - -function arrayStrictEqual(arr, arr2) { - if (!Array.isArray(arr) || !Array.isArray(arr2)) { - return false; - } - - return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); -} - -function tagsStrictEqual(tags, tags2) { - const tagsKeys = Object.keys(tags); - const tags2Keys = Object.keys(tags2); - return tagsKeys.length === tags2Keys.length && tagsKeys.every(key => tags2[key] === tags[key]); -} - -function errorStrictEqual(lhs, rhs) { - if (lhs === rhs) { - return true; - } - - if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { - return false; - } - - if (lhs.constructor.name !== rhs.constructor.name) { - return false; - } - - if (lhs.message !== rhs.message) { - return false; - } - - return true; -} - -function makeStateMachine(stateTable) { - return function stateTransition(target, newState) { - const legalStates = stateTable[target.s.state]; - if (legalStates && legalStates.indexOf(newState) < 0) { - throw new TypeError( - `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]` - ); - } - - target.emit('stateChanged', target.s.state, newState); - target.s.state = newState; - }; -} - -function makeClientMetadata(options) { - options = options || {}; - - const metadata = { - driver: { - name: 'nodejs', - version: require('../../package.json').version - }, - os: { - type: os.type(), - name: process.platform, - architecture: process.arch, - version: os.release() - }, - platform: `'Node.js ${process.version}, ${os.endianness} (${ - options.useUnifiedTopology ? 'unified' : 'legacy' - })` - }; - - // support optionally provided wrapping driver info - if (options.driverInfo) { - if (options.driverInfo.name) { - metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; - } - - if (options.driverInfo.version) { - metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; - } - - if (options.driverInfo.platform) { - metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; - } - } - - if (options.appname) { - // MongoDB requires the appname not exceed a byte length of 128 - const buffer = Buffer.from(options.appname); - metadata.application = { - name: buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname - }; - } - - return metadata; -} - -const noop = () => {}; - -module.exports = { - uuidV4, - relayEvents, - collationNotSupported, - retrieveEJSON, - retrieveKerberos, - maxWireVersion, - isPromiseLike, - eachAsync, - eachAsyncSeries, - isUnifiedTopology, - arrayStrictEqual, - tagsStrictEqual, - errorStrictEqual, - makeStateMachine, - makeClientMetadata, - noop -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/command.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/command.js deleted file mode 100644 index 8ebcb73..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/command.js +++ /dev/null @@ -1,206 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const Msg = require('../connection/msg').Msg; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const isSharded = require('./shared').isSharded; -const databaseNamespace = require('./shared').databaseNamespace; -const isTransactionCommand = require('../transactions').isTransactionCommand; -const applySession = require('../sessions').applySession; -const MongoNetworkError = require('../error').MongoNetworkError; -const maxWireVersion = require('../utils').maxWireVersion; - -function isClientEncryptionEnabled(server) { - const wireVersion = maxWireVersion(server); - return wireVersion && server.autoEncrypter; -} - -function command(server, ns, cmd, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (!isClientEncryptionEnabled(server)) { - _command(server, ns, cmd, options, callback); - return; - } - - const wireVersion = maxWireVersion(server); - if (typeof wireVersion !== 'number' || wireVersion < 8) { - callback(new MongoError('Auto-encryption requires a minimum MongoDB version of 4.2')); - return; - } - - _cryptCommand(server, ns, cmd, options, callback); -} - -function _command(server, ns, cmd, options, callback) { - const bson = server.s.bson; - const pool = server.s.pool; - const readPreference = getReadPreference(cmd, options); - const shouldUseOpMsg = supportsOpMsg(server); - const session = options.session; - - const serverClusterTime = server.clusterTime; - let clusterTime = serverClusterTime; - let finalCmd = Object.assign({}, cmd); - - const serverApi = options.serverApi; - if (serverApi) { - finalCmd.apiVersion = serverApi.version || serverApi; - if (serverApi.strict != null) { - finalCmd.apiStrict = serverApi.strict; - } - if (serverApi.deprecationErrors != null) { - finalCmd.apiDeprecationErrors = serverApi.deprecationErrors; - } - } - - if (hasSessionSupport(server) && session) { - const sessionClusterTime = session.clusterTime; - if ( - serverClusterTime && - serverClusterTime.clusterTime && - sessionClusterTime && - sessionClusterTime.clusterTime && - sessionClusterTime.clusterTime.greaterThan(serverClusterTime.clusterTime) - ) { - clusterTime = sessionClusterTime; - } - - // We need to unpin any read or write commands that happen outside of a pinned - // transaction, so we check if we have a pinned transaction that is no longer - // active, and unpin for all except start or commit. - if ( - !session.transaction.isActive && - session.transaction.isPinned && - !finalCmd.startTransaction && - !finalCmd.commitTransaction - ) { - session.transaction.unpinServer(); - } - - const err = applySession(session, finalCmd, options); - if (err) { - return callback(err); - } - } - - if (clusterTime) { - // if we have a known cluster time, gossip it - finalCmd.$clusterTime = clusterTime; - } - - if (isSharded(server) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON() - }; - } - - const commandOptions = Object.assign( - { - command: true, - numberToSkip: 0, - numberToReturn: -1, - checkKeys: false - }, - options - ); - - // This value is not overridable - commandOptions.slaveOk = readPreference.slaveOk(); - - const cmdNs = `${databaseNamespace(ns)}.$cmd`; - const message = shouldUseOpMsg - ? new Msg(bson, cmdNs, finalCmd, commandOptions) - : new Query(bson, cmdNs, finalCmd, commandOptions); - - const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); - const commandResponseHandler = inTransaction - ? function(err) { - // We need to add a TransientTransactionError errorLabel, as stated in the transaction spec. - if ( - err && - err instanceof MongoNetworkError && - !err.hasErrorLabel('TransientTransactionError') - ) { - err.addErrorLabel('TransientTransactionError'); - } - - if ( - !cmd.commitTransaction && - err && - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') - ) { - session.transaction.unpinServer(); - } - - return callback.apply(null, arguments); - } - : callback; - - try { - pool.write(message, commandOptions, commandResponseHandler); - } catch (err) { - commandResponseHandler(err); - } -} - -function hasSessionSupport(topology) { - if (topology == null) return false; - if (topology.description) { - return topology.description.maxWireVersion >= 6; - } - - return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; -} - -function supportsOpMsg(topologyOrServer) { - const description = topologyOrServer.ismaster - ? topologyOrServer.ismaster - : topologyOrServer.description; - - if (description == null) { - return false; - } - - return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; -} - -function _cryptCommand(server, ns, cmd, options, callback) { - const autoEncrypter = server.autoEncrypter; - function commandResponseHandler(err, response) { - if (err || response == null) { - callback(err, response); - return; - } - - autoEncrypter.decrypt(response.result, options, (err, decrypted) => { - if (err) { - callback(err, null); - return; - } - - response.result = decrypted; - response.message.documents = [decrypted]; - callback(null, response); - }); - } - - autoEncrypter.encrypt(ns, cmd, options, (err, encrypted) => { - if (err) { - callback(err, null); - return; - } - - _command(server, ns, encrypted, options, commandResponseHandler); - }); -} - -module.exports = command; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/compression.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/compression.js deleted file mode 100644 index b1e1583..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/compression.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -const Snappy = require('../connection/utils').retrieveSnappy(); -const zlib = require('zlib'); - -const compressorIDs = { - snappy: 1, - zlib: 2 -}; - -const uncompressibleCommands = new Set([ - 'ismaster', - 'saslStart', - 'saslContinue', - 'getnonce', - 'authenticate', - 'createUser', - 'updateUser', - 'copydbSaslStart', - 'copydbgetnonce', - 'copydb' -]); - -// Facilitate compressing a message using an agreed compressor -function compress(self, dataToBeCompressed, callback) { - switch (self.options.agreedCompressor) { - case 'snappy': - Snappy.compress(dataToBeCompressed, callback); - break; - case 'zlib': - // Determine zlibCompressionLevel - var zlibOptions = {}; - if (self.options.zlibCompressionLevel) { - zlibOptions.level = self.options.zlibCompressionLevel; - } - zlib.deflate(dataToBeCompressed, zlibOptions, callback); - break; - default: - throw new Error( - 'Attempt to compress message using unknown compressor "' + - self.options.agreedCompressor + - '".' - ); - } -} - -// Decompress a message using the given compressor -function decompress(compressorID, compressedData, callback) { - if (compressorID < 0 || compressorID > compressorIDs.length) { - throw new Error( - 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + - compressorID + - ')' - ); - } - switch (compressorID) { - case compressorIDs.snappy: - Snappy.uncompress(compressedData, callback); - break; - case compressorIDs.zlib: - zlib.inflate(compressedData, callback); - break; - default: - callback(null, compressedData); - } -} - -module.exports = { - compressorIDs, - uncompressibleCommands, - compress, - decompress -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/constants.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/constants.js deleted file mode 100644 index a9789b1..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const MIN_SUPPORTED_SERVER_VERSION = '2.6'; -const MAX_SUPPORTED_SERVER_VERSION = '5.0'; -const MIN_SUPPORTED_WIRE_VERSION = 2; -const MAX_SUPPORTED_WIRE_VERSION = 13; - -module.exports = { - MIN_SUPPORTED_SERVER_VERSION, - MAX_SUPPORTED_SERVER_VERSION, - MIN_SUPPORTED_WIRE_VERSION, - MAX_SUPPORTED_WIRE_VERSION -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/get_more.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/get_more.js deleted file mode 100644 index 9e452f6..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/get_more.js +++ /dev/null @@ -1,95 +0,0 @@ -'use strict'; - -const GetMore = require('../connection/commands').GetMore; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const BSON = retrieveBSON(); -const Long = BSON.Long; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function getMore(server, ns, cursorState, batchSize, options, callback) { - options = options || {}; - - const wireVersion = maxWireVersion(server); - function queryCallback(err, result) { - if (err) return callback(err); - const response = result.message; - - // If we have a timed out query or a cursor that was killed - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (wireVersion < 4) { - const cursorId = - typeof response.cursorId === 'number' - ? Long.fromNumber(response.cursorId) - : response.cursorId; - - cursorState.documents = response.documents; - cursorState.cursorId = cursorId; - - callback(null, null, response.connection); - return; - } - - // We have an error detected - if (response.documents[0].ok === 0) { - return callback(new MongoError(response.documents[0])); - } - - // Ensure we have a Long valid cursor id - const cursorId = - typeof response.documents[0].cursor.id === 'number' - ? Long.fromNumber(response.documents[0].cursor.id) - : response.documents[0].cursor.id; - - cursorState.documents = response.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - callback(null, response.documents[0], response.connection); - } - - if (wireVersion < 4) { - const bson = server.s.bson; - const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); - const queryOptions = applyCommonQueryOptions({}, cursorState); - server.s.pool.write(getMoreOp, queryOptions, queryCallback); - return; - } - - const cursorId = - cursorState.cursorId instanceof Long - ? cursorState.cursorId - : Long.fromNumber(cursorState.cursorId); - - const getMoreCmd = { - getMore: cursorId, - collection: collectionNamespace(ns), - batchSize: Math.abs(batchSize) - }; - - if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { - getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; - } - - const commandOptions = Object.assign( - { - returnFieldSelector: null, - documentsReturnedIn: 'nextBatch' - }, - options - ); - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, getMoreCmd, commandOptions, queryCallback); -} - -module.exports = getMore; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/index.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/index.js deleted file mode 100644 index b6ffda7..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; -const writeCommand = require('./write_command'); - -module.exports = { - insert: function insert(server, ns, ops, options, callback) { - writeCommand(server, 'insert', 'documents', ns, ops, options, callback); - }, - update: function update(server, ns, ops, options, callback) { - writeCommand(server, 'update', 'updates', ns, ops, options, callback); - }, - remove: function remove(server, ns, ops, options, callback) { - writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); - }, - killCursors: require('./kill_cursors'), - getMore: require('./get_more'), - query: require('./query'), - command: require('./command') -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js deleted file mode 100644 index e54001a..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -const KillCursor = require('../connection/commands').KillCursor; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const emitWarning = require('../utils').emitWarning; -const command = require('./command'); - -function killCursors(server, ns, cursorState, defaultOptions, callback) { - if (typeof defaultOptions === 'function') { - callback = defaultOptions; - defaultOptions = {}; - } - callback = typeof callback === 'function' ? callback : () => {}; - - const cursorId = cursorState.cursorId; - - if (maxWireVersion(server) < 4) { - const bson = server.s.bson; - const pool = server.s.pool; - const killCursor = new KillCursor(bson, ns, [cursorId]); - const options = { - immediateRelease: true, - noResponse: true - }; - - if (typeof cursorState.session === 'object') { - options.session = cursorState.session; - } - - if (pool && pool.isConnected()) { - try { - pool.write(killCursor, options, callback); - } catch (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - emitWarning(err); - } - } - } - - return; - } - - const killCursorCmd = { - killCursors: collectionNamespace(ns), - cursors: [cursorId] - }; - - const options = defaultOptions || {}; - if (typeof cursorState.session === 'object') options.session = cursorState.session; - - command(server, ns, killCursorCmd, options, (err, result) => { - if (err) { - return callback(err); - } - - const response = result.message; - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (!Array.isArray(response.documents) || response.documents.length === 0) { - return callback( - new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) - ); - } - - callback(null, response.documents[0]); - }); -} - -module.exports = killCursors; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/query.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/query.js deleted file mode 100644 index 2988ae6..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/query.js +++ /dev/null @@ -1,240 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const collectionNamespace = require('./shared').collectionNamespace; -const isSharded = require('./shared').isSharded; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); -const decorateWithExplain = require('../../utils').decorateWithExplain; -const Explain = require('../../explain').Explain; - -function query(server, ns, cmd, cursorState, options, callback) { - options = options || {}; - if (cursorState.cursorId != null) { - return callback(); - } - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (maxWireVersion(server) < 4) { - const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); - const queryOptions = applyCommonQueryOptions({}, cursorState); - if (typeof query.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = query.documentsReturnedIn; - } - - server.s.pool.write(query, queryOptions, callback); - return; - } - - const readPreference = getReadPreference(cmd, options); - let findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - try { - const explain = Explain.fromOptions(options); - if (explain) { - findCmd = decorateWithExplain(findCmd, explain); - } - } catch (err) { - return callback(err); - } - - // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this - // side-effect. Change this ASAP - cmd.virtual = false; - - const commandOptions = Object.assign( - { - documentsReturnedIn: 'firstBatch', - numberToReturn: 1, - slaveOk: readPreference.slaveOk() - }, - options - ); - - if (cmd.readPreference) { - commandOptions.readPreference = readPreference; - } - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, findCmd, commandOptions, callback); -} - -function prepareFindCommand(server, ns, cmd, cursorState) { - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - const findCmd = { - find: collectionNamespace(ns) - }; - - if (cmd.query) { - if (cmd.query['$query']) { - findCmd.filter = cmd.query['$query']; - } else { - findCmd.filter = cmd.query; - } - } - - let sortValue = cmd.sort; - if (Array.isArray(sortValue)) { - const sortObject = {}; - - if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { - let sortDirection = sortValue[1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[0]] = sortDirection; - } else { - for (let i = 0; i < sortValue.length; i++) { - let sortDirection = sortValue[i][1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - } - - if (typeof cmd.allowDiskUse === 'boolean') { - findCmd.allowDiskUse = cmd.allowDiskUse; - } - - if (cmd.sort) findCmd.sort = sortValue; - if (cmd.fields) findCmd.projection = cmd.fields; - if (cmd.hint) findCmd.hint = cmd.hint; - if (cmd.skip) findCmd.skip = cmd.skip; - if (cmd.limit) findCmd.limit = cmd.limit; - if (cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - if (typeof cmd.batchSize === 'number') { - if (cmd.batchSize < 0) { - if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { - findCmd.limit = Math.abs(cmd.batchSize); - } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); - } - - if (cmd.comment) findCmd.comment = cmd.comment; - if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; - if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - if (cmd.min) findCmd.min = cmd.min; - if (cmd.max) findCmd.max = cmd.max; - if (typeof cmd.returnKey === 'boolean') findCmd.returnKey = cmd.returnKey; - if (typeof cmd.showDiskLoc === 'boolean') findCmd.showRecordId = cmd.showDiskLoc; - if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; - if (cmd.tailable) findCmd.tailable = cmd.tailable; - if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - if (cmd.partial) findCmd.partial = cmd.partial; - if (cmd.collation) findCmd.collation = cmd.collation; - if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - return findCmd; -} - -function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { - options = options || {}; - const bson = server.s.bson; - const readPreference = getReadPreference(cmd, options); - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - let numberToReturn = 0; - if ( - cursorState.limit < 0 || - (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || - (cursorState.limit > 0 && cursorState.batchSize === 0) - ) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - const numberToSkip = cursorState.skip || 0; - - const findCmd = {}; - if (isSharded(server) && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - if (cmd.sort) findCmd['$orderby'] = cmd.sort; - if (cmd.hint) findCmd['$hint'] = cmd.hint; - if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; - if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; - if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; - if (cmd.min) findCmd['$min'] = cmd.min; - if (cmd.max) findCmd['$max'] = cmd.max; - if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; - if (cmd.comment) findCmd['$comment'] = cmd.comment; - if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; - if (options.explain !== undefined) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - findCmd['$explain'] = true; - } - - findCmd['$query'] = cmd.query; - if (cmd.readConcern && cmd.readConcern.level !== 'local') { - throw new MongoError( - `server find command does not support a readConcern level of ${cmd.readConcern.level}` - ); - } - - if (cmd.readConcern) { - cmd = Object.assign({}, cmd); - delete cmd['readConcern']; - } - - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - - const query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, - numberToReturn: numberToReturn, - pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, - checkKeys: false, - returnFieldSelector: cmd.fields, - serializeFunctions: serializeFunctions, - ignoreUndefined: ignoreUndefined - }); - - if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; - if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; - if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; - if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; - - query.slaveOk = readPreference.slaveOk(); - return query; -} - -module.exports = query; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/shared.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/shared.js deleted file mode 100644 index 99c70a3..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/shared.js +++ /dev/null @@ -1,116 +0,0 @@ -'use strict'; - -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; -const ServerType = require('../sdam/common').ServerType; -const TopologyDescription = require('../sdam/topology_description').TopologyDescription; - -const MESSAGE_HEADER_SIZE = 16; -const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID - -// OPCODE Numbers -// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes -var opcodes = { - OP_REPLY: 1, - OP_UPDATE: 2001, - OP_INSERT: 2002, - OP_QUERY: 2004, - OP_GETMORE: 2005, - OP_DELETE: 2006, - OP_KILL_CURSORS: 2007, - OP_COMPRESSED: 2012, - OP_MSG: 2013 -}; - -var getReadPreference = function(cmd, options) { - // Default to command version of the readPreference - var readPreference = cmd.readPreference || new ReadPreference('primary'); - // If we have an option readPreference override the command one - if (options.readPreference) { - readPreference = options.readPreference; - } - - if (typeof readPreference === 'string') { - readPreference = new ReadPreference(readPreference); - } - - if (!(readPreference instanceof ReadPreference)) { - throw new MongoError('read preference must be a ReadPreference instance'); - } - - return readPreference; -}; - -// Parses the header of a wire protocol message -var parseHeader = function(message) { - return { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; -}; - -function applyCommonQueryOptions(queryOptions, options) { - Object.assign(queryOptions, { - raw: typeof options.raw === 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false - }); - - if (typeof options.socketTimeout === 'number') { - queryOptions.socketTimeout = options.socketTimeout; - } - - if (options.session) { - queryOptions.session = options.session; - } - - if (typeof options.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = options.documentsReturnedIn; - } - - return queryOptions; -} - -function isSharded(topologyOrServer) { - if (topologyOrServer.type === 'mongos') return true; - if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { - return true; - } - - // NOTE: This is incredibly inefficient, and should be removed once command construction - // happens based on `Server` not `Topology`. - if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { - const servers = Array.from(topologyOrServer.description.servers.values()); - return servers.some(server => server.type === ServerType.Mongos); - } - - return false; -} - -function databaseNamespace(ns) { - return ns.split('.')[0]; -} -function collectionNamespace(ns) { - return ns - .split('.') - .slice(1) - .join('.'); -} - -module.exports = { - getReadPreference, - MESSAGE_HEADER_SIZE, - COMPRESSION_DETAILS_SIZE, - opcodes, - parseHeader, - applyCommonQueryOptions, - isSharded, - databaseNamespace, - collectionNamespace -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/write_command.js b/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/write_command.js deleted file mode 100644 index e6babc3..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/core/wireprotocol/write_command.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; -const collectionNamespace = require('./shared').collectionNamespace; -const command = require('./command'); -const decorateWithExplain = require('../../utils').decorateWithExplain; -const Explain = require('../../explain').Explain; - -function writeCommand(server, type, opsField, ns, ops, options, callback) { - if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; - const writeConcern = options.writeConcern; - - let writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - if (options.collation) { - for (let i = 0; i < writeCommand[opsField].length; i++) { - if (!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; - } - } - } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // If a command is to be explained, we need to reformat the command after - // the other command properties are specified. - const explain = Explain.fromOptions(options); - if (explain) { - writeCommand = decorateWithExplain(writeCommand, explain); - } - - const commandOptions = Object.assign( - { - checkKeys: type === 'insert', - numberToReturn: 1 - }, - options - ); - - command(server, ns, writeCommand, commandOptions, callback); -} - -module.exports = writeCommand; diff --git a/reverse_engineering/node_modules/mongodb/lib/cursor.js b/reverse_engineering/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index 63f5fb7..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1151 +0,0 @@ -'use strict'; - -const Transform = require('stream').Transform; -const PassThrough = require('stream').PassThrough; -const deprecate = require('util').deprecate; -const handleCallback = require('./utils').handleCallback; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const CoreCursor = require('./core/cursor').CoreCursor; -const CursorState = require('./core/cursor').CursorState; -const Map = require('./core').BSON.Map; -const maybePromise = require('./utils').maybePromise; -const executeOperation = require('./operations/execute_operation'); -const formattedOrderClause = require('./utils').formattedOrderClause; -const Explain = require('./explain').Explain; -const Aspect = require('./operations/operation').Aspect; - -const each = require('./operations/cursor_ops').each; -const CountOperation = require('./operations/count'); - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the code module - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -const fields = ['numberOfRetries', 'tailableRetryInterval']; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor max - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(true) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -class Cursor extends CoreCursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - if (this.operation) { - options = this.operation.options; - } - - // Tailable cursor options - const numberOfRetries = options.numberOfRetries || 5; - const tailableRetryInterval = options.tailableRetryInterval || 500; - const currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries, - tailableRetryInterval: tailableRetryInterval, - currentNumberOfRetries: currentNumberOfRetries, - // State - state: CursorState.INIT, - // Promise library - promiseLibrary, - // explicitlyIgnoreSession - explicitlyIgnoreSession: !!options.explicitlyIgnoreSession - }; - - // Optional ClientSession - if (!options.explicitlyIgnoreSession && options.session) { - this.cursorState.session = options.session; - } - - // Translate correctly - if (this.options.noCursorTimeout === true) { - this.addCursorFlag('noCursorTimeout', true); - } - - // Get the batchSize - let batchSize = 1000; - if (this.cmd.cursor && this.cmd.cursor.batchSize) { - batchSize = this.cmd.cursor.batchSize; - } else if (options.cursor && options.cursor.batchSize) { - batchSize = options.cursor.batchSize; - } else if (typeof options.batchSize === 'number') { - batchSize = options.batchSize; - } - - // Set the batchSize - this.setCursorBatchSize(batchSize); - } - - get readPreference() { - if (this.operation) { - return this.operation.readPreference; - } - - return this.options.readPreference; - } - - get sortValue() { - return this.cmd.sort; - } - - set session(clientSession) { - this.cursorState.session = clientSession; - } - - _initializeCursor(callback) { - if (this.operation && this.operation.session != null) { - this.cursorState.session = this.operation.session; - } else { - // implicitly create a session if one has not been provided - if ( - !this.s.explicitlyIgnoreSession && - !this.cursorState.session && - this.topology.hasSessionSupport() - ) { - this.cursorState.session = this.topology.startSession({ owner: this }); - - if (this.operation) { - this.operation.session = this.cursorState.session; - } - } - } - - super._initializeCursor(callback); - } - - /** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - if (this.s.state === CursorState.CLOSED || (this.isDead && this.isDead())) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - return maybePromise(this, callback, cb => { - const cursor = this; - if (cursor.isNotified()) { - return cb(null, false); - } - - cursor._next((err, doc) => { - if (err) return cb(err); - if (doc == null || cursor.s.state === Cursor.CLOSED || cursor.isDead()) { - return cb(null, false); - } - - cursor.s.state = CursorState.OPEN; - - // NODE-2482: merge this into the core cursor implementation - cursor.cursorState.cursorIndex--; - if (cursor.cursorState.limit > 0) { - cursor.cursorState.currentLimit--; - } - - cb(null, true); - }); - }); - } - - /** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - return maybePromise(this, callback, cb => { - const cursor = this; - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - cb(MongoError.create({ message: 'Cursor is closed', driver: true })); - return; - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return cb(err); - } - } - - cursor._next((err, doc) => { - if (err) return cb(err); - cursor.s.state = CursorState.OPEN; - cb(null, doc); - }); - }); - } - - /** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ - filter(filter) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.query = filter; - return this; - } - - /** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - maxScan(maxScan) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxScan = maxScan; - return this; - } - - /** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ - hint(hint) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.hint = hint; - return this; - } - - /** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ - min(min) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.min = min; - return this; - } - - /** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ - max(max) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.max = max; - return this; - } - - /** - * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. - * @method - * @param {bool} returnKey the returnKey value. - * @return {Cursor} - */ - returnKey(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.returnKey = value; - return this; - } - - /** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ - showRecordId(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.showDiskLoc = value; - return this; - } - - /** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - snapshot(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.snapshot = value; - return this; - } - - /** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ - setCursorOption(field, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (fields.indexOf(field) === -1) { - throw MongoError.create({ - message: `option ${field} is not a supported option ${fields}`, - driver: true - }); - } - - this.s[field] = value; - if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; - return this; - } - - /** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ - addCursorFlag(flag, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (flags.indexOf(flag) === -1) { - throw MongoError.create({ - message: `flag ${flag} is not a supported flag ${flags}`, - driver: true - }); - } - - if (typeof value !== 'boolean') { - throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); - } - - this.cmd[flag] = value; - return this; - } - - /** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {string|boolean|number} value The modifier value. - * @throws {MongoError} - * @return {Cursor} - */ - addQueryModifier(name, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (name[0] !== '$') { - throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); - } - - // Strip of the $ - const field = name.substr(1); - // Set on the command - this.cmd[field] = value; - // Deal with the special case for sort - if (field === 'orderby') this.cmd.sort = this.cmd[field]; - return this; - } - - /** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ - comment(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.comment = value; - return this; - } - - /** - * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) - * @method - * @param {number} value Number of milliseconds to wait before aborting the tailed query. - * @throws {MongoError} - * @return {Cursor} - */ - maxAwaitTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxAwaitTimeMS = value; - return this; - } - - /** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ - maxTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxTimeMS = value; - return this; - } - - /** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ - project(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.fields = value; - return this; - } - - /** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ - sort(keyOrList, direction) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - let order = keyOrList; - - // We have an array of arrays, we need to preserve the order of the sort - // so we will us a Map - if (Array.isArray(order) && Array.isArray(order[0])) { - order = new Map( - order.map(x => { - const value = [x[0], null]; - if (x[1] === 'asc') { - value[1] = 1; - } else if (x[1] === 'desc') { - value[1] = -1; - } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { - value[1] = x[1]; - } else { - throw new MongoError( - "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return value; - }) - ); - } - - if (direction != null) { - order = [[keyOrList, direction]]; - } - - this.cmd.sort = order; - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {Cursor} - */ - batchSize(value) { - if (this.options.tailable) { - throw MongoError.create({ - message: "Tailable cursor doesn't support batchSize", - driver: true - }); - } - - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Set the collation options for the cursor. - * @method - * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @throws {MongoError} - * @return {Cursor} - */ - collation(value) { - this.cmd.collation = value; - return this; - } - - /** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - limit(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'limit requires an integer', driver: true }); - } - - this.cmd.limit = value; - this.setCursorLimit(value); - return this; - } - - /** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - skip(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'skip requires an integer', driver: true }); - } - - this.cmd.skip = value; - this.setCursorSkip(value); - return this; - } - - /** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - - /** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - - /** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - - /** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - each(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = CursorState.INIT; - // Run the query - each(this, callback); - } - - /** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - - /** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - - /** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {Promise} if no callback supplied - */ - forEach(iterator, callback) { - // Rewind cursor state - this.rewind(); - - // Set current cursor to INIT - this.s.state = CursorState.INIT; - - if (typeof callback === 'function') { - each(this, (err, doc) => { - if (err) { - callback(err); - return false; - } - if (doc != null) { - try { - iterator(doc); - } catch (error) { - callback(error); - return false; - } - return true; - } - if (doc == null && callback) { - const internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); - } else { - return new this.s.promiseLibrary((fulfill, reject) => { - each(this, (err, doc) => { - if (err) { - reject(err); - return false; - } else if (doc == null) { - fulfill(null); - return false; - } else { - try { - iterator(doc); - } catch (error) { - reject(error); - return false; - } - return true; - } - }); - }); - } - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - - /** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contains partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - toArray(callback) { - if (this.options.tailable) { - throw MongoError.create({ - message: 'Tailable cursor cannot be converted to array', - driver: true - }); - } - - return maybePromise(this, callback, cb => { - const cursor = this; - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return handleCallback(cb, err); - } - - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(cb, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - Array.prototype.push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); - }); - } - - /** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - - /** - * Get the count of documents for this cursor - * @method - * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options] Optional settings. - * @param {number} [options.skip] The number of documents to skip. - * @param {number} [options.limit] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - count(applySkipLimit, opts, callback) { - if (this.cmd.query == null) - throw MongoError.create({ - message: 'count can only be used with find command', - driver: true - }); - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - if (typeof applySkipLimit === 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if (this.cursorState.session) { - opts = Object.assign({}, opts, { session: this.cursorState.session }); - } - - const countOperation = new CountOperation(this, applySkipLimit, opts); - - return executeOperation(this.topology, countOperation, callback); - } - - /** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { skipKillCursors: false }, options); - - return maybePromise(this, callback, cb => { - this.s.state = CursorState.CLOSED; - if (!options.skipKillCursors) { - // Kill the cursor - this.kill(); - } - - this._endSession(() => { - this.emit('close'); - cb(null, this); - }); - }); - } - - /** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {Cursor} - */ - map(transform) { - if (this.cursorState.transforms && this.cursorState.transforms.doc) { - const oldTransform = this.cursorState.transforms.doc; - this.cursorState.transforms.doc = doc => { - return transform(oldTransform(doc)); - }; - } else { - this.cursorState.transforms = { doc: transform }; - } - - return this; - } - - /** - * Is the cursor closed - * @method - * @return {boolean} - */ - isClosed() { - return this.isDead(); - } - - destroy(err) { - if (err) this.emit('error', err); - this.pause(); - this.close(); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - * TODO: replace this method with transformStream in next major release - */ - stream(options) { - this.cursorState.streamOptions = options || {}; - return this; - } - - /** - * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, - * returns a stream of unmodified docs. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {stream} - */ - transformStream(options) { - const streamOptions = options || {}; - if (typeof streamOptions.transform === 'function') { - const stream = new Transform({ - objectMode: true, - transform: function(chunk, encoding, callback) { - this.push(streamOptions.transform(chunk)); - callback(); - } - }); - - return this.pipe(stream); - } - - return this.pipe(new PassThrough({ objectMode: true })); - } - - /** - * Execute the explain for the cursor - * - * For backwards compatibility, a verbosity of true is interpreted as "allPlansExecution" - * and false as "queryPlanner". Prior to server version 3.6, aggregate() - * ignores the verbosity parameter and executes in "queryPlanner". - * - * @method - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [verbosity=true] - An optional mode in which to run the explain. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - explain(verbosity, callback) { - if (typeof verbosity === 'function') (callback = verbosity), (verbosity = true); - if (verbosity === undefined) verbosity = true; - - if (!this.operation || !this.operation.hasAspect(Aspect.EXPLAINABLE)) { - throw new MongoError('This command cannot be explained'); - } - this.operation.explain = new Explain(verbosity); - - return maybePromise(this, callback, cb => { - CoreCursor.prototype._next.apply(this, [cb]); - }); - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// aliases -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -// deprecated methods -deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); -deprecate( - Cursor.prototype.maxScan, - 'Cursor.maxScan is deprecated, and will be removed in a later version' -); - -deprecate( - Cursor.prototype.snapshot, - 'Cursor Snapshot is deprecated, and will be removed in a later version' -); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -module.exports = Cursor; diff --git a/reverse_engineering/node_modules/mongodb/lib/db.js b/reverse_engineering/node_modules/mongodb/lib/db.js deleted file mode 100644 index 8ee070f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,1065 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const getSingleProperty = require('./utils').getSingleProperty; -const CommandCursor = require('./command_cursor'); -const handleCallback = require('./utils').handleCallback; -const filterOptions = require('./utils').filterOptions; -const toError = require('./utils').toError; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const ObjectID = require('./core').ObjectID; -const Logger = require('./core').Logger; -const Collection = require('./collection'); -const conditionallyMergeWriteConcern = require('./utils').conditionallyMergeWriteConcern; -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const ChangeStream = require('./change_stream'); -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const CONSTANTS = require('./constants'); -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const AggregationCursor = require('./aggregation_cursor'); - -// Operations -const createListener = require('./operations/db_ops').createListener; -const ensureIndex = require('./operations/db_ops').ensureIndex; -const evaluate = require('./operations/db_ops').evaluate; -const profilingInfo = require('./operations/db_ops').profilingInfo; -const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; - -const AggregateOperation = require('./operations/aggregate'); -const AddUserOperation = require('./operations/add_user'); -const CollectionsOperation = require('./operations/collections'); -const CommandOperation = require('./operations/command'); -const RunCommandOperation = require('./operations/run_command'); -const CreateCollectionOperation = require('./operations/create_collection'); -const CreateIndexesOperation = require('./operations/create_indexes'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation; -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const IndexInformationOperation = require('./operations/index_information'); -const ListCollectionsOperation = require('./operations/list_collections'); -const ProfilingLevelOperation = require('./operations/profiling_level'); -const RemoveUserOperation = require('./operations/remove_user'); -const RenameOperation = require('./operations/rename'); -const SetProfilingLevelOperation = require('./operations/set_profiling_level'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Select the database by name - * const testDb = client.db(dbName); - * client.close(); - * }); - */ - -// Allowed parameters -const legalOptionNames = [ - 'w', - 'wtimeout', - 'fsync', - 'j', - 'writeConcern', - 'readPreference', - 'readPreferenceTags', - 'native_parser', - 'forceServerObjectId', - 'pkFactory', - 'serializeFunctions', - 'raw', - 'bufferMaxEntries', - 'authSource', - 'ignoreUndefined', - 'promiseLibrary', - 'readConcern', - 'retryMiliSeconds', - 'numberOfRetries', - 'parentDb', - 'noListener', - 'loggerLevel', - 'logger', - 'promoteBuffers', - 'promoteLongs', - 'promoteValues', - 'bsonRegExp', - 'compression', - 'retryWrites' -]; - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options] Optional settings. - * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @property {object} topology Access the topology object (single server, replicaset or mongos). - * @fires Db#close - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -function Db(databaseName, topology, options) { - options = options || {}; - if (!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // Internal state of the db object - this.s = { - // DbCache - dbCache: {}, - // Children db's - children: [], - // Topology - topology: topology, - // Options - options: options, - // Logger instance - logger: Logger('Db', options), - // Get the bson parser - bson: topology ? topology.bson : null, - // Unpack read preference - readPreference: ReadPreference.fromOptions(options), - // Set buffermaxEntries - bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, - // Parent db (if chained) - parentDb: options.parentDb || null, - // Set up the primary key factory or fallback to ObjectID - pkFactory: options.pkFactory || ObjectID, - // Get native parser - nativeParser: options.nativeParser || options.native_parser, - // Promise library - promiseLibrary: promiseLibrary, - // No listener - noListener: typeof options.noListener === 'boolean' ? options.noListener : false, - // ReadConcern - readConcern: ReadConcern.fromOptions(options), - writeConcern: WriteConcern.fromOptions(options), - // Namespace - namespace: new MongoDBNamespace(databaseName) - }; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Add a read Only property - getSingleProperty(this, 'serverConfig', this.s.topology); - getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', this.s.namespace.db); - - // This is a child db, do not register any listeners - if (options.parentDb) return; - if (this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(this, 'error', this)); - topology.on('timeout', createListener(this, 'timeout', this)); - topology.on('close', createListener(this, 'close', this)); - topology.on('parseError', createListener(this, 'parseError', this)); - topology.once('open', createListener(this, 'open', this)); - topology.once('fullsetup', createListener(this, 'fullsetup', this)); - topology.once('all', createListener(this, 'all', this)); - topology.on('reconnect', createListener(this, 'reconnect', this)); -} - -inherits(Db, EventEmitter); - -Db.prototype.on = deprecate(function() { - return Db.super_.prototype.on.apply(this, arguments); -}, 'Listening to events on the Db class has been deprecated and will be removed in the next major version.'); - -Db.prototype.once = deprecate(function() { - return Db.super_.prototype.once.apply(this, arguments); -}, 'Listening to events on the Db class has been deprecated and will be removed in the next major version.'); - -// Topology -Object.defineProperty(Db.prototype, 'topology', { - enumerable: true, - get: function() { - return this.s.topology; - } -}); - -// Options -Object.defineProperty(Db.prototype, 'options', { - enumerable: true, - get: function() { - return this.s.options; - } -}); - -// slaveOk specified -Object.defineProperty(Db.prototype, 'slaveOk', { - enumerable: true, - get: function() { - if ( - this.s.options.readPreference != null && - (this.s.options.readPreference !== 'primary' || - this.s.options.readPreference.mode !== 'primary') - ) { - return true; - } - return false; - } -}); - -Object.defineProperty(Db.prototype, 'readConcern', { - enumerable: true, - get: function() { - return this.s.readConcern; - } -}); - -Object.defineProperty(Db.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - // TODO: check client - return ReadPreference.primary; - } - - return this.s.readPreference; - } -}); - -// get the write Concern -Object.defineProperty(Db.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(Db.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - const commandOperation = new RunCommandOperation(this, command, options); - - return executeOperation(this.s.topology, commandOperation, callback); -}; - -/** - * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Database~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Db.prototype.aggregate = function(pipeline, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - const Admin = require('./admin'); - - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * The callback format for an aggregation call - * @callback Database~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -const COLLECTION_OPTION_KEYS = [ - 'pkFactory', - 'readPreference', - 'serializeFunctions', - 'strict', - 'readConcern', - 'ignoreUndefined', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs', - 'bsonRegExp' -]; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you - * can use it without a callback in the following way: `const collection = db.collection('mycollection');` - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] **Deprecated** Returns an error if the collection does not exist - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} [callback] The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = deprecateOptions( - { - name: 'Db.collection', - deprecatedOptions: ['strict'], - optionsIndex: 1 - }, - function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options = Object.assign({}, options); - - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - - // Do we have ignoreUndefined set - if (this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - for (const collectionOptionKey of COLLECTION_OPTION_KEYS) { - if (!(collectionOptionKey in options) && this.s.options[collectionOptionKey] !== undefined) { - options[collectionOptionKey] = this.s.options[collectionOptionKey]; - } - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = conditionallyMergeWriteConcern(options, this.s.options); - - // Execute - if (options == null || !options.strict) { - try { - const collection = new Collection( - this, - this.s.topology, - this.databaseName, - name, - this.s.pkFactory, - options - ); - if (callback) callback(null, collection); - return collection; - } catch (err) { - if (err instanceof MongoError && callback) return callback(err); - throw err; - } - } - - // Strict mode - if (typeof callback !== 'function') { - throw toError(`A callback is required in strict mode. While getting collection ${name}`); - } - - // Did the user destroy the topology - if (this.serverConfig && this.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - - // Strict mode - this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length === 0) - return handleCallback( - callback, - toError(`Collection ${name} does not exist. Currently in strict mode.`), - null - ); - - try { - return handleCallback( - callback, - null, - new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err, null); - } - }); - } -); - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] DEPRECATED: Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 - * @param {number} [options.size] The size of the capped collection in bytes. - * @param {number} [options.max] The maximum number of documents in the capped collection. - * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. - * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. - * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. - * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. - * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. - * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. - * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. - * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = deprecateOptions( - { - name: 'Db.createCollection', - deprecatedOptions: ['autoIndexId', 'strict', 'w', 'wtimeout', 'j'], - optionsIndex: 1 - }, - function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - const createCollectionOperation = new CreateCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, createCollectionOperation, callback); - } -); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Build command object - const commandObject = { dbStats: true }; - // Check if we have the scale value - if (options['scale'] != null) commandObject['scale'] = options['scale']; - - // If we have a readPreference set - if (options.readPreference == null && this.s.readPreference) { - options.readPreference = this.s.readPreference; - } - - const statsOperation = new CommandOperation(this, options, null, commandObject); - - // Execute the command - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} [filter={}] Query to filter collections by - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - return new CommandCursor( - this.s.topology, - new ListCollectionsOperation(this, filter, options), - options - ); -}; - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = deprecate(function(code, parameters, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - return executeLegacyOperation(this.s.topology, evaluate, [ - this, - code, - parameters, - options, - callback - ]); -}, 'Db.eval is deprecated as of MongoDB version 3.2'); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Add return new collection - options.new_collection = true; - - const renameOperation = new RenameOperation( - this.collection(fromCollection), - toCollection, - options - ); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropDatabaseOperation = new DropDatabaseOperation(this, options); - - return executeOperation(this.s.topology, dropDatabaseOperation, callback); -}; - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const collectionsOperation = new CollectionsOperation(this, options); - - return executeOperation(this.s.topology, collectionsOperation, callback); -}; - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.readPreference = ReadPreference.resolve(this, options); - - const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( - this, - selector, - options - ); - - return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); -}; - -/** - * Creates an index on the db and collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - const createIndexesOperation = new CreateIndexesOperation(this, name, fieldOrSpec, options); - - return executeOperation(this.s.topology, createIndexesOperation, callback); -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - name, - fieldOrSpec, - options, - callback - ]); -}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); - -Db.prototype.addChild = function(db) { - if (this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - const addUserOperation = new AddUserOperation(this, username, password, options); - - return executeOperation(this.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const removeUserOperation = new RemoveUserOperation(this, username, options); - - return executeOperation(this.s.topology, removeUserOperation, callback); -}; - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.setProfilingLevel = function(level, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); - - return executeOperation(this.s.topology, setProfilingLevelOperation, callback); -}; - -/** - * Retrieve the current profiling information for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Query the system.profile collection directly. - */ -Db.prototype.profilingInfo = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); -}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.profilingLevel = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const profilingLevelOperation = new ProfilingLevelOperation(this, options); - - return executeOperation(this.s.topology, profilingLevelOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexInformationOperation = new IndexInformationOperation(this, name, options); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * Unref all sockets - * @method - * @deprecated This function is deprecated and will be removed in the next major version. - */ -Db.prototype.unref = function() { - this.s.topology.unref(); -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Db.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Db.prototype.getLogger = function() { - return this.s.logger; -}; - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; -Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; -Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; -Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; -Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; -Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; - -module.exports = Db; diff --git a/reverse_engineering/node_modules/mongodb/lib/dynamic_loaders.js b/reverse_engineering/node_modules/mongodb/lib/dynamic_loaders.js deleted file mode 100644 index c461002..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/dynamic_loaders.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -let collection; -let cursor; -let db; - -function loadCollection() { - if (!collection) { - collection = require('./collection'); - } - return collection; -} - -function loadCursor() { - if (!cursor) { - cursor = require('./cursor'); - } - return cursor; -} - -function loadDb() { - if (!db) { - db = require('./db'); - } - return db; -} - -module.exports = { - loadCollection, - loadCursor, - loadDb -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/encrypter.js b/reverse_engineering/node_modules/mongodb/lib/encrypter.js deleted file mode 100644 index ecf69ba..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/encrypter.js +++ /dev/null @@ -1,168 +0,0 @@ -'use strict'; -const MongoClient = require('./mongo_client'); -const BSON = require('./core/connection/utils').retrieveBSON(); -const MongoError = require('./core/error').MongoError; - -let mongodbClientEncryption = undefined; -try { - // Ensure you always wrap an optional require in the try block NODE-3199 - mongodbClientEncryption = require('mongodb-client-encryption'); -} catch (err) { - throw new MongoError( - 'Auto-encryption requested, but the module is not installed. ' + - 'Please add `mongodb-client-encryption` as a dependency of your project' - ); -} - -if ( - mongodbClientEncryption === undefined || - typeof mongodbClientEncryption.extension !== 'function' -) { - throw new MongoError( - 'loaded version of `mongodb-client-encryption` does not have property `extension`. ' + - 'Please make sure you are loading the correct version of `mongodb-client-encryption`' - ); -} - -const AutoEncrypter = mongodbClientEncryption.extension(require('../index')).AutoEncrypter; - -const kInternalClient = Symbol('internalClient'); - -class Encrypter { - /** - * @param {MongoClient} client - * @param {{autoEncryption: import('./mongo_client').AutoEncryptionOptions, bson: object}} options - */ - constructor(client, options) { - this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; - this.needsConnecting = false; - - if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { - options.autoEncryption.keyVaultClient = client; - } else if (options.autoEncryption.keyVaultClient == null) { - options.autoEncryption.keyVaultClient = this.getInternalClient(client); - } - - if (this.bypassAutoEncryption) { - options.autoEncryption.metadataClient = undefined; - } else if (options.maxPoolSize === 0) { - options.autoEncryption.metadataClient = client; - } else { - options.autoEncryption.metadataClient = this.getInternalClient(client); - } - - options.autoEncryption.bson = Encrypter.makeBSON(options); - - this.autoEncrypter = new AutoEncrypter(client, options.autoEncryption); - } - - getInternalClient(client) { - if (!this[kInternalClient]) { - const clonedOptions = {}; - - for (const key of Object.keys(client.s.options)) { - if ( - ['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].indexOf(key) !== - -1 - ) - continue; - clonedOptions[key] = client.s.options[key]; - } - - clonedOptions.minPoolSize = 0; - - const allEvents = [ - // APM - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // SDAM - 'serverOpening', - 'serverClosed', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - - // Legacy - 'joined', - 'left', - 'ping', - 'ha', - - // CMAP - 'connectionPoolCreated', - 'connectionPoolClosed', - 'connectionCreated', - 'connectionReady', - 'connectionClosed', - 'connectionCheckOutStarted', - 'connectionCheckOutFailed', - 'connectionCheckedOut', - 'connectionCheckedIn', - 'connectionPoolCleared' - ]; - - this[kInternalClient] = new MongoClient(client.s.url, clonedOptions); - - for (const eventName of allEvents) { - for (const listener of client.listeners(eventName)) { - this[kInternalClient].on(eventName, listener); - } - } - - client.on('newListener', (eventName, listener) => { - this[kInternalClient].on(eventName, listener); - }); - - this.needsConnecting = true; - } - return this[kInternalClient]; - } - - connectInternalClient(callback) { - if (this.needsConnecting) { - this.needsConnecting = false; - return this[kInternalClient].connect(callback); - } - - return callback(); - } - - close(client, force, callback) { - this.autoEncrypter.teardown(e => { - if (this[kInternalClient] && client !== this[kInternalClient]) { - return this[kInternalClient].close(force, callback); - } - callback(e); - }); - } - - static makeBSON(options) { - return ( - (options || {}).bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]) - ); - } -} - -module.exports = { Encrypter }; diff --git a/reverse_engineering/node_modules/mongodb/lib/error.js b/reverse_engineering/node_modules/mongodb/lib/error.js deleted file mode 100644 index 31b4ffd..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/error.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const MongoNetworkError = require('./core').MongoNetworkError; -const MONGODB_ERROR_CODES = require('./error_codes').MONGODB_ERROR_CODES; - -// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error -const GET_MORE_RESUMABLE_CODES = new Set([ - MONGODB_ERROR_CODES.HostUnreachable, - MONGODB_ERROR_CODES.HostNotFound, - MONGODB_ERROR_CODES.NetworkTimeout, - MONGODB_ERROR_CODES.ShutdownInProgress, - MONGODB_ERROR_CODES.PrimarySteppedDown, - MONGODB_ERROR_CODES.ExceededTimeLimit, - MONGODB_ERROR_CODES.SocketException, - MONGODB_ERROR_CODES.NotMaster, - MONGODB_ERROR_CODES.InterruptedAtShutdown, - MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, - MONGODB_ERROR_CODES.NotMasterNoSlaveOk, - MONGODB_ERROR_CODES.NotMasterOrSecondary, - MONGODB_ERROR_CODES.StaleShardVersion, - MONGODB_ERROR_CODES.StaleEpoch, - MONGODB_ERROR_CODES.StaleConfig, - MONGODB_ERROR_CODES.RetryChangeStream, - MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, - MONGODB_ERROR_CODES.CursorNotFound -]); - -function isResumableError(error, wireVersion) { - if (error instanceof MongoNetworkError) { - return true; - } - - if (wireVersion >= 9) { - // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable - if (error.code === MONGODB_ERROR_CODES.CursorNotFound) { - return true; - } - return error.hasErrorLabel('ResumableChangeStreamError'); - } - - return GET_MORE_RESUMABLE_CODES.has(error.code); -} - -module.exports = { GET_MORE_RESUMABLE_CODES, isResumableError, MONGODB_ERROR_CODES }; diff --git a/reverse_engineering/node_modules/mongodb/lib/error_codes.js b/reverse_engineering/node_modules/mongodb/lib/error_codes.js deleted file mode 100644 index 7f80000..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/error_codes.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -const MONGODB_ERROR_CODES = Object.freeze({ - HostUnreachable: 6, - HostNotFound: 7, - NetworkTimeout: 89, - ShutdownInProgress: 91, - PrimarySteppedDown: 189, - ExceededTimeLimit: 262, - SocketException: 9001, - NotMaster: 10107, - InterruptedAtShutdown: 11600, - InterruptedDueToReplStateChange: 11602, - NotMasterNoSlaveOk: 13435, - NotMasterOrSecondary: 13436, - StaleShardVersion: 63, - StaleEpoch: 150, - StaleConfig: 13388, - RetryChangeStream: 234, - FailedToSatisfyReadPreference: 133, - CursorNotFound: 43, - LegacyNotPrimary: 10058, - WriteConcernFailed: 64, - NamespaceNotFound: 26, - IllegalOperation: 20, - MaxTimeMSExpired: 50, - UnknownReplWriteConcern: 79, - UnsatisfiableWriteConcern: 100, - DuplicateKey: 11000, - CannotCreateIndex: 67, - IndexOptionsConflict: 85, - IndexKeySpecsConflict: 86, - InvalidIndexSpecificationOption: 197 -}); - -module.exports = Object.freeze({ MONGODB_ERROR_CODES }); diff --git a/reverse_engineering/node_modules/mongodb/lib/explain.js b/reverse_engineering/node_modules/mongodb/lib/explain.js deleted file mode 100644 index be8e95f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/explain.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const MongoError = require('./core/error').MongoError; - -/** - * @class - * @property {string} verbosity The verbosity mode for the explain output, e.g.: 'queryPlanner', 'queryPlannerExtended', 'executionStats', 'allPlansExecution'. - */ -class Explain { - /** - * Constructs an Explain from the explain verbosity. - * - * For backwards compatibility, true is interpreted as "allPlansExecution" - * and false as "queryPlanner". Prior to server version 3.6, aggregate() - * ignores the verbosity parameter and executes in "queryPlanner". - * - * @param {string|boolean} [verbosity] The verbosity mode for the explain output. - */ - constructor(verbosity) { - if (typeof verbosity === 'boolean') { - this.verbosity = verbosity ? 'allPlansExecution' : 'queryPlanner'; - } else { - this.verbosity = verbosity; - } - } - - /** - * Construct an Explain given an options object. - * - * @param {object} [options] The options object from which to extract the explain. - * @param {string|boolean} [options.explain] The verbosity mode for the explain output. - * @return {Explain} - */ - static fromOptions(options) { - if (options == null || options.explain === undefined) { - return; - } - - const explain = options.explain; - if (typeof explain === 'boolean' || typeof explain === 'string') { - return new Explain(options.explain); - } - - throw new MongoError(`explain must be a string or a boolean`); - } -} - -module.exports = { Explain }; diff --git a/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/download.js b/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/download.js deleted file mode 100644 index 0aab5dc..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/download.js +++ /dev/null @@ -1,433 +0,0 @@ -'use strict'; - -var stream = require('stream'), - util = require('util'); - -module.exports = GridFSBucketReadStream; - -/** - * A readable stream that enables you to read buffers from GridFS. - * - * Do not instantiate this class directly. Use `openDownloadStream()` instead. - * - * @class - * @extends external:Readable - * @param {Collection} chunks Handle for chunks collection - * @param {Collection} files Handle for files collection - * @param {Object} readPreference The read preference to use - * @param {Object} filter The query to use to find the file document - * @param {Object} [options] Optional settings. - * @param {Number} [options.sort] Optional sort for the file find query - * @param {Number} [options.skip] Optional skip for the file find query - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @fires GridFSBucketReadStream#error - * @fires GridFSBucketReadStream#file - */ -function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { - this.s = { - bytesRead: 0, - chunks: chunks, - cursor: null, - expected: 0, - files: files, - filter: filter, - init: false, - expectedEnd: 0, - file: null, - options: options, - readPreference: readPreference - }; - - stream.Readable.call(this); -} - -util.inherits(GridFSBucketReadStream, stream.Readable); - -/** - * An error occurred - * - * @event GridFSBucketReadStream#error - * @type {Error} - */ - -/** - * Fires when the stream loaded the file document corresponding to the - * provided id. - * - * @event GridFSBucketReadStream#file - * @type {object} - */ - -/** - * Emitted when a chunk of data is available to be consumed. - * - * @event GridFSBucketReadStream#data - * @type {object} - */ - -/** - * Fired when the stream is exhausted (no more data events). - * - * @event GridFSBucketReadStream#end - * @type {object} - */ - -/** - * Fired when the stream is exhausted and the underlying cursor is killed - * - * @event GridFSBucketReadStream#close - * @type {object} - */ - -/** - * Reads from the cursor and pushes to the stream. - * Private Impl, do not call directly - * @ignore - * @method - */ - -GridFSBucketReadStream.prototype._read = function() { - var _this = this; - if (this.destroyed) { - return; - } - - waitForFile(_this, function() { - doRead(_this); - }); -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} start Offset in bytes to start reading at - * @return {GridFSBucketReadStream} Reference to Self - */ - -GridFSBucketReadStream.prototype.start = function(start) { - throwIfInitialized(this); - this.s.options.start = start; - return this; -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} end Offset in bytes to stop reading at - * @return {GridFSBucketReadStream} Reference to self - */ - -GridFSBucketReadStream.prototype.end = function(end) { - throwIfInitialized(this); - this.s.options.end = end; - return this; -}; - -/** - * Marks this stream as aborted (will never push another `data` event) - * and kills the underlying cursor. Will emit the 'end' event, and then - * the 'close' event once the cursor is successfully killed. - * - * @method - * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. - * @fires GridFSBucketWriteStream#close - * @fires GridFSBucketWriteStream#end - */ - -GridFSBucketReadStream.prototype.abort = function(callback) { - var _this = this; - this.push(null); - this.destroyed = true; - if (this.s.cursor) { - this.s.cursor.close(function(error) { - _this.emit('close'); - callback && callback(error); - }); - } else { - if (!this.s.init) { - // If not initialized, fire close event because we will never - // get a cursor - _this.emit('close'); - } - callback && callback(); - } -}; - -/** - * @ignore - */ - -function throwIfInitialized(self) { - if (self.s.init) { - throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); - } -} - -/** - * @ignore - */ - -function doRead(_this) { - if (_this.destroyed) { - return; - } - - _this.s.cursor.next(function(error, doc) { - if (_this.destroyed) { - return; - } - if (error) { - return __handleError(_this, error); - } - if (!doc) { - _this.push(null); - - process.nextTick(() => { - _this.s.cursor.close(function(error) { - if (error) { - __handleError(_this, error); - return; - } - - _this.emit('close'); - }); - }); - - return; - } - - var bytesRemaining = _this.s.file.length - _this.s.bytesRead; - var expectedN = _this.s.expected++; - var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); - - if (doc.n > expectedN) { - var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.n < expectedN) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; - - if (buf.length !== expectedLength) { - if (bytesRemaining <= 0) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; - return __handleError(_this, new Error(errmsg)); - } - - errmsg = - 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; - return __handleError(_this, new Error(errmsg)); - } - - _this.s.bytesRead += buf.length; - - if (buf.length === 0) { - return _this.push(null); - } - - var sliceStart = null; - var sliceEnd = null; - - if (_this.s.bytesToSkip != null) { - sliceStart = _this.s.bytesToSkip; - _this.s.bytesToSkip = 0; - } - - const atEndOfStream = expectedN === _this.s.expectedEnd - 1; - const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; - if (atEndOfStream && _this.s.bytesToTrim != null) { - sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; - } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { - sliceEnd = bytesLeftToRead; - } - - if (sliceStart != null || sliceEnd != null) { - buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); - } - - _this.push(buf); - }); -} - -/** - * @ignore - */ - -function init(self) { - var findOneOptions = {}; - if (self.s.readPreference) { - findOneOptions.readPreference = self.s.readPreference; - } - if (self.s.options && self.s.options.sort) { - findOneOptions.sort = self.s.options.sort; - } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; - } - - self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { - if (error) { - return __handleError(self, error); - } - - if (!doc) { - var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; - var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; - var err = new Error(errmsg); - err.code = 'ENOENT'; - return __handleError(self, err); - } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; - } - - if (self.destroyed) { - // If user destroys the stream before we have a cursor, wait - // until the query is done to say we're 'closed' because we can't - // cancel a query. - self.emit('close'); - return; - } - - try { - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - } catch (error) { - return __handleError(self, error); - } - - var filter = { files_id: doc._id }; - - // Currently (MongoDB 3.4.4) skip function does not support the index, - // it needs to retrieve all the documents first and then skip them. (CS-25811) - // As work around we use $gte on the "n" field. - if (self.s.options && self.s.options.start != null) { - var skip = Math.floor(self.s.options.start / doc.chunkSize); - if (skip > 0) { - filter['n'] = { $gte: skip }; - } - } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); - } - - self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); - self.s.file = doc; - - try { - self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); - } catch (error) { - return __handleError(self, error); - } - - self.emit('file', doc); - }); -} - -/** - * @ignore - */ - -function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); - } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; - } - - _this.once('file', function() { - callback(); - }); -} - -/** - * @ignore - */ - -function handleStartOption(stream, doc, options) { - if (options && options.start != null) { - if (options.start > doc.length) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); - } - if (options.end != null && options.end < options.start) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'greater than stream end (' + - options.end + - ')' - ); - } - - stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; - stream.s.expected = Math.floor(options.start / doc.chunkSize); - - return options.start - stream.s.bytesRead; - } -} - -/** - * @ignore - */ - -function handleEndOption(stream, doc, cursor, options) { - if (options && options.end != null) { - if (options.end > doc.length) { - throw new Error( - 'Stream end (' + - options.end + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); - } - - var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; - - cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); - - stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); - - return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; - } -} - -/** - * @ignore - */ - -function __handleError(_this, error) { - _this.emit('error', error); -} diff --git a/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/index.js b/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/index.js deleted file mode 100644 index bf1f9dd..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/index.js +++ /dev/null @@ -1,374 +0,0 @@ -'use strict'; - -var Emitter = require('events').EventEmitter; -var GridFSBucketReadStream = require('./download'); -var GridFSBucketWriteStream = require('./upload'); -var shallowClone = require('../utils').shallowClone; -var toError = require('../utils').toError; -var util = require('util'); -var executeLegacyOperation = require('../utils').executeLegacyOperation; -const deprecateOptions = require('../utils').deprecateOptions; - -var DEFAULT_GRIDFS_BUCKET_OPTIONS = { - bucketName: 'fs', - chunkSizeBytes: 255 * 1024 -}; - -module.exports = GridFSBucket; - -/** - * Constructor for a streaming GridFS interface - * @class - * @extends external:EventEmitter - * @param {Db} db A db handle - * @param {object} [options] Optional settings. - * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. - * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB - * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` - * @param {object} [options.readPreference] Optional read preference to be passed to read operations - * @fires GridFSBucketWriteStream#index - */ - -function GridFSBucket(db, options) { - Emitter.apply(this); - this.setMaxListeners(0); - - if (options && typeof options === 'object') { - options = shallowClone(options); - var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); - for (var i = 0; i < keys.length; ++i) { - if (!options[keys[i]]) { - options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; - } - } - } else { - options = DEFAULT_GRIDFS_BUCKET_OPTIONS; - } - - this.s = { - db: db, - options: options, - _chunksCollection: db.collection(options.bucketName + '.chunks'), - _filesCollection: db.collection(options.bucketName + '.files'), - checkedIndexes: false, - calledOpenUploadStream: false, - promiseLibrary: db.s.promiseLibrary || Promise - }; -} - -util.inherits(GridFSBucket, Emitter); - -/** - * When the first call to openUploadStream is made, the upload stream will - * check to see if it needs to create the proper indexes on the chunks and - * files collections. This event is fired either when 1) it determines that - * no index creation is necessary, 2) when it successfully creates the - * necessary indexes. - * - * @event GridFSBucket#index - * @type {Error} - */ - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] **Deprecated** If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStream = deprecateOptions( - { - name: 'GridFSBucket.openUploadStream', - deprecatedOptions: ['disableMD5'], - optionsIndex: 1 - }, - function(filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - return new GridFSBucketWriteStream(this, filename, options); - } -); - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string|number|object} id A custom id used to identify the file - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] **Deprecated** If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStreamWithId = deprecateOptions( - { - name: 'GridFSBucket.openUploadStreamWithId', - deprecatedOptions: ['disableMD5'], - optionsIndex: 2 - }, - function(id, filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - - options.id = id; - - return new GridFSBucketWriteStream(this, filename, options); - } -); - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming file - * data from GridFS. - * @method - * @param {ObjectId} id The id of the file doc - * @param {Object} [options] Optional settings. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStream = function(id, options) { - var filter = { _id: id }; - options = { - start: options && options.start, - end: options && options.end - }; - - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Deletes a file with the given id - * @method - * @param {ObjectId} id The id of the file doc - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.delete = function(id, callback) { - return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _delete(_this, id, callback) { - _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { - if (error) { - return callback(error); - } - - _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { - if (error) { - return callback(error); - } - - // Delete orphaned chunks before returning FileNotFound - if (!res.result.n) { - var errmsg = 'FileNotFound: no file with id ' + id + ' found'; - return callback(new Error(errmsg)); - } - - callback(); - }); - }); -} - -/** - * Convenience wrapper around find on the files collection - * @method - * @param {Object} filter - * @param {Object} [options] Optional settings for cursor - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. - * @param {number} [options.limit] Optional limit for cursor - * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor - * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag - * @param {number} [options.skip] Optional skip for cursor - * @param {object} [options.sort] Optional sort for cursor - * @return {Cursor} - */ - -GridFSBucket.prototype.find = function(filter, options) { - filter = filter || {}; - options = options || {}; - - var cursor = this.s._filesCollection.find(filter); - - if (options.batchSize != null) { - cursor.batchSize(options.batchSize); - } - if (options.limit != null) { - cursor.limit(options.limit); - } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); - } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); - } - if (options.skip != null) { - cursor.skip(options.skip); - } - if (options.sort != null) { - cursor.sort(options.sort); - } - - return cursor; -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming the - * file with the given name from GridFS. If there are multiple files with - * the same name, this will stream the most recent file with the given name - * (as determined by the `uploadDate` field). You can set the `revision` - * option to change this behavior. - * @method - * @param {String} filename The name of the file to stream - * @param {Object} [options] Optional settings - * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { - var sort = { uploadDate: -1 }; - var skip = null; - if (options && options.revision != null) { - if (options.revision >= 0) { - sort = { uploadDate: 1 }; - skip = options.revision; - } else { - skip = -options.revision - 1; - } - } - - var filter = { filename: filename }; - options = { - sort: sort, - skip: skip, - start: options && options.start, - end: options && options.end - }; - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Renames the file with the given _id to the given string - * @method - * @param {ObjectId} id the id of the file to rename - * @param {String} filename new name for the file - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.rename = function(id, filename, callback) { - return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _rename(_this, id, filename, callback) { - var filter = { _id: id }; - var update = { $set: { filename: filename } }; - _this.s._filesCollection.updateOne(filter, update, function(error, res) { - if (error) { - return callback(error); - } - if (!res.result.n) { - return callback(toError('File with id ' + id + ' not found')); - } - callback(); - }); -} - -/** - * Removes this bucket's files collection, followed by its chunks collection. - * @method - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.drop = function(callback) { - return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { - skipSessions: true - }); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -GridFSBucket.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -/** - * @ignore - */ - -function _drop(_this, callback) { - _this.s._filesCollection.drop(function(error) { - if (error) { - return callback(error); - } - _this.s._chunksCollection.drop(function(error) { - if (error) { - return callback(error); - } - - return callback(); - }); - }); -} - -/** - * Callback format for all GridFSBucket methods that can accept a callback. - * @callback GridFSBucket~errorCallback - * @param {MongoError|undefined} error If present, an error instance representing any errors that occurred - * @param {*} result If present, a returned result for the method - */ diff --git a/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/upload.js b/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/upload.js deleted file mode 100644 index d988fdc..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/gridfs-stream/upload.js +++ /dev/null @@ -1,548 +0,0 @@ -'use strict'; - -const MONGODB_ERROR_CODES = require('../error_codes').MONGODB_ERROR_CODES; -const core = require('../core'); -const crypto = require('crypto'); -const stream = require('stream'); -const util = require('util'); -const Buffer = require('safe-buffer').Buffer; -const deprecateOptions = require('../utils').deprecateOptions; - -/** - * A writable stream that enables you to write buffers to GridFS. - * - * Do not instantiate this class directly. Use `openUploadStream()` instead. - * - * @class - * @extends external:Writable - * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {string|number|object} [options.id] Custom file id for the GridFS file. - * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @fires GridFSBucketWriteStream#error - * @fires GridFSBucketWriteStream#finish - */ - -const GridFSBucketWriteStream = deprecateOptions( - { - name: 'GridFSBucketWriteStream', - deprecatedOptions: ['disableMD5'], - optionsIndex: 2 - }, - function(bucket, filename, options) { - options = options || {}; - stream.Writable.call(this, options); - this.bucket = bucket; - this.chunks = bucket.s._chunksCollection; - this.filename = filename; - this.files = bucket.s._filesCollection; - this.options = options; - // Signals the write is all done - this.done = false; - - this.id = options.id ? options.id : core.BSON.ObjectId(); - this.chunkSizeBytes = this.options.chunkSizeBytes; - this.bufToStore = Buffer.alloc(this.chunkSizeBytes); - this.length = 0; - this.md5 = !options.disableMD5 && crypto.createHash('md5'); - this.n = 0; - this.pos = 0; - this.state = { - streamEnd: false, - outstandingRequests: 0, - errored: false, - aborted: false, - promiseLibrary: this.bucket.s.promiseLibrary - }; - - if (!this.bucket.s.calledOpenUploadStream) { - this.bucket.s.calledOpenUploadStream = true; - - var _this = this; - checkIndexes(this, function() { - _this.bucket.s.checkedIndexes = true; - _this.bucket.emit('index'); - }); - } - } -); - -util.inherits(GridFSBucketWriteStream, stream.Writable); - -/** - * An error occurred - * - * @event GridFSBucketWriteStream#error - * @type {Error} - */ - -/** - * `end()` was called and the write stream successfully wrote the file - * metadata and all the chunks to MongoDB. - * - * @event GridFSBucketWriteStream#finish - * @type {object} - */ - -/** - * Write a buffer to the stream. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {GridFSBucket~errorCallback} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. - * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. - */ - -GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { - var _this = this; - return waitForIndexes(this, function() { - return doWrite(_this, chunk, encoding, callback); - }); -}; - -/** - * Places this write stream into an aborted state (all future writes fail) - * and deletes all chunks that have already been written. - * - * @method - * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred - * @return {Promise} if no callback specified - */ - -GridFSBucketWriteStream.prototype.abort = function(callback) { - if (this.state.streamEnd) { - var error = new Error('Cannot abort a stream that has already completed'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - if (this.state.aborted) { - error = new Error('Cannot call abort() on a stream twice'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - this.state.aborted = true; - this.chunks.deleteMany({ files_id: this.id }, function(error) { - if (typeof callback === 'function') callback(error); - }); -}; - -/** - * Tells the stream that no more data will be coming in. The stream will - * persist the remaining data to MongoDB, write the files document, and - * then emit a 'finish' event. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {GridFSBucket~errorCallback} callback Function to call when all files and chunks have been persisted to MongoDB - */ - -GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { - var _this = this; - if (typeof chunk === 'function') { - (callback = chunk), (chunk = null), (encoding = null); - } else if (typeof encoding === 'function') { - (callback = encoding), (encoding = null); - } - - if (checkAborted(this, callback)) { - return; - } - this.state.streamEnd = true; - - if (callback) { - this.once('finish', function(result) { - callback(null, result); - }); - } - - if (!chunk) { - waitForIndexes(this, function() { - writeRemnant(_this); - }); - return; - } - - this.write(chunk, encoding, function() { - writeRemnant(_this); - }); -}; - -/** - * @ignore - */ - -function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; - } - _this.state.errored = true; - if (callback) { - return callback(error); - } - _this.emit('error', error); -} - -/** - * @ignore - */ - -function createChunkDoc(filesId, n, data) { - return { - _id: core.BSON.ObjectId(), - files_id: filesId, - n: n, - data: data - }; -} - -/** - * @ignore - */ - -function checkChunksIndex(_this, callback) { - _this.chunks.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { - var index = { files_id: 1, n: 1 }; - _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - return; - } - return callback(error); - } - - var hasChunksIndex = false; - indexes.forEach(function(index) { - if (index.key) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { - hasChunksIndex = true; - } - } - }); - - if (hasChunksIndex) { - callback(); - } else { - index = { files_id: 1, n: 1 }; - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - indexOptions.unique = true; - - _this.chunks.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - } - }); -} - -/** - * @ignore - */ - -function checkDone(_this, callback) { - if (_this.done) return true; - if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { - // Set done so we dont' trigger duplicate createFilesDoc - _this.done = true; - // Create a new files doc - var filesDoc = createFilesDoc( - _this.id, - _this.length, - _this.chunkSizeBytes, - _this.md5 && _this.md5.digest('hex'), - _this.filename, - _this.options.contentType, - _this.options.aliases, - _this.options.metadata - ); - - if (checkAborted(_this, callback)) { - return false; - } - - _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error, callback); - } - _this.emit('finish', filesDoc); - _this.emit('close'); - }); - - return true; - } - - return false; -} - -/** - * @ignore - */ - -function checkIndexes(_this, callback) { - _this.files.findOne({}, { _id: 1 }, function(error, doc) { - if (error) { - return callback(error); - } - if (doc) { - return callback(); - } - - _this.files.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { - var index = { filename: 1, uploadDate: 1 }; - _this.files.createIndex(index, { background: false }, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - return; - } - return callback(error); - } - - var hasFileIndex = false; - indexes.forEach(function(index) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { - hasFileIndex = true; - } - }); - - if (hasFileIndex) { - checkChunksIndex(_this, callback); - } else { - index = { filename: 1, uploadDate: 1 }; - - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - - _this.files.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - } - }); - }); -} - -/** - * @ignore - */ - -function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { - var ret = { - _id: _id, - length: length, - chunkSize: chunkSize, - uploadDate: new Date(), - filename: filename - }; - - if (md5) { - ret.md5 = md5; - } - - if (contentType) { - ret.contentType = contentType; - } - - if (aliases) { - ret.aliases = aliases; - } - - if (metadata) { - ret.metadata = metadata; - } - - return ret; -} - -/** - * @ignore - */ - -function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; - } - - var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); - - _this.length += inputBuf.length; - - // Input is small enough to fit in our buffer - if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { - inputBuf.copy(_this.bufToStore, _this.pos); - _this.pos += inputBuf.length; - - callback && callback(); - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // True means client can keep writing. - return true; - } - - // Otherwise, buffer is too big for current chunk, so we need to flush - // to MongoDB. - var inputBufRemaining = inputBuf.length; - var spaceRemaining = _this.chunkSizeBytes - _this.pos; - var numToCopy = Math.min(spaceRemaining, inputBuf.length); - var outstandingRequests = 0; - while (inputBufRemaining > 0) { - var inputBufPos = inputBuf.length - inputBufRemaining; - inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); - _this.pos += numToCopy; - spaceRemaining -= numToCopy; - if (spaceRemaining === 0) { - if (_this.md5) { - _this.md5.update(_this.bufToStore); - } - var doc = createChunkDoc(_this.id, _this.n, Buffer.from(_this.bufToStore)); - ++_this.state.outstandingRequests; - ++outstandingRequests; - - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - --outstandingRequests; - - if (!outstandingRequests) { - _this.emit('drain', doc); - callback && callback(); - checkDone(_this); - } - }); - - spaceRemaining = _this.chunkSizeBytes; - _this.pos = 0; - ++_this.n; - } - inputBufRemaining -= numToCopy; - numToCopy = Math.min(spaceRemaining, inputBufRemaining); - } - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // False means the client should wait for the 'drain' event. - return false; -} - -/** - * @ignore - */ - -function getWriteOptions(_this) { - var obj = {}; - if (_this.options.writeConcern) { - obj.w = _this.options.writeConcern.w; - obj.wtimeout = _this.options.writeConcern.wtimeout; - obj.j = _this.options.writeConcern.j; - } - return obj; -} - -/** - * @ignore - */ - -function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); - } - - _this.bucket.once('index', function() { - callback(true); - }); - - return true; -} - -/** - * @ignore - */ - -function writeRemnant(_this, callback) { - // Buffer is empty, so don't bother to insert - if (_this.pos === 0) { - return checkDone(_this, callback); - } - - ++_this.state.outstandingRequests; - - // Create a new buffer to make sure the buffer isn't bigger than it needs - // to be. - var remnant = Buffer.alloc(_this.pos); - _this.bufToStore.copy(remnant, 0, 0, _this.pos); - if (_this.md5) { - _this.md5.update(remnant); - } - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); - }); -} - -/** - * @ignore - */ - -function checkAborted(_this, callback) { - if (_this.state.aborted) { - if (typeof callback === 'function') { - callback(new Error('this stream has been aborted')); - } - return true; - } - return false; -} - -module.exports = GridFSBucketWriteStream; diff --git a/reverse_engineering/node_modules/mongodb/lib/gridfs/chunk.js b/reverse_engineering/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index d276d72..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; - -var Binary = require('../core').BSON.Binary, - ObjectID = require('../core').BSON.ObjectID; - -var Buffer = require('safe-buffer').Buffer; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || { w: 1 }; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if (typeof mongoObjectFinal.data === 'string') { - var buffer = Buffer.alloc(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if (Array.isArray(mongoObjectFinal.data)) { - buffer = Buffer.alloc(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { - throw Error('Illegal chunk format'); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if (callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length === 0 ? this.length() : length; - - if (this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if (this.length() - this.internalPosition >= length) { - var data = null; - if (this.data.buffer != null) { - //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { - //Native BSON - data = Buffer.alloc(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition === this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if (typeof options === 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if (err) return callback(err); - - // Merge the options - var writeOptions = { upsert: true }; - for (var name in options) writeOptions[name] = options[name]; - for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - if (self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = { forceServerObjectId: true }; - for (var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - // }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

- *        {
- *          '_id' : , // {number} id for this chunk
- *          'files_id' : , // {number} foreign key to the file collection
- *          'n' : , // {number} chunk number
- *          'data' : , // {bson#Binary} the chunk data itself
- *        }
- *        
- * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - files_id: this.file.fileId, - n: this.chunkNumber, - data: this.data - }; - // If we are saving using a specific ObjectId - if (this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, 'position', { - enumerable: true, - get: function() { - return this.internalPosition; - }, - set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; - -module.exports = Chunk; diff --git a/reverse_engineering/node_modules/mongodb/lib/gridfs/grid_store.js b/reverse_engineering/node_modules/mongodb/lib/gridfs/grid_store.js deleted file mode 100644 index 4f229a0..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/gridfs/grid_store.js +++ /dev/null @@ -1,1925 +0,0 @@ -'use strict'; - -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * const GridStore = require('mongodb').GridStore; - * const ObjectID = require('mongodb').ObjectID; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * const gridStore = new GridStore(db, null, "w"); - * gridStore.open(function(err, gridStore) { - * gridStore.write("hello world!", function(err, gridStore) { - * gridStore.close(function(err, result) { - * // Let's read the file using object Id - * GridStore.read(db, result._id, function(err, data) { - * test.equal('hello world!', data); - * client.close(); - * test.done(); - * }); - * }); - * }); - * }); - * }); - */ -const Chunk = require('./chunk'); -const ObjectID = require('../core').BSON.ObjectID; -const ReadPreference = require('../core').ReadPreference; -const Buffer = require('safe-buffer').Buffer; -const fs = require('fs'); -const f = require('util').format; -const util = require('util'); -const MongoError = require('../core').MongoError; -const inherits = util.inherits; -const Duplex = require('stream').Duplex; -const shallowClone = require('../utils').shallowClone; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const deprecate = require('util').deprecate; - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -const deprecationFn = deprecate(() => {}, -'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); - -/** - * Namespace provided by the core module - * @external Duplex - */ - -/** - * Create a new GridStore instance - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwritten. - * - * @class - * @param {Db} db A database instance to interact with. - * @param {object} [id] optional unique id for this file - * @param {string} [filename] optional filename for this file, no unique constrain on the field - * @param {string} mode set the mode for this file. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * @param {object} [options.metadata] Arbitrary data the user wants to store. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @property {number} chunkSize Get the gridstore chunk size. - * @property {number} md5 The md5 checksum for this file. - * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory - * @return {GridStore} a GridStore instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - deprecationFn(); - if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - this.db = db; - - // Handle options - if (typeof options === 'undefined') options = {}; - // Handle mode - if (typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if (typeof mode === 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if (id && id._bsontype === 'ObjectID') { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if (typeof filename === 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? 'r' : mode; - this.options = options || {}; - - // Opened - this.isOpen = false; - - // Set the root if overridden - this.root = - this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = - this.options.readPreference || db.options.readPreference || ReadPreference.primary; - this.writeConcern = _getWriteConcern(db, this.options); - // Set default chunk size - this.internalChunkSize = - this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; - - // Get the promiseLibrary - var promiseLibrary = this.options.promiseLibrary || Promise; - - // Set the promiseLibrary - this.promiseLibrary = promiseLibrary; - - Object.defineProperty(this, 'chunkSize', { - enumerable: true, - get: function() { - return this.internalChunkSize; - }, - set: function(value) { - if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { - // eslint-disable-next-line no-self-assign - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } - }); - - Object.defineProperty(this, 'md5', { - enumerable: true, - get: function() { - return this.internalMd5; - } - }); - - Object.defineProperty(this, 'chunkNumber', { - enumerable: true, - get: function() { - return this.currentChunk && this.currentChunk.chunkNumber - ? this.currentChunk.chunkNumber - : null; - } - }); -}; - -/** - * The callback format for the Gridstore.open method - * @callback GridStore~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The GridStore instance if the open method was successful. - */ - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~openCallback} [callback] this will be called after executing this method - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.open = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { - throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); - } - - return executeLegacyOperation(this.db.s.topology, open, [this, options, callback], { - skipSessions: true - }); -}; - -var open = function(self, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(self.db, self.options); - - // If we are writing we need to ensure we have the right indexes for md5's - if (self.mode === 'w' || self.mode === 'w+') { - // Get files collection - var collection = self.collection(); - // Put index on filename - collection.ensureIndex([['filename', 1]], writeConcern, function() { - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Make an unique index for compatibility with mongo-cxx-driver:legacy - var chunkIndexOptions = shallowClone(writeConcern); - chunkIndexOptions.unique = true; - // Ensure index on chunk collection - chunkCollection.ensureIndex( - [ - ['files_id', 1], - ['n', 1] - ], - chunkIndexOptions, - function() { - // Open the connection - _open(self, writeConcern, function(err, r) { - if (err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - } - ); - }); - } else { - // Open the gridstore - _open(self, writeConcern, function(err, r) { - if (err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - } -}; - -/** - * Verify if the file is at EOF. - * - * @method - * @return {boolean} true if the read/write head is at the end of this file. - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.eof = function() { - return this.position === this.length ? true : false; -}; - -/** - * The callback result format. - * @callback GridStore~resultCallback - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result from the callback. - */ - -/** - * Retrieves a single character from this file. - * - * @method - * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.getc = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, getc, [this, options, callback], { - skipSessions: true - }); -}; - -var getc = function(self, options, callback) { - if (self.eof()) { - callback(null, null); - } else if (self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -}; - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @method - * @param {string} string the string to write. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.puts = function(string, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - var finalString = string.match(/\n$/) == null ? string + '\n' : string; - return executeLegacyOperation( - this.db.s.topology, - this.write.bind(this), - [finalString, options, callback], - { skipSessions: true } - ); -}; - -/** - * Return a modified Readable stream including a possible transform method. - * - * @method - * @return {GridStoreStream} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.stream = function() { - return new GridStoreStream(this); -}; - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @method - * @param {(string|Buffer)} data the data to write. - * @param {boolean} [close] closes this file after writing if set to true. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.write = function write(data, close, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation( - this.db.s.topology, - _writeNormal, - [this, data, close, options, callback], - { skipSessions: true } - ); -}; - -/** - * Handles the destroy part of a stream - * - * @method - * @result {null} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if (!this.writable) return; - this.readable = false; - if (this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -}; - -/** - * Stores a file from the file system to the GridFS database. - * - * @method - * @param {(string|Buffer|FileHandle)} file the file to store. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.writeFile = function(file, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, writeFile, [this, file, options, callback], { - skipSessions: true - }); -}; - -var writeFile = function(self, file, options, callback) { - if (typeof file === 'string') { - fs.open(file, 'r', function(err, fd) { - if (err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function(err, self) { - if (err) return callback(err, self); - - fs.fstat(file, function(err, stats) { - if (err) return callback(err, self); - - var offset = 0; - var index = 0; - - // Write a chunk - var writeChunk = function() { - // Allocate the buffer - var _buffer = Buffer.alloc(self.chunkSize); - // Read the file - fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { - if (err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, { n: index++ }, self.writeConcern); - chunk.write(data.slice(0, bytesRead), function(err, chunk) { - if (err) return callback(err, self); - - chunk.save({}, function(err) { - if (err) return callback(err, self); - - self.position = self.position + bytesRead; - - // Point to current chunk - self.currentChunk = chunk; - - if (offset >= stats.size) { - fs.close(file, function(err) { - if (err) return callback(err); - - self.close(function(err) { - if (err) return callback(err, self); - return callback(null, self); - }); - }); - } else { - return process.nextTick(writeChunk); - } - }); - }); - }); - }; - - // Process the first write - process.nextTick(writeChunk); - }); - }); -}; - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.close = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, close, [this, options, callback], { - skipSessions: true - }); -}; - -var close = function(self, options, callback) { - if (self.mode[0] === 'w') { - // Set up options - options = Object.assign({}, self.writeConcern, options); - - if (self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err) { - if (err && typeof callback === 'function') return callback(err); - - self.collection(function(err, files) { - if (err && typeof callback === 'function') return callback(err); - - // Build the mongo object - if (self.uploadDate != null) { - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if (err && typeof callback === 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - }); - } - } else if (self.mode[0] === 'r') { - if (typeof callback === 'function') callback(null, null); - } else { - if (typeof callback === 'function') - callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); - } -}; - -/** - * The collection callback format. - * @callback GridStore~collectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection from the command execution. - */ - -/** - * Retrieve this file's chunks collection. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.chunkCollection = function(callback) { - if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); - return this.db.collection(this.root + '.chunks'); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.unlink = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, unlink, [this, options, callback], { - skipSessions: true - }); -}; - -var unlink = function(self, options, callback) { - deleteChunks(self, function(err) { - if (err !== null) { - err.message = 'at deleteChunks: ' + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if (err !== null) { - err.message = 'at collection: ' + err.message; - return callback(err); - } - - collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { - callback(err, self); - }); - }); - }); -}; - -/** - * Retrieves the file collection associated with this object. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.collection = function(callback) { - if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); - return this.db.collection(this.root + '.files'); -}; - -/** - * The readlines callback format. - * @callback GridStore~readlinesCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {string[]} strings The array of strings returned. - */ - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.readlines = function(separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : '\n'; - separator = separator || '\n'; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - readlines, - [this, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlines = function(self, separator, options, callback) { - self.read(function(err, data) { - if (err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for (var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -}; - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.rewind = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, rewind, [this, options, callback], { - skipSessions: true - }); -}; - -var rewind = function(self, options, callback) { - if (self.currentChunk.chunkNumber !== 0) { - if (self.mode[0] === 'w') { - deleteChunks(self, function(err) { - if (err) return callback(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if (err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -}; - -/** - * The read callback format. - * @callback GridStore~readCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Buffer} data The data read from the GridStore object - */ - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.read = function(length, buffer, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - read, - [this, length, buffer, options, callback], - { skipSessions: true } - ); -}; - -var read = function(self, length, buffer, options, callback) { - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if (finalLength === 0 && finalBuffer.length === 0) - return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); - // Else return data - return callback(null, finalBuffer); - } - - // Read the next chunk - slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if (err) return callback(err); - - if (chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if (finalBuffer._index > 0) { - callback(null, finalBuffer); - } else { - callback( - MongoError.create({ - message: 'no chunks found for file, possibly corrupt', - driver: true - }), - null - ); - } - } - }); -}; - -/** - * The tell callback format. - * @callback GridStore~tellCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} position The current read position in the GridStore. - */ - -/** - * Retrieves the position of the read/write head of this file. - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~tellCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.tell = function(callback) { - var self = this; - // We provided a callback leg - if (typeof callback === 'function') return callback(null, this.position); - // Return promise - return new self.promiseLibrary(function(resolve) { - resolve(self.position); - }); -}; - -/** - * The tell callback format. - * @callback GridStore~gridStoreCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The gridStore. - */ - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @method - * @param {number} [position] the position to seek to - * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~gridStoreCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.seek = function(position, seekLocation, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - seekLocation = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - seek, - [this, position, seekLocation, options, callback], - { skipSessions: true } - ); -}; - -var seek = function(self, position, seekLocation, options, callback) { - // Seek only supports read mode - if (self.mode !== 'r') { - return callback( - MongoError.create({ message: 'seek is only supported for mode r', driver: true }) - ); - } - - var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if (seekLocationFinal === GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if (seekLocationFinal === GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition / self.chunkSize); - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - if (err) return callback(err, null); - if (chunk == null) return callback(new Error('no chunk found')); - - // Set the current chunk - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = self.position % self.chunkSize; - callback(err, self); - }); - }; - - seekChunk(); -}; - -/** - * @ignore - */ -var _open = function(self, options, callback) { - var collection = self.collection(); - // Create the query - var query = - self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; - query = null == self.fileId && self.filename == null ? null : query; - options.readPreference = self.readPreference; - - // Fetch the chunks - if (query != null) { - collection.findOne(query, options, function(err, doc) { - if (err) { - return error(err); - } - - // Check if the collection for the files exists otherwise prepare the new one - if (doc != null) { - self.fileId = doc._id; - // Prefer a new filename over the existing one if this is a write - self.filename = - self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode !== 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = - self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; - return error( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename - ), - driver: true - }), - self - ); - } - - // Process the mode of the object - if (self.mode === 'r') { - nthChunk(self, 0, options, function(err, chunk) { - if (err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w' && doc) { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if (err) return error(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null - ? self.internalChunkSize - : self.options['chunk_size']; - self.metadata = - self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w') { - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - } else if (self.mode === 'w+') { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if (err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = - self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = - self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - // No file exists set up write mode - if (self.mode === 'w') { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if (err) return error(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w+') { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if (err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - } - - // only pass error to callback once - function error(err) { - if (error.err) return; - callback((error.err = err)); - } -}; - -/** - * @ignore - */ -var writeBuffer = function(self, buffer, close, callback) { - if (typeof close === 'function') { - callback = close; - close = null; - } - var finalClose = typeof close === 'boolean' ? close : false; - - if (self.mode !== 'w') { - callback( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename - ), - driver: true - }), - null - ); - } else { - if (self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while (leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); - firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); - // If we have left over data write it - if (leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - - for (var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function(err) { - if (err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if (numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if (finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - - // Return normally - return callback(null, self); - } - }); - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - // We care closing the file before returning - if (finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - *

- *        {
- *          '_id' : , // {number} id for this file
- *          'filename' : , // {string} name for this file
- *          'contentType' : , // {string} mime type for this file
- *          'length' : , // {number} size of this file?
- *          'chunksize' : , // {number} chunk size used by this file
- *          'uploadDate' : , // {Date}
- *          'aliases' : , // {array of string}
- *          'metadata' : , // {string}
- *        }
- *        
- * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - _id: self.fileId, - filename: self.filename, - contentType: self.contentType, - length: self.position ? self.position : 0, - chunkSize: self.chunkSize, - uploadDate: self.uploadDate, - aliases: self.aliases, - metadata: self.metadata - }; - - var md5Command = { filemd5: self.fileId, root: self.root }; - self.db.command(md5Command, function(err, results) { - if (err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self - .chunkCollection() - .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { - if (err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if (self.fileId != null) { - self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { - if (err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** - * The collection to be used for holding the files and chunks collection. - * - * @classconstant DEFAULT_ROOT_COLLECTION - */ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** - * Default file mime type - * - * @classconstant DEFAULT_CONTENT_TYPE - */ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** - * Seek mode where the given length is absolute. - * - * @classconstant IO_SEEK_SET - */ -GridStore.IO_SEEK_SET = 0; - -/** - * Seek mode where the given length is an offset to the current read/write head. - * - * @classconstant IO_SEEK_CUR - */ -GridStore.IO_SEEK_CUR = 1; - -/** - * Seek mode where the given length is an offset to the end of the file. - * - * @classconstant IO_SEEK_END - */ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - exists, - [db, fileIdObject, rootCollection, options, callback], - { skipSessions: true } - ); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - // Build query - var query = - typeof fileIdObject === 'string' || - Object.prototype.toString.call(fileIdObject) === '[object RegExp]' - ? { filename: fileIdObject } - : { _id: fileIdObject }; // Attempt to locate file - - // We have a specific query - if ( - fileIdObject != null && - typeof fileIdObject === 'object' && - Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' - ) { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, { readPreference: readPreference }, function(err, item) { - if (err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { - skipSessions: true - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if (rootCollection != null && typeof rootCollection === 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.primary; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - collection.find({}, { readPreference: readPreference }, function(err, cursor) { - if (err) return callback(err); - - cursor.each(function(err, item) { - if (item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readStatic, - [db, name, length, offset, options, callback], - { skipSessions: true } - ); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - // Make sure we are not reading out of bounds - if (offset && offset >= gridStore.length) - return callback('offset larger than size of file', null); - if (length && length > gridStore.length) - return callback('length is larger than the size of the file', null); - if (offset && length && offset + length > gridStore.length) - return callback('offset and length is larger than the size of the file', null); - - if (offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if (err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readlinesStatic, - [db, name, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? '\n' : separator; - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options] Optional settings. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.unlink = function(db, names, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { - skipSessions: true - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if (names.constructor === Array) { - var tc = 0; - for (var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function() { - if (--tc === 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, 'w', options).open(function(err, gridStore) { - if (err) return callback(err); - deleteChunks(gridStore, function(err) { - if (err) return callback(err); - gridStore.collection(function(err, collection) { - if (err) return callback(err); - collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, options, callback) { - // If we have a buffer write it using the writeBuffer method - if (Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); - } -}; - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - const baseOptions = Object.assign(options, options.writeConcern); - var finalOptions = {}; - if (baseOptions.w != null) finalOptions.w = baseOptions.w; - if (baseOptions.journal === true) finalOptions.j = baseOptions.journal; - if (baseOptions.j === true) finalOptions.j = baseOptions.j; - if (baseOptions.fsync === true) finalOptions.fsync = baseOptions.fsync; - if (baseOptions.wtimeout != null) finalOptions.wtimeout = baseOptions.wtimeout; - return finalOptions; -}; - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = { w: 1 }; - options = options || {}; - - // Local options verification - if ( - options.writeConcern != null || - options.w != null || - typeof options.j === 'boolean' || - typeof options.journal === 'boolean' || - typeof options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(options); - } else if (options.safe != null && typeof options.safe === 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if (typeof options.safe === 'boolean') { - finalOptions = { w: options.safe ? 1 : 0 }; - } else if ( - self.options.writeConcern != null || - self.options.w != null || - typeof self.options.j === 'boolean' || - typeof self.options.journal === 'boolean' || - typeof self.options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(self.options); - } else if ( - self.safe && - (self.safe.w != null || - typeof self.safe.j === 'boolean' || - typeof self.safe.journal === 'boolean' || - typeof self.safe.fsync === 'boolean') - ) { - finalOptions = _setWriteConcernHash(self.safe); - } else if (typeof self.safe === 'boolean') { - finalOptions = { w: self.safe ? 1 : 0 }; - } - - // Ensure we don't have an invalid combination of write concerns - if ( - finalOptions.w < 1 && - (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) - ) - throw MongoError.create({ - message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', - driver: true - }); - - // Return the options - return finalOptions; -}; - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStoreStream = function(gs) { - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -}; - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if (!self.gs.isOpen) { - self.gs.open(function(err) { - if (err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } - - return destination; -}; - -// Called by stream -GridStoreStream.prototype._read = function() { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if (err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if (self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if (buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if (buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if (self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - }; - - // Set read length - var length = - self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if (!self.gs.isOpen) { - self.gs.open(function(err) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if (err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -}; - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -}; - -GridStoreStream.prototype.write = function(chunk) { - var self = this; - if (self.endCalled) - return self.emit( - 'error', - MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) - ); - // Do we have to open the gridstore - if (!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -}; - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if (chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); - }); - } - - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); -}; - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/reverse_engineering/node_modules/mongodb/lib/mongo_client.js b/reverse_engineering/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index e9cbbe7..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,522 +0,0 @@ -'use strict'; - -const ChangeStream = require('./change_stream'); -const Db = require('./db'); -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const MongoError = require('./core').MongoError; -const ValidServerApiVersions = require('./core').ValidServerApiVersions; -const deprecate = require('util').deprecate; -const WriteConcern = require('./write_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const ReadPreference = require('./core/topologies/read_preference'); -const maybePromise = require('./utils').maybePromise; -const NativeTopology = require('./topologies/native_topology'); -const connect = require('./operations/connect').connect; -const validOptions = require('./operations/connect').validOptions; - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * // Connect using a MongoClient instance - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * const mongoClient = new MongoClient(url); - * mongoClient.connect(function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - * - * @example - * // Connect using the MongoClient.connect static method - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - */ - -/** - * A string specifying the level of a ReadConcern - * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels - */ - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} DriverInfoOptions - * @property {string} [name] The name of the driver - * @property {string} [version] The version of the driver - * @property {string} [platform] Optional platform information - */ - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} DriverInfoOptions - * @property {string} [name] The name of the driver - * @property {string} [version] The version of the driver - * @property {string} [platform] Optional platform information - */ - -/** - * @public - * @typedef AutoEncryptionOptions - * @property {MongoClient} [keyVaultClient] A `MongoClient` used to fetch keys from a key vault - * @property {string} [keyVaultNamespace] The namespace where keys are stored in the key vault - * @property {object} [kmsProviders] Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. - * @property {object} [schemaMap] A map of namespaces to a local JSON schema for encryption - * - * > **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. - * > It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. - * > Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. - * > Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. - * - * @property {object} [options] An optional hook to catch logging messages from the underlying encryption engine - * @property {object} [extraOptions] - * @property {boolean} [bypassAutoEncryption] - */ - -/** - * @typedef {object} MongoClientOptions - * @property {number} [poolSize] (**default**: 5) The maximum size of the individual server pool - * @property {boolean} [ssl] (**default**: false) Enable SSL connection. *deprecated* use `tls` variants - * @property {boolean} [sslValidate] (**default**: false) Validate mongod server certificate against Certificate Authority - * @property {buffer} [sslCA] (**default**: undefined) SSL Certificate store binary buffer *deprecated* use `tls` variants - * @property {buffer} [sslCert] (**default**: undefined) SSL Certificate binary buffer *deprecated* use `tls` variants - * @property {buffer} [sslKey] (**default**: undefined) SSL Key file binary buffer *deprecated* use `tls` variants - * @property {string} [sslPass] (**default**: undefined) SSL Certificate pass phrase *deprecated* use `tls` variants - * @property {buffer} [sslCRL] (**default**: undefined) SSL Certificate revocation list binary buffer *deprecated* use `tls` variants - * @property {boolean|function} [checkServerIdentity] (**default**: true) Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants - * @property {boolean} [tls] (**default**: false) Enable TLS connections - * @property {boolean} [tlsInsecure] (**default**: false) Relax TLS constraints, disabling validation - * @property {string} [tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection - * @property {string} [tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated - * @property {string} [tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections - * @property {boolean} [tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid - * @property {boolean} [tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate - * @property {boolean} [autoReconnect] (**default**: true) Enable autoReconnect for single server instances - * @property {boolean} [noDelay] (**default**: true) TCP Connection no delay - * @property {boolean} [keepAlive] (**default**: true) TCP Connection keep alive enabled - * @property {number} [keepAliveInitialDelay] (**default**: 120000) The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @property {number} [connectTimeoutMS] (**default**: 10000) How long to wait for a connection to be established before timing out - * @property {number} [socketTimeoutMS] (**default**: 0) How long a send or receive on a socket can take before timing out - * @property {number} [family] Version of IP stack. Can be 4, 6 or null (default). If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @property {number} [reconnectTries] (**default**: 30) Server attempt to reconnect #times - * @property {number} [reconnectInterval] (**default**: 1000) Server will wait # milliseconds between retries - * @property {boolean} [ha] (**default**: true) Control if high availability monitoring runs for Replicaset or Mongos proxies - * @property {number} [haInterval] (**default**: 10000) The High availability period for replicaset inquiry - * @property {string} [replicaSet] (**default**: undefined) The Replicaset set name - * @property {number} [secondaryAcceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Replicaset member selection - * @property {number} [acceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Mongos proxies selection - * @property {boolean} [connectWithNoPrimary] (**default**: false) Sets if the driver should connect even if no primary is available - * @property {string} [authSource] (**default**: undefined) Define the database to authenticate against - * @property {(number|string)} [w] **Deprecated** The write concern. Use writeConcern instead. - * @property {number} [wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @property {boolean} [j] (**default**: false) **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @property {boolean} [fsync] (**default**: false) **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @property {object|WriteConcern} [writeConcern] Specify write concern settings. - * @property {boolean} [forceServerObjectId] (**default**: false) Force server to assign _id values instead of driver - * @property {boolean} [serializeFunctions] (**default**: false) Serialize functions on any object - * @property {Boolean} [ignoreUndefined] (**default**: false) Specify if the BSON serializer should ignore undefined fields - * @property {boolean} [raw] (**default**: false) Return document results as raw BSON buffers - * @property {number} [bufferMaxEntries] (**default**: -1) Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @property {(ReadPreference|string)} [readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @property {object} [pkFactory] A primary key factory object for generation of custom _id keys - * @property {object} [promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @property {object} [readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @property {ReadConcernLevel} [readConcern.level] (**default**: {Level: 'local'}) Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @property {number} [maxStalenessSeconds] (**default**: undefined) The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @property {string} [loggerLevel] (**default**: undefined) The logging level (error/warn/info/debug) - * @property {object} [logger] (**default**: undefined) Custom logger object - * @property {boolean} [promoteValues] (**default**: true) Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @property {boolean} [promoteBuffers] (**default**: false) Promotes Binary BSON values to native Node Buffers - * @property {boolean} [promoteLongs] (**default**: true) Promotes long values to number if they fit inside the 53 bits resolution - * * @param {boolean} [bsonRegExp] (**default**: false) By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @property {boolean} [domainsEnabled] (**default**: false) Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @property {object} [validateOptions] (**default**: false) Validate MongoClient passed in options for correctness - * @property {string} [appname] (**default**: undefined) The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @property {string} [options.auth.user] (**default**: undefined) The username for auth - * @property {string} [options.auth.password] (**default**: undefined) The password for auth - * @property {string} [authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options. - * @property {object} [compression] Type of compression to use: snappy or zlib - * @property {array} [readPreferenceTags] Read preference tags - * @property {number} [numberOfRetries] (**default**: 5) The number of retries for a tailable cursor - * @property {boolean} [auto_reconnect] (**default**: true) Enable auto reconnecting for single server instances - * @property {boolean} [monitorCommands] (**default**: false) Enable command monitoring for this client - * @property {string|ServerApi} [serverApi] (**default**: undefined) The server API version - * @property {number} [minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @property {boolean} [useNewUrlParser] (**default**: true) Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. - * @property {boolean} [useUnifiedTopology] Enables the new unified topology layer - * @property {number} [localThresholdMS] (**default**: 15) **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers - * @property {number} [serverSelectionTimeoutMS] (**default**: 30000) **Only applies to the unified topology** How long to block for server selection before throwing an error - * @property {number} [heartbeatFrequencyMS] (**default**: 10000) **Only applies to the unified topology** The frequency with which topology updates are scheduled - * @property {number} [maxPoolSize] (**default**: 10) **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. - * @property {number} [minPoolSize] (**default**: 0) **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool. - * @property {number} [maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity. - * @property {number} [waitQueueTimeoutMS] (**default**: 0) **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. - * @property {AutoEncryptionOptions} [autoEncryption] Optionally enable client side auto encryption. - * - * > Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error - * > (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. - * > - * > Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections). - * > - * > If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: - * > - AutoEncryptionOptions.keyVaultClient is not passed. - * > - AutoEncryptionOptions.bypassAutomaticEncryption is false. - * > If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. - * - * @property {DriverInfoOptions} [driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver - * @property {boolean} [directConnection] (**default**: false) Enable directConnection - * @property {function} [callback] The command result callback - */ - -/** - * Creates a new MongoClient instance - * @constructor - * @extends {EventEmitter} - * @param {string} url The connection URI string - * @param {MongoClientOptions} [options] Optional settings - */ -function MongoClient(url, options) { - options = options || {}; - if (!(this instanceof MongoClient)) return new MongoClient(url, options); - // Set up event emitter - EventEmitter.call(this); - - if (options.autoEncryption) require('./encrypter'); // Does CSFLE lib check - - if (options.serverApi) { - const serverApiToValidate = - typeof options.serverApi === 'string' ? { version: options.serverApi } : options.serverApi; - const versionToValidate = serverApiToValidate && serverApiToValidate.version; - if (!versionToValidate) { - throw new MongoError( - `Invalid \`serverApi\` property; must specify a version from the following enum: ["${ValidServerApiVersions.join( - '", "' - )}"]` - ); - } - if (!ValidServerApiVersions.some(v => v === versionToValidate)) { - throw new MongoError( - `Invalid server API version=${versionToValidate}; must be in the following enum: ["${ValidServerApiVersions.join( - '", "' - )}"]` - ); - } - options.serverApi = serverApiToValidate; - } - - // The internal state - this.s = { - url, - options, - promiseLibrary: (options && options.promiseLibrary) || Promise, - dbCache: new Map(), - sessions: new Set(), - writeConcern: WriteConcern.fromOptions(options), - readPreference: ReadPreference.fromOptions(options) || ReadPreference.primary, - namespace: new MongoDBNamespace('admin') - }; -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -Object.defineProperty(MongoClient.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(MongoClient.prototype, 'readPreference', { - enumerable: true, - get: function() { - return this.s.readPreference; - } -}); - -/** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {MongoClient} client The connected client. - */ - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.connect = function(callback) { - if (typeof callback === 'string') { - throw new TypeError('`connect` only accepts a callback'); - } - - const client = this; - return maybePromise(this, callback, cb => { - const err = validOptions(client.s.options); - if (err) return cb(err); - - connect(client, client.s.url, client.s.options, err => { - if (err) return cb(err); - cb(null, client); - }); - }); -}; - -MongoClient.prototype.logout = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - if (typeof callback === 'function') callback(null, true); -}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); - -/** - * Close the db and its underlying connections - * @method - * @param {boolean} [force=false] Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.close = function(force, callback) { - if (typeof force === 'function') { - callback = force; - force = false; - } - - const client = this; - return maybePromise(this, callback, cb => { - const completeClose = err => { - client.emit('close', client); - - if (!(client.topology instanceof NativeTopology)) { - for (const item of client.s.dbCache) { - item[1].emit('close', client); - } - } - - client.removeAllListeners('close'); - cb(err); - }; - - if (client.topology == null) { - completeClose(); - return; - } - - client.topology.close(force, err => { - const encrypter = client.topology.s.options.encrypter; - if (encrypter) { - return encrypter.close(client, force, err2 => { - completeClose(err || err2); - }); - } - completeClose(err); - }); - }); -}; - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -MongoClient.prototype.db = function(dbName, options) { - options = options || {}; - - // Default to db from connection string if not provided - if (!dbName) { - dbName = this.s.options.dbName; - } - - // Copy the options and add out internal override of the not shared flag - const finalOptions = Object.assign({}, this.s.options, options); - - // Do we have the db in the cache already - if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { - return this.s.dbCache.get(dbName); - } - - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; - - // If no topology throw an error message - if (!this.topology) { - throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); - } - - // Return the db object - const db = new Db(dbName, this.topology, finalOptions); - - // Add the db to the cache - this.s.dbCache.set(dbName, db); - // Return the database - return db; -}; - -/** - * Check if MongoClient is connected - * - * @method - * @deprecated - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {boolean} - */ -MongoClient.prototype.isConnected = deprecate(function(options) { - options = options || {}; - - if (!this.topology) return false; - return this.topology.isConnected(options); -}, 'isConnected is deprecated and will be removed in the next major version'); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {MongoClientOptions} [options] Optional settings - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : null; - options = options || {}; - - // Create client - const mongoClient = new MongoClient(url, options); - // Execute the connect method - return mongoClient.connect(callback); -}; - -/** - * Starts a new session on the server - * - * @param {SessionOptions} [options] optional settings for a driver session - * @return {ClientSession} the newly established session - */ -MongoClient.prototype.startSession = function(options) { - options = Object.assign({ explicit: true }, options); - if (!this.topology) { - throw new MongoError('Must connect to a server before calling this method'); - } - - return this.topology.startSession(options, this.s.options); -}; - -/** - * Runs a given operation with an implicitly created session. The lifetime of the session - * will be handled without the need for user interaction. - * - * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) - * - * @param {Object} [options] Optional settings to be appled to implicitly created session - * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` - * @return {Promise} - */ -MongoClient.prototype.withSession = function(options, operation) { - if (typeof options === 'function') (operation = options), (options = undefined); - const session = this.startSession(options); - - let cleanupHandler = (err, result, opts) => { - // prevent multiple calls to cleanupHandler - cleanupHandler = () => { - throw new ReferenceError('cleanupHandler was called too many times'); - }; - - opts = Object.assign({ throw: true }, opts); - session.endSession(); - - if (err) { - if (opts.throw) throw err; - return Promise.reject(err); - } - }; - - try { - const result = operation(session); - return Promise.resolve(result) - .then(result => cleanupHandler(null, result)) - .catch(err => cleanupHandler(err, null, { throw: true })); - } catch (err) { - return cleanupHandler(err, null, { throw: false }); - } -}; -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, - * and config databases. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -MongoClient.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the mongo client logger - * @method - * @return {Logger} return the mongo client logger - * @ignore - */ -MongoClient.prototype.getLogger = function() { - return this.s.options.logger; -}; - -module.exports = MongoClient; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/add_user.js b/reverse_engineering/node_modules/mongodb/lib/operations/add_user.js deleted file mode 100644 index 62af9d8..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/add_user.js +++ /dev/null @@ -1,99 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const crypto = require('crypto'); -const handleCallback = require('../utils').handleCallback; -const toError = require('../utils').toError; -const emitWarning = require('../utils').emitWarning; - -class AddUserOperation extends CommandOperation { - constructor(db, username, password, options) { - super(db, options); - - this.username = username; - this.password = password; - } - - _buildCommand() { - const db = this.db; - const username = this.username; - const password = this.password; - const options = this.options; - - // Get additional values - let roles = []; - if (Array.isArray(options.roles)) roles = options.roles; - if (typeof options.roles === 'string') roles = [options.roles]; - - // If not roles defined print deprecated message - // TODO: handle deprecation properly - if (roles.length === 0) { - emitWarning('Creating a user without roles is deprecated in MongoDB >= 2.6'); - } - - // Check the db name and add roles if needed - if ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // Build the command to execute - const command = { - createUser: username, - customData: options.customData || {}, - roles: roles, - digestPassword - }; - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - return command; - } - - execute(callback) { - const options = this.options; - - // Error out if digestPassword set - if (options.digestPassword != null) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Attempt to execute auth command - super.execute((err, r) => { - if (!err) { - return handleCallback(callback, err, r); - } - - return handleCallback(callback, err, null); - }); - } -} - -defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); - -module.exports = AddUserOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/admin_ops.js b/reverse_engineering/node_modules/mongodb/lib/operations/admin_ops.js deleted file mode 100644 index d5f3516..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/admin_ops.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const executeCommand = require('./db_ops').executeCommand; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; - -/** - * Get ReplicaSet status - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function replSetGetStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); -} - -/** - * Retrieve this db's server status. - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback - */ -function serverStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); -} - -/** - * Validate an existing collection - * - * @param {Admin} a collection instance. - * @param {string} collectionName The name of the collection to validate. - * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function validateCollection(admin, collectionName, options, callback) { - const command = { validate: collectionName }; - const keys = Object.keys(options); - - // Decorate command with extra options - for (let i = 0; i < keys.length; i++) { - if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - executeCommand(admin.s.db, command, options, (err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); -} - -module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/aggregate.js b/reverse_engineering/node_modules/mongodb/lib/operations/aggregate.js deleted file mode 100644 index ca69a52..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/aggregate.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const MongoError = require('../core').MongoError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const ReadPreference = require('../core').ReadPreference; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -const DB_AGGREGATE_COLLECTION = 1; -const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; - -class AggregateOperation extends CommandOperationV2 { - constructor(parent, pipeline, options) { - super(parent, options, { fullResponse: true }); - - this.target = - parent.s.namespace && parent.s.namespace.collection - ? parent.s.namespace.collection - : DB_AGGREGATE_COLLECTION; - - this.pipeline = pipeline; - - // determine if we have a write stage, override read preference if so - this.hasWriteStage = false; - if (typeof options.out === 'string') { - this.pipeline = this.pipeline.concat({ $out: options.out }); - this.hasWriteStage = true; - } else if (pipeline.length > 0) { - const finalStage = pipeline[pipeline.length - 1]; - if (finalStage.$out || finalStage.$merge) { - this.hasWriteStage = true; - } - } - - if (this.hasWriteStage) { - this.readPreference = ReadPreference.primary; - } - - if (this.explain && this.writeConcern) { - throw new MongoError('"explain" cannot be used on an aggregate call with writeConcern'); - } - - if (options.cursor != null && typeof options.cursor !== 'object') { - throw new MongoError('cursor options must be an object'); - } - } - - get canRetryRead() { - return !this.hasWriteStage; - } - - addToPipeline(stage) { - this.pipeline.push(stage); - } - - execute(server, callback) { - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const command = { aggregate: this.target, pipeline: this.pipeline }; - - if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { - this.readConcern = null; - } - - if (serverWireVersion >= 5) { - if (this.hasWriteStage && this.writeConcern) { - Object.assign(command, { writeConcern: this.writeConcern }); - } - } - - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - if (typeof options.allowDiskUse === 'boolean') { - command.allowDiskUse = options.allowDiskUse; - } - - if (options.hint) { - command.hint = options.hint; - } - - if (this.explain) { - options.full = false; - } - - command.cursor = options.cursor || {}; - if (options.batchSize && !this.hasWriteStage) { - command.cursor.batchSize = options.batchSize; - } - - super.executeCommand(server, command, callback); - } -} - -defineAspects(AggregateOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.EXPLAINABLE -]); - -module.exports = AggregateOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/bulk_write.js b/reverse_engineering/node_modules/mongodb/lib/operations/bulk_write.js deleted file mode 100644 index 493defd..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/bulk_write.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; - -class BulkWriteOperation extends OperationBase { - constructor(collection, operations, options) { - super(options); - - this.collection = collection; - this.operations = operations; - } - - execute(callback) { - const coll = this.collection; - const operations = this.operations; - let options = this.options; - - // Add ignoreUndfined - if (coll.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = coll.s.options.ignoreUndefined; - } - - // Create the bulk operation - const bulk = - options.ordered === true || options.ordered == null - ? coll.initializeOrderedBulkOp(options) - : coll.initializeUnorderedBulkOp(options); - - // Do we have a collation - let collation = false; - - // for each op go through and add to the bulk - try { - for (let i = 0; i < operations.length; i++) { - // Get the operation type - const key = Object.keys(operations[i])[0]; - // Check if we have a collation - if (operations[i][key].collation) { - collation = true; - } - - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch (err) { - return callback(err, null); - } - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - const capabilities = coll.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - // Execute the bulk - bulk.execute(writeCon, finalOptions, (err, r) => { - // We have connection level error - if (!r && err) { - return callback(err, null); - } - - // Return the results - callback(null, r); - }); - } -} - -module.exports = BulkWriteOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/collection_ops.js b/reverse_engineering/node_modules/mongodb/lib/operations/collection_ops.js deleted file mode 100644 index 655bd70..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/collection_ops.js +++ /dev/null @@ -1,353 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const createIndexDb = require('./db_ops').createIndex; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const ensureIndexDb = require('./db_ops').ensureIndex; -const evaluate = require('./db_ops').evaluate; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const insertDocuments = require('./common_functions').insertDocuments; -const updateDocuments = require('./common_functions').updateDocuments; - -/** - * Group function helper - * @ignore - */ -// var groupFunction = function () { -// var c = db[ns].find(condition); -// var map = new Map(); -// var reduce_function = reduce; -// -// while (c.hasNext()) { -// var obj = c.next(); -// var key = {}; -// -// for (var i = 0, len = keys.length; i < len; ++i) { -// var k = keys[i]; -// key[k] = obj[k]; -// } -// -// var aggObj = map.get(key); -// -// if (aggObj == null) { -// var newObj = Object.extend({}, key); -// aggObj = Object.extend(newObj, initial); -// map.put(key, aggObj); -// } -// -// reduce_function(obj, aggObj); -// } -// -// return { "result": map.values() }; -// }.toString(); -const groupFunction = - 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; - -/** - * Create an index on the db and collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndex(coll, fieldOrSpec, options, callback) { - createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Create multiple indexes in the collection. This method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * - * @method - * @param {Collection} a Collection instance. - * @param {array} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndexes(coll, indexSpecs, options, callback) { - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); -} - -/** - * Ensure that an index exists. If the index does not exist, this function creates it. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function ensureIndex(coll, fieldOrSpec, options, callback) { - ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Run a group command across a collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. - */ -function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if (command) { - const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); - - const selector = { - group: { - ns: coll.collectionName, - $reduce: reduceFunction, - cond: condition, - initial: initial, - out: 'inline' - } - }; - - // if finalize is defined - if (finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { - selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); - } else { - const hash = {}; - keys.forEach(key => { - hash[key] = 1; - }); - selector.group.key = hash; - } - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = ReadPreference.resolve(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(selector, coll, options); - - // Have we specified collation - try { - decorateWithCollation(selector, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, selector, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; - - scope.ns = coll.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -/** - * Retrieve all the indexes on the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexes(coll, options, callback) { - options = Object.assign({}, { full: true }, options); - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexExists(coll, indexes, options, callback) { - indexInformation(coll, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -/** - * Retrieve this collection's index info. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexInformation(coll, options, callback) { - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are - * no ordering guarantees for returned results. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - */ -function parallelCollectionScan(coll, options, callback) { - // Create command object - const commandObject = { - parallelCollectionScan: coll.collectionName, - numCursors: options.numCursors - }; - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Store the raw value - const raw = options.raw; - delete options['raw']; - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result == null) - return handleCallback( - callback, - new Error('no result returned for parallelCollectionScan'), - null - ); - - options = Object.assign({ explicitlyIgnoreSession: true }, options); - - const cursors = []; - // Add the raw back to the option - if (raw) options.raw = raw; - // Create command cursors for each item - for (let i = 0; i < result.cursors.length; i++) { - const rawId = result.cursors[i].cursor.id; - // Convert cursorId to Long if needed - const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; - // Add a command cursor - cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -/** - * Save a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} doc Document to save - * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -function save(coll, doc, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern( - Object.assign({}, options), - { db: coll.s.db, collection: coll }, - options - ); - // Establish if we need to perform an insert or update - if (doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(coll, [doc], finalOptions, (err, result) => { - if (callback == null) return; - if (doc == null) return handleCallback(callback, null, null); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -module.exports = { - createIndex, - createIndexes, - ensureIndex, - group, - indexes, - indexExists, - indexInformation, - parallelCollectionScan, - save -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/collections.js b/reverse_engineering/node_modules/mongodb/lib/operations/collections.js deleted file mode 100644 index eac690a..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/collections.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} - -class CollectionsOperation extends OperationBase { - constructor(db, options) { - super(options); - - this.db = db; - } - - execute(callback) { - const db = this.db; - let options = this.options; - - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); - } -} - -module.exports = CollectionsOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/command.js b/reverse_engineering/node_modules/mongodb/lib/operations/command.js deleted file mode 100644 index 769275f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/command.js +++ /dev/null @@ -1,122 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const MongoDBNamespace = require('../utils').MongoDBNamespace; -const extractCommand = require('../command_utils').extractCommand; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -class CommandOperation extends OperationBase { - constructor(db, options, collection, command) { - super(options); - - if (!this.hasAspect(Aspect.WRITE_OPERATION)) { - if (collection != null) { - this.options.readPreference = ReadPreference.resolve(collection, options); - } else { - this.options.readPreference = ReadPreference.resolve(db, options); - } - } else { - if (collection != null) { - applyWriteConcern(this.options, { db, coll: collection }, this.options); - } else { - applyWriteConcern(this.options, { db }, this.options); - } - this.options.readPreference = ReadPreference.primary; - } - - this.db = db; - - if (command != null) { - this.command = command; - } - - if (collection != null) { - this.collection = collection; - } - } - - _buildCommand() { - if (this.command != null) { - return this.command; - } - } - - execute(callback) { - const db = this.db; - const options = Object.assign({}, this.options); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let command; - try { - command = this._buildCommand(); - } catch (e) { - return callback(e); - } - - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - if (this.hasAspect(Aspect.WRITE_OPERATION)) { - if (options.writeConcern && (!options.session || !options.session.inTransaction())) { - command.writeConcern = options.writeConcern; - } - } - - // Debug information - if (db.s.logger.isDebug()) { - const extractedCommand = extractCommand(command); - db.s.logger.debug( - `executing command ${JSON.stringify( - extractedCommand.shouldRedact ? `${extractedCommand.name} details REDACTED` : command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - } - - const namespace = - this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); - - // Execute command - db.s.topology.command(namespace, command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = CommandOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/command_v2.js b/reverse_engineering/node_modules/mongodb/lib/operations/command_v2.js deleted file mode 100644 index 475a1c1..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/command_v2.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const ReadPreference = require('../core').ReadPreference; -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); -const maxWireVersion = require('../core/utils').maxWireVersion; -const decorateWithExplain = require('../utils').decorateWithExplain; -const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern; -const MongoError = require('../core/error').MongoError; -const extractCommand = require('../command_utils').extractCommand; - -const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; - -class CommandOperationV2 extends OperationBase { - constructor(parent, options, operationOptions) { - super(options); - - this.ns = parent.s.namespace.withCollection('$cmd'); - const propertyProvider = this.hasAspect(Aspect.NO_INHERIT_OPTIONS) ? undefined : parent; - this.readPreference = this.hasAspect(Aspect.WRITE_OPERATION) - ? ReadPreference.primary - : ReadPreference.resolve(propertyProvider, this.options); - this.readConcern = resolveReadConcern(propertyProvider, this.options); - this.writeConcern = resolveWriteConcern(propertyProvider, this.options); - - if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { - this.fullResponse = true; - } - - // TODO: A lot of our code depends on having the read preference in the options. This should - // go away, but also requires massive test rewrites. - this.options.readPreference = this.readPreference; - - // TODO(NODE-2056): make logger another "inheritable" property - if (parent.s.logger) { - this.logger = parent.s.logger; - } else if (parent.s.db && parent.s.db.logger) { - this.logger = parent.s.db.logger; - } - } - - executeCommand(server, cmd, callback) { - // TODO: consider making this a non-enumerable property - this.server = server; - - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const inTransaction = this.session && this.session.inTransaction(); - - if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { - Object.assign(cmd, { readConcern: this.readConcern }); - } - - if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - callback( - new MongoError( - `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` - ) - ); - return; - } - - if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { - Object.assign(cmd, { writeConcern: this.writeConcern }); - } - - if (options.collation && typeof options.collation === 'object') { - Object.assign(cmd, { collation: options.collation }); - } - } - - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - if (typeof options.comment === 'string') { - cmd.comment = options.comment; - } - - if (this.hasAspect(Aspect.EXPLAINABLE) && this.explain) { - if (serverWireVersion < 6 && cmd.aggregate) { - // Prior to 3.6, with aggregate, verbosity is ignored, and we must pass in "explain: true" - cmd.explain = true; - } else { - cmd = decorateWithExplain(cmd, this.explain); - } - } - - if (this.logger && this.logger.isDebug()) { - const extractedCommand = extractCommand(cmd); - this.logger.debug( - `executing command ${JSON.stringify( - extractedCommand.shouldRedact ? `${extractedCommand.name} details REDACTED` : cmd - )} against ${this.ns}` - ); - } - - server.command(this.ns.toString(), cmd, this.options, (err, result) => { - if (err) { - callback(err, null); - return; - } - - if (this.fullResponse) { - callback(null, result); - return; - } - - callback(null, result.result); - }); - } -} - -function resolveWriteConcern(parent, options) { - return WriteConcern.fromOptions(options) || (parent && parent.writeConcern); -} - -function resolveReadConcern(parent, options) { - return ReadConcern.fromOptions(options) || (parent && parent.readConcern); -} - -module.exports = CommandOperationV2; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/common_functions.js b/reverse_engineering/node_modules/mongodb/lib/operations/common_functions.js deleted file mode 100644 index 5b9c172..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/common_functions.js +++ /dev/null @@ -1,399 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CursorState = require('../core/cursor').CursorState; -const maxWireVersion = require('../core/utils').maxWireVersion; - -/** - * Build the count command. - * - * @method - * @param {collectionOrCursor} an instance of a collection or cursor - * @param {object} query The query for the count. - * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. - */ -function buildCountCommand(collectionOrCursor, query, options) { - const skip = options.skip; - const limit = options.limit; - let hint = options.hint; - const maxTimeMS = options.maxTimeMS; - query = query || {}; - - // Final query - const cmd = { - count: options.collectionName, - query: query - }; - - if (collectionOrCursor.s.numberOfRetries) { - // collectionOrCursor is a cursor - if (collectionOrCursor.options.hint) { - hint = collectionOrCursor.options.hint; - } else if (collectionOrCursor.cmd.hint) { - hint = collectionOrCursor.cmd.hint; - } - decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); - } else { - decorateWithCollation(cmd, collectionOrCursor, options); - } - - // Add limit, skip and maxTimeMS if defined - if (typeof skip === 'number') cmd.skip = skip; - if (typeof limit === 'number') cmd.limit = limit; - if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; - if (hint) cmd.hint = hint; - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, collectionOrCursor); - - return cmd; -} - -/** - * Find and update a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -function findAndModify(coll, query, sort, doc, options, callback) { - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - sort = formattedOrderClause(sort); - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - delete options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (finalOptions.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - finalOptions.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, finalOptions); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db.collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -function prepareDocs(coll, docs, options) { - const forceServerObjectId = - typeof options.forceServerObjectId === 'boolean' - ? options.forceServerObjectId - : coll.s.db.options.forceServerObjectId; - - // no need to modify the docs if server sets the ObjectId - if (forceServerObjectId === true) { - return docs; - } - - return docs.map(doc => { - if (forceServerObjectId !== true && doc._id == null) { - doc._id = coll.s.pkFactory.createPk(); - } - - return doc; - }); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -function insertDocuments(coll, docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If keep going set unordered - if (finalOptions.keepGoing === true) finalOptions.ordered = false; - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // File inserts - coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -function removeDocuments(coll, selector, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}); - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If selector is null set empty - if (selector == null) selector = {}; - - // Build the op - const op = { q: selector, limit: 0 }; - if (options.single) { - op.limit = 1; - } else if (finalOptions.retryWrites) { - finalOptions.retryWrites = false; - } - if (options.hint) { - op.hint = options.hint; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - if (options.explain !== undefined && maxWireVersion(coll.s.topology) < 3) { - return callback - ? callback(new MongoError(`server does not support explain on remove`)) - : undefined; - } - - // Execute the remove - coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) { - return handleCallback(callback, toError(result.result.writeErrors[0])); - } - - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateDocuments(coll, selector, document, options, callback) { - if ('function' === typeof options) (callback = options), (options = null); - if (options == null) options = {}; - if (!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if (selector == null || typeof selector !== 'object') - return callback(toError('selector must be a valid JavaScript object')); - if (document == null || typeof document !== 'object') - return callback(toError('document must be a valid JavaScript object')); - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // Execute the operation - const op = { q: selector, u: document }; - op.upsert = options.upsert !== void 0 ? !!options.upsert : false; - op.multi = options.multi !== void 0 ? !!options.multi : false; - - if (options.hint) { - op.hint = options.hint; - } - - if (finalOptions.arrayFilters) { - op.arrayFilters = finalOptions.arrayFilters; - delete finalOptions.arrayFilters; - } - - if (finalOptions.retryWrites && op.multi) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - if (options.explain !== undefined && maxWireVersion(coll.s.topology) < 3) { - return callback - ? callback(new MongoError(`server does not support explain on update`)) - : undefined; - } - - // Update options - coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -module.exports = { - buildCountCommand, - findAndModify, - indexInformation, - nextObject, - prepareDocs, - insertDocuments, - removeDocuments, - updateDocuments -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/connect.js b/reverse_engineering/node_modules/mongodb/lib/operations/connect.js deleted file mode 100644 index a220466..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/connect.js +++ /dev/null @@ -1,784 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const Logger = require('../core').Logger; -const MongoCredentials = require('../core').MongoCredentials; -const MongoError = require('../core').MongoError; -const Mongos = require('../topologies/mongos'); -const NativeTopology = require('../topologies/native_topology'); -const parse = require('../core').parseConnectionString; -const ReadConcern = require('../read_concern'); -const ReadPreference = require('../core').ReadPreference; -const ReplSet = require('../topologies/replset'); -const Server = require('../topologies/server'); -const ServerSessionPool = require('../core').Sessions.ServerSessionPool; -const emitDeprecationWarning = require('../utils').emitDeprecationWarning; -const emitWarningOnce = require('../utils').emitWarningOnce; -const fs = require('fs'); -const WriteConcern = require('../write_concern'); -const CMAP_EVENT_NAMES = require('../cmap/events').CMAP_EVENT_NAMES; - -let client; -function loadClient() { - if (!client) { - client = require('../mongo_client'); - } - return client; -} - -const legacyParse = deprecate( - require('../url_parser'), - 'current URL string parser is deprecated, and will be removed in a future version. ' + - 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' -); - -const AUTH_MECHANISM_INTERNAL_MAP = { - DEFAULT: 'default', - PLAIN: 'plain', - GSSAPI: 'gssapi', - 'MONGODB-CR': 'mongocr', - 'MONGODB-X509': 'x509', - 'MONGODB-AWS': 'mongodb-aws', - 'SCRAM-SHA-1': 'scram-sha-1', - 'SCRAM-SHA-256': 'scram-sha-256' -}; - -const monitoringEvents = [ - 'timeout', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]; - -const VALID_AUTH_MECHANISMS = new Set([ - 'DEFAULT', - 'PLAIN', - 'GSSAPI', - 'MONGODB-CR', - 'MONGODB-X509', - 'MONGODB-AWS', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256' -]); - -const validOptionNames = [ - 'poolSize', - 'ssl', - 'sslValidate', - 'sslCA', - 'sslCert', - 'sslKey', - 'sslPass', - 'sslCRL', - 'autoReconnect', - 'noDelay', - 'keepAlive', - 'keepAliveInitialDelay', - 'connectTimeoutMS', - 'family', - 'socketTimeoutMS', - 'reconnectTries', - 'reconnectInterval', - 'ha', - 'haInterval', - 'replicaSet', - 'secondaryAcceptableLatencyMS', - 'acceptableLatencyMS', - 'connectWithNoPrimary', - 'authSource', - 'w', - 'wtimeout', - 'j', - 'writeConcern', - 'forceServerObjectId', - 'serializeFunctions', - 'ignoreUndefined', - 'raw', - 'bufferMaxEntries', - 'readPreference', - 'pkFactory', - 'promiseLibrary', - 'readConcern', - 'maxStalenessSeconds', - 'loggerLevel', - 'logger', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs', - 'bsonRegExp', - 'domainsEnabled', - 'checkServerIdentity', - 'validateOptions', - 'appname', - 'auth', - 'user', - 'password', - 'authMechanism', - 'compression', - 'fsync', - 'readPreferenceTags', - 'numberOfRetries', - 'auto_reconnect', - 'minSize', - 'monitorCommands', - 'serverApi', - 'retryWrites', - 'retryReads', - 'useNewUrlParser', - 'useUnifiedTopology', - 'serverSelectionTimeoutMS', - 'useRecoveryToken', - 'autoEncryption', - 'driverInfo', - 'tls', - 'tlsInsecure', - 'tlsinsecure', - 'tlsAllowInvalidCertificates', - 'tlsAllowInvalidHostnames', - 'tlsCAFile', - 'tlsCertificateFile', - 'tlsCertificateKeyFile', - 'tlsCertificateKeyFilePassword', - 'minHeartbeatFrequencyMS', - 'heartbeatFrequencyMS', - 'directConnection', - 'appName', - - // CMAP options - 'maxPoolSize', - 'minPoolSize', - 'maxIdleTimeMS', - 'waitQueueTimeoutMS' -]; - -const ignoreOptionNames = ['native_parser']; -const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; - -// Validate options object -function validOptions(options) { - const _validOptions = validOptionNames.concat(legacyOptionNames); - - for (const name in options) { - if (ignoreOptionNames.indexOf(name) !== -1) { - continue; - } - - if (_validOptions.indexOf(name) === -1) { - if (options.validateOptions) { - return new MongoError(`option ${name} is not supported`); - } else { - emitWarningOnce(`the options [${name}] is not supported`); - } - } - - if (legacyOptionNames.indexOf(name) !== -1) { - emitWarningOnce( - `the server/replset/mongos/db options are deprecated, ` + - `all their options are supported at the top level of the options object [${validOptionNames}]` - ); - } - } -} - -const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { - obj[name.toLowerCase()] = name; - return obj; -}, {}); - -function addListeners(mongoClient, topology) { - topology.on('authenticated', createListener(mongoClient, 'authenticated')); - topology.on('error', createListener(mongoClient, 'error')); - topology.on('timeout', createListener(mongoClient, 'timeout')); - topology.on('close', createListener(mongoClient, 'close')); - topology.on('parseError', createListener(mongoClient, 'parseError')); - topology.once('open', createListener(mongoClient, 'open')); - topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); - topology.once('all', createListener(mongoClient, 'all')); - topology.on('reconnect', createListener(mongoClient, 'reconnect')); -} - -function assignTopology(client, topology) { - client.topology = topology; - - if (!(topology instanceof NativeTopology)) { - topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); - } -} - -// Clear out all events -function clearAllEvents(topology) { - monitoringEvents.forEach(event => topology.removeAllListeners(event)); -} - -// Collect all events in order from SDAM -function collectEvents(mongoClient, topology) { - let MongoClient = loadClient(); - const collectedEvents = []; - - if (mongoClient instanceof MongoClient) { - monitoringEvents.forEach(event => { - topology.on(event, (object1, object2) => { - if (event === 'open') { - collectedEvents.push({ event: event, object1: mongoClient }); - } else { - collectedEvents.push({ event: event, object1: object1, object2: object2 }); - } - }); - }); - } - - return collectedEvents; -} - -function resolveTLSOptions(options) { - if (options.tls == null) { - return; - } - - ['sslCA', 'sslKey', 'sslCert'].forEach(optionName => { - if (options[optionName]) { - options[optionName] = fs.readFileSync(options[optionName]); - } - }); -} - -function connect(mongoClient, url, options, callback) { - options = Object.assign({}, options); - - // If callback is null throw an exception - if (callback == null) { - throw new Error('no callback function provided'); - } - - let didRequestAuthentication = false; - const logger = Logger('MongoClient', options); - - // Did we pass in a Server/ReplSet/Mongos - if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { - return connectWithUrl(mongoClient, url, options, connectCallback); - } - - const useNewUrlParser = options.useNewUrlParser !== false; - - const parseFn = useNewUrlParser ? parse : legacyParse; - const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; - - parseFn(url, options, (err, _object) => { - // Do not attempt to connect if parsing error - if (err) return callback(err); - - // Flatten - const object = transform(_object); - - // Parse the string - const _finalOptions = createUnifiedOptions(object, options); - - // Check if we have connection and socket timeout set - if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 0; - if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 10000; - if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; - if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; - if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; - - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } - - // resolve tls options if needed - resolveTLSOptions(_finalOptions); - - // Store the merged options object - mongoClient.s.options = _finalOptions; - - // Apply read and write concern from parsed url - mongoClient.s.readPreference = ReadPreference.fromOptions(_finalOptions); - mongoClient.s.writeConcern = WriteConcern.fromOptions(_finalOptions); - - // Failure modes - if (object.servers.length === 0) { - return callback(new Error('connection string must contain at least one seed host')); - } - - if (_finalOptions.auth && !_finalOptions.credentials) { - try { - didRequestAuthentication = true; - _finalOptions.credentials = generateCredentials( - mongoClient, - _finalOptions.auth.user, - _finalOptions.auth.password, - _finalOptions - ); - } catch (err) { - return callback(err); - } - } - - if (_finalOptions.useUnifiedTopology) { - return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); - } - - emitWarningOnce( - 'Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.' - ); - - // Do we have a replicaset then skip discovery and go straight to connectivity - if (_finalOptions.replicaSet || _finalOptions.rs_name) { - return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); - } else if (object.servers.length > 1) { - return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); - } else { - return createServer(mongoClient, _finalOptions, connectCallback); - } - }); - - function connectCallback(err, topology) { - const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; - if (err && err.message === 'no mongos proxies found in seed list') { - if (logger.isWarn()) { - logger.warn(warningMessage); - } - - // Return a more specific error message for MongoClient.connect - return callback(new MongoError(warningMessage)); - } - - if (didRequestAuthentication) { - mongoClient.emit('authenticated', null, true); - } - - // Return the error and db instance - callback(err, topology); - } -} - -function connectWithUrl(mongoClient, url, options, connectCallback) { - // Set the topology - assignTopology(mongoClient, url); - - // Add listeners - addListeners(mongoClient, url); - - // Propagate the events to the client - relayEvents(mongoClient, url); - - let finalOptions = Object.assign({}, options); - - // If we have a readPreference passed in by the db options, convert it from a string - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - finalOptions.readPreference = new ReadPreference( - options.readPreference || options.read_preference - ); - } - - const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; - if (isDoingAuth && !finalOptions.credentials) { - try { - finalOptions.credentials = generateCredentials( - mongoClient, - finalOptions.user, - finalOptions.password, - finalOptions - ); - } catch (err) { - return connectCallback(err, url); - } - } - - return url.connect(finalOptions, connectCallback); -} - -function createListener(mongoClient, event) { - const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); - return (v1, v2) => { - if (eventSet.has(event)) { - return mongoClient.emit(event, mongoClient); - } - - mongoClient.emit(event, v1, v2); - }; -} - -function createServer(mongoClient, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - // Set default options - const servers = translateOptions(options); - - const server = servers[0]; - - // Propagate the events to the client - const collectedEvents = collectEvents(mongoClient, server); - - // Connect to topology - server.connect(options, (err, topology) => { - if (err) { - server.close(true); - return callback(err); - } - // Clear out all the collected event listeners - clearAllEvents(server); - - // Relay all the events - relayEvents(mongoClient, server); - // Add listeners - addListeners(mongoClient, server); - // Check if we are really speaking to a mongos - const ismaster = topology.lastIsMaster(); - - // Set the topology - assignTopology(mongoClient, topology); - - // Do we actually have a mongos - if (ismaster && ismaster.msg === 'isdbgrid') { - // Destroy the current connection - topology.close(); - // Create mongos connection instead - return createTopology(mongoClient, 'mongos', options, callback); - } - - // Fire all the events - replayEvents(mongoClient, collectedEvents); - // Otherwise callback - callback(err, topology); - }); -} - -const DEPRECATED_UNIFIED_EVENTS = new Set([ - 'reconnect', - 'reconnectFailed', - 'attemptReconnect', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]); - -function registerDeprecatedEventNotifiers(client) { - client.on('newListener', eventName => { - if (DEPRECATED_UNIFIED_EVENTS.has(eventName)) { - emitDeprecationWarning( - `The \`${eventName}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, - 'DeprecationWarning' - ); - } - }); -} - -function createTopology(mongoClient, topologyType, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - const translationOptions = {}; - if (topologyType === 'unified') translationOptions.createServers = false; - - // Set default options - const servers = translateOptions(options, translationOptions); - - // determine CSFLE support - if (options.autoEncryption != null) { - const Encrypter = require('../encrypter').Encrypter; - options.encrypter = new Encrypter(mongoClient, options); - options.autoEncrypter = options.encrypter.autoEncrypter; - } - - // Create the topology - let topology; - if (topologyType === 'mongos') { - topology = new Mongos(servers, options); - } else if (topologyType === 'replicaset') { - topology = new ReplSet(servers, options); - } else if (topologyType === 'unified') { - topology = new NativeTopology(options.servers, options); - registerDeprecatedEventNotifiers(mongoClient); - } - - // Add listeners - addListeners(mongoClient, topology); - - // Propagate the events to the client - relayEvents(mongoClient, topology); - - // Open the connection - assignTopology(mongoClient, topology); - - // initialize CSFLE if requested - if (options.autoEncrypter) { - options.autoEncrypter.init(err => { - if (err) { - callback(err); - return; - } - - topology.connect(options, err => { - if (err) { - topology.close(true); - callback(err); - return; - } - - options.encrypter.connectInternalClient(error => { - if (error) return callback(error); - callback(undefined, topology); - }); - }); - }); - - return; - } - - // otherwise connect normally - topology.connect(options, err => { - if (err) { - topology.close(true); - return callback(err); - } - - callback(undefined, topology); - return; - }); -} - -function createUnifiedOptions(finalOptions, options) { - const childOptions = [ - 'mongos', - 'server', - 'db', - 'replset', - 'db_options', - 'server_options', - 'rs_options', - 'mongos_options' - ]; - const noMerge = ['readconcern', 'compression', 'autoencryption']; - const skip = ['w', 'wtimeout', 'j', 'journal', 'fsync', 'writeconcern']; - - for (const name in options) { - if (skip.indexOf(name.toLowerCase()) !== -1) { - continue; - } else if (noMerge.indexOf(name.toLowerCase()) !== -1) { - finalOptions[name] = options[name]; - } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { - finalOptions = mergeOptions(finalOptions, options[name], false); - } else { - if ( - options[name] && - typeof options[name] === 'object' && - !Buffer.isBuffer(options[name]) && - !Array.isArray(options[name]) - ) { - finalOptions = mergeOptions(finalOptions, options[name], true); - } else { - finalOptions[name] = options[name]; - } - } - } - - // Handle write concern keys separately, since `options` may have the keys at the top level or - // under `options.writeConcern`. The final merged keys will be under `finalOptions.writeConcern`. - // This way, `fromOptions` will warn once if `options` is using deprecated write concern options - const optionsWriteConcern = WriteConcern.fromOptions(options); - if (optionsWriteConcern) { - finalOptions.writeConcern = Object.assign({}, finalOptions.writeConcern, optionsWriteConcern); - } - - return finalOptions; -} - -function generateCredentials(client, username, password, options) { - options = Object.assign({}, options); - - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - const source = options.authSource || options.authdb || options.dbName; - - // authMechanism - const authMechanismRaw = options.authMechanism || 'DEFAULT'; - const authMechanism = authMechanismRaw.toUpperCase(); - const mechanismProperties = options.authMechanismProperties; - - if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { - throw MongoError.create({ - message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, - driver: true - }); - } - - return new MongoCredentials({ - mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], - mechanismProperties, - source, - username, - password - }); -} - -function legacyTransformUrlOptions(object) { - return mergeOptions(createUnifiedOptions({}, object), object, false); -} - -function mergeOptions(target, source, flatten) { - for (const name in source) { - if (source[name] && typeof source[name] === 'object' && flatten) { - target = mergeOptions(target, source[name], flatten); - } else { - target[name] = source[name]; - } - } - - return target; -} - -function relayEvents(mongoClient, topology) { - const serverOrCommandEvents = [ - // APM - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // SDAM - 'serverOpening', - 'serverClosed', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - - // Legacy - 'joined', - 'left', - 'ping', - 'ha' - ].concat(CMAP_EVENT_NAMES); - - serverOrCommandEvents.forEach(event => { - topology.on(event, (object1, object2) => { - mongoClient.emit(event, object1, object2); - }); - }); -} - -// -// Replay any events due to single server connection switching to Mongos -// -function replayEvents(mongoClient, events) { - for (let i = 0; i < events.length; i++) { - mongoClient.emit(events[i].event, events[i].object1, events[i].object2); - } -} - -function transformUrlOptions(_object) { - let object = Object.assign({ servers: _object.hosts }, _object.options); - for (let name in object) { - const camelCaseName = LEGACY_OPTIONS_MAP[name]; - if (camelCaseName) { - object[camelCaseName] = object[name]; - } - } - - const hasUsername = _object.auth && _object.auth.username; - const hasAuthMechanism = _object.options && _object.options.authMechanism; - if (hasUsername || hasAuthMechanism) { - object.auth = Object.assign({}, _object.auth); - if (object.auth.db) { - object.authSource = object.authSource || object.auth.db; - } - - if (object.auth.username) { - object.auth.user = object.auth.username; - } - } - - if (_object.defaultDatabase) { - object.dbName = _object.defaultDatabase; - } - - if (object.maxPoolSize) { - object.poolSize = object.maxPoolSize; - } - - if (object.readConcernLevel) { - object.readConcern = new ReadConcern(object.readConcernLevel); - } - - if (object.wTimeoutMS) { - object.wtimeout = object.wTimeoutMS; - object.wTimeoutMS = undefined; - } - - if (_object.srvHost) { - object.srvHost = _object.srvHost; - } - - // Any write concern options from the URL will be top-level, so we manually - // move them options under `object.writeConcern` to avoid warnings later - const wcKeys = ['w', 'wtimeout', 'j', 'journal', 'fsync']; - for (const key of wcKeys) { - if (object[key] !== undefined) { - if (object.writeConcern === undefined) object.writeConcern = {}; - object.writeConcern[key] = object[key]; - object[key] = undefined; - } - } - - return object; -} - -function translateOptions(options, translationOptions) { - translationOptions = Object.assign({}, { createServers: true }, translationOptions); - - // If we have a readPreference passed in by the db options - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - options.readPreference = new ReadPreference(options.readPreference || options.read_preference); - } - - // Do we have readPreference tags, add them - if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { - options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; - } - - // Do we have maxStalenessSeconds - if (options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; - } - - // Set the socket and connection timeouts - if (options.socketTimeoutMS == null) options.socketTimeoutMS = 0; - if (options.connectTimeoutMS == null) options.connectTimeoutMS = 10000; - - if (!translationOptions.createServers) { - return; - } - - // Create server instances - return options.servers.map(serverObj => { - return serverObj.domain_socket - ? new Server(serverObj.domain_socket, 27017, options) - : new Server(serverObj.host, serverObj.port, options); - }); -} - -module.exports = { validOptions, connect }; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/count.js b/reverse_engineering/node_modules/mongodb/lib/operations/count.js deleted file mode 100644 index a7216d6..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/count.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./common_functions').buildCountCommand; -const OperationBase = require('./operation').OperationBase; - -class CountOperation extends OperationBase { - constructor(cursor, applySkipLimit, options) { - super(options); - - this.cursor = cursor; - this.applySkipLimit = applySkipLimit; - } - - execute(callback) { - const cursor = this.cursor; - const applySkipLimit = this.applySkipLimit; - const options = this.options; - - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (options.readPreference) { - cursor.setReadPreference(options.readPreference); - } - - if ( - typeof options.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - options.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let finalOptions = {}; - finalOptions.skip = options.skip; - finalOptions.limit = options.limit; - finalOptions.hint = options.hint; - finalOptions.maxTimeMS = options.maxTimeMS; - - // Command - finalOptions.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); - } -} - -module.exports = CountOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/count_documents.js b/reverse_engineering/node_modules/mongodb/lib/operations/count_documents.js deleted file mode 100644 index d043abf..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/count_documents.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const AggregateOperation = require('./aggregate'); - -class CountDocumentsOperation extends AggregateOperation { - constructor(collection, query, options) { - const pipeline = [{ $match: query }]; - if (typeof options.skip === 'number') { - pipeline.push({ $skip: options.skip }); - } - - if (typeof options.limit === 'number') { - pipeline.push({ $limit: options.limit }); - } - - pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); - - super(collection, pipeline, options); - } - - execute(server, callback) { - super.execute(server, (err, result) => { - if (err) { - callback(err, null); - return; - } - - // NOTE: We're avoiding creating a cursor here to reduce the callstack. - const response = result.result; - if (response.cursor == null || response.cursor.firstBatch == null) { - callback(null, 0); - return; - } - - const docs = response.cursor.firstBatch; - callback(null, docs.length ? docs[0].n : 0); - }); - } -} - -module.exports = CountDocumentsOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/create_collection.js b/reverse_engineering/node_modules/mongodb/lib/operations/create_collection.js deleted file mode 100644 index c84adb0..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/create_collection.js +++ /dev/null @@ -1,102 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const loadCollection = require('../dynamic_loaders').loadCollection; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -const ILLEGAL_COMMAND_FIELDS = new Set([ - 'w', - 'wtimeout', - 'j', - 'fsync', - 'autoIndexId', - 'strict', - 'serializeFunctions', - 'pkFactory', - 'raw', - 'readPreference', - 'session', - 'readConcern', - 'writeConcern' -]); - -class CreateCollectionOperation extends CommandOperation { - constructor(db, name, options) { - super(db, options); - this.name = name; - } - - _buildCommand() { - const name = this.name; - const options = this.options; - - const cmd = { create: name }; - for (let n in options) { - if ( - options[n] != null && - typeof options[n] !== 'function' && - !ILLEGAL_COMMAND_FIELDS.has(n) - ) { - cmd[n] = options[n]; - } - } - - return cmd; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - const Collection = loadCollection(); - - let listCollectionOptions = Object.assign({ nameOnly: true, strict: false }, options); - listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); - - function done(err) { - if (err) { - return callback(err); - } - - try { - callback( - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - callback(err); - } - } - - const strictMode = listCollectionOptions.strict; - if (strictMode) { - db.listCollections({ name }, listCollectionOptions) - .setReadPreference(ReadPreference.PRIMARY) - .toArray((err, collections) => { - if (err) { - return callback(err); - } - - if (collections.length > 0) { - return callback( - new MongoError(`Collection ${name} already exists. Currently in strict mode.`) - ); - } - - super.execute(done); - }); - - return; - } - - // otherwise just execute the command - super.execute(done); - } -} - -defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); -module.exports = CreateCollectionOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/create_indexes.js b/reverse_engineering/node_modules/mongodb/lib/operations/create_indexes.js deleted file mode 100644 index 211b43c..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/create_indexes.js +++ /dev/null @@ -1,137 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; -const maxWireVersion = require('../core/utils').maxWireVersion; - -const VALID_INDEX_OPTIONS = new Set([ - 'background', - 'unique', - 'name', - 'partialFilterExpression', - 'sparse', - 'expireAfterSeconds', - 'storageEngine', - 'collation', - - // text indexes - 'weights', - 'default_language', - 'language_override', - 'textIndexVersion', - - // 2d-sphere indexes - '2dsphereIndexVersion', - - // 2d indexes - 'bits', - 'min', - 'max', - - // geoHaystack Indexes - 'bucketSize', - - // wildcard indexes - 'wildcardProjection' -]); - -class CreateIndexesOperation extends CommandOperationV2 { - /** - * @ignore - */ - constructor(parent, collection, indexes, options) { - super(parent, options); - this.collection = collection; - - // createIndex can be called with a variety of styles: - // coll.createIndex('a'); - // coll.createIndex({ a: 1 }); - // coll.createIndex([['a', 1]]); - // createIndexes is always called with an array of index spec objects - if (!Array.isArray(indexes) || Array.isArray(indexes[0])) { - this.onlyReturnNameOfCreatedIndex = true; - // TODO: remove in v4 (breaking change); make createIndex return full response as createIndexes does - - const indexParameters = parseIndexOptions(indexes); - // Generate the index name - const name = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexSpec = { name, key: indexParameters.fieldHash }; - // merge valid index options into the index spec - for (let optionName in options) { - if (VALID_INDEX_OPTIONS.has(optionName)) { - indexSpec[optionName] = options[optionName]; - } - } - this.indexes = [indexSpec]; - return; - } - - this.indexes = indexes; - } - - /** - * @ignore - */ - execute(server, callback) { - const options = this.options; - const indexes = this.indexes; - - const serverWireVersion = maxWireVersion(server); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexes.length; i++) { - // Did the user pass in a collation, check if our write server supports it - if (indexes[i].collation && serverWireVersion < 5) { - callback( - new MongoError( - `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` - ) - ); - return; - } - - if (indexes[i].name == null) { - const keys = []; - - for (let name in indexes[i].key) { - keys.push(`${name}_${indexes[i].key[name]}`); - } - - // Set the name - indexes[i].name = keys.join('_'); - } - } - - const cmd = { createIndexes: this.collection, indexes }; - - if (options.commitQuorum != null) { - if (serverWireVersion < 9) { - callback( - new MongoError('`commitQuorum` option for `createIndexes` not supported on servers < 4.4') - ); - return; - } - cmd.commitQuorum = options.commitQuorum; - } - - // collation is set on each index, it should not be defined at the root - this.options.collation = undefined; - - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } - - callback(null, this.onlyReturnNameOfCreatedIndex ? indexes[0].name : result); - }); - } -} - -defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION, Aspect.EXECUTE_WITH_SELECTION]); - -module.exports = CreateIndexesOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/cursor_ops.js b/reverse_engineering/node_modules/mongodb/lib/operations/cursor_ops.js deleted file mode 100644 index fda4c91..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/cursor_ops.js +++ /dev/null @@ -1,167 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./collection_ops').buildCountCommand; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const push = Array.prototype.push; -const CursorState = require('../core/cursor').CursorState; - -/** - * Get the count of documents for this cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to count. - * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. - * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. - * @param {Cursor~countResultCallback} [callback] The result callback. - */ -function count(cursor, applySkipLimit, opts, callback) { - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (opts.readPreference) { - cursor.setReadPreference(opts.readPreference); - } - - if ( - typeof opts.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - opts.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let options = {}; - options.skip = opts.skip; - options.limit = opts.limit; - options.hint = opts.hint; - options.maxTimeMS = opts.maxTimeMS; - - // Command - options.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, options); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); -} - -/** - * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. - * - * @method - * @deprecated - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} callback The result callback. - */ -function each(cursor, callback) { - if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); - if (cursor.isNotified()) return; - if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT) { - cursor.s.state = CursorState.OPEN; - } - - // Define function to avoid global scope escape - let fn = null; - // Trampoline all the entries - if (cursor.bufferedCount() > 0) { - while ((fn = loop(cursor, callback))) fn(cursor, callback); - each(cursor, callback); - } else { - cursor.next((err, item) => { - if (err) return handleCallback(callback, err); - if (item == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); - } - - if (handleCallback(callback, null, item) === false) return; - each(cursor, callback); - }); - } -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -function loop(cursor, callback) { - // No more items we are done - if (cursor.bufferedCount() === 0) return; - // Get the next document - cursor._next(callback); - // Loop - return loop; -} - -/** - * Returns an array of documents. See Cursor.prototype.toArray for more information. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - */ -function toArray(cursor, callback) { - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return handleCallback(callback, err); - } - - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); -} - -module.exports = { count, each, toArray }; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/db_ops.js b/reverse_engineering/node_modules/mongodb/lib/operations/db_ops.js deleted file mode 100644 index 78f1e4f..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/db_ops.js +++ /dev/null @@ -1,474 +0,0 @@ -'use strict'; - -const MONGODB_ERROR_CODES = require('../error_codes').MONGODB_ERROR_CODES; -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const extractCommand = require('../command_utils').extractCommand; -const CONSTANTS = require('../constants'); -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -/** - * Creates an index on the db and collection. - * @method - * @param {Db} db The Db instance on which to create an index. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function createIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); - finalOptions = applyWriteConcern(finalOptions, { db }, options); - - // Ensure we have a callback - if (finalOptions.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { - if (err == null) return handleCallback(callback, err, result); - - /** - * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: - * 67 = 'CannotCreateIndex' (malformed index options) - * 85 = 'IndexOptionsConflict' (index already exists with different options) - * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) - * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) - * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) - * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) - */ - if ( - err.code === MONGODB_ERROR_CODES.CannotCreateIndex || - err.code === MONGODB_ERROR_CODES.DuplicateKey || - err.code === MONGODB_ERROR_CODES.IndexOptionsConflict || - err.code === MONGODB_ERROR_CODES.IndexKeySpecsConflict || - err.code === MONGODB_ERROR_CODES.InterruptedAtShutdown || - err.code === MONGODB_ERROR_CODES.InvalidIndexSpecificationOption - ) { - return handleCallback(callback, err, result); - } - - // Create command - const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - db.s.topology.insert( - db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), - doc, - finalOptions, - (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.writeErrors) - return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - } - ); - }); -} - -// Add listeners to topology -function createListener(db, e, object) { - function listener(err) { - if (object.listeners(e).length > 0) { - object.emit(e, err, db); - - // Emit on all associated db's if available - for (let i = 0; i < db.s.children.length; i++) { - db.s.children[i].emit(e, err, db.s.children[i]); - } - } - } - return listener; -} - -/** - * Ensures that an index exists. If it does not, creates it. - * - * @method - * @param {Db} db The Db instance on which to ensure the index. - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function ensureIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern({}, { db }, options); - // Create command - const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); - const index_name = selector.name; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Merge primary readPreference - finalOptions.readPreference = ReadPreference.PRIMARY; - - // Check if the index already exists - indexInformation(db, name, finalOptions, (err, indexInformation) => { - if (err != null && err.code !== MONGODB_ERROR_CODES.NamespaceNotFound) { - return handleCallback(callback, err, null); - } - // If the index does not exist, create it - if (indexInformation == null || !indexInformation[index_name]) { - createIndex(db, name, fieldOrSpec, options, callback); - } else { - if (typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Db} db The Db instance. - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - */ -function evaluate(db, code, parameters, options, callback) { - let finalCode = code; - let finalParameters = []; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // If not a code object translate to one - if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - let cmd = { $eval: finalCode, args: finalParameters }; - // Check if the nolock parameter is passed in - if (options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new ReadPreference(ReadPreference.PRIMARY); - - // Execute the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result && result.ok === 1) return handleCallback(callback, null, result.retval); - if (result) - return handleCallback( - callback, - MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), - null - ); - handleCallback(callback, err, result); - }); -} - -/** - * Execute a command - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeCommand(db, command, options, callback) { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - options.readPreference = ReadPreference.resolve(db, options); - - // Debug information - if (db.s.logger.isDebug()) { - const extractedCommand = extractCommand(command); - db.s.logger.debug( - `executing command ${JSON.stringify( - extractedCommand.shouldRedact ? `${extractedCommand.name} details REDACTED` : command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - } - - // Execute command - db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); -} - -/** - * Runs a command on the database as admin. - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeDbAdminCommand(db, command, options, callback) { - const namespace = new MongoDBNamespace('admin', '$cmd'); - - db.s.topology.command(namespace, command, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db.collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -/** - * Retrieve the current profiling information for MongoDB - * - * @method - * @param {Db} db The Db instance on which to retrieve the profiling info. - * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - * @deprecated Query the system.profile collection directly. - */ -function profilingInfo(db, options, callback) { - try { - db.collection('system.profile') - .find({}, options) - .toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -// Validate the database name -function validateDatabaseName(databaseName) { - if (typeof databaseName !== 'string') - throw MongoError.create({ message: 'database name must be a string', driver: true }); - if (databaseName.length === 0) - throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); - if (databaseName === '$external') return; - - const invalidChars = [' ', '.', '$', '/', '\\']; - for (let i = 0; i < invalidChars.length; i++) { - if (databaseName.indexOf(invalidChars[i]) !== -1) - throw MongoError.create({ - message: "database names cannot contain the character '" + invalidChars[i] + "'", - driver: true - }); - } -} - -/** - * Create the command object for Db.prototype.createIndex. - * - * @param {Db} db The Db instance on which to create the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @return {Object} The insert command object. - */ -function createCreateIndexCommand(db, name, fieldOrSpec, options) { - const indexParameters = parseIndexOptions(fieldOrSpec); - const fieldHash = indexParameters.fieldHash; - - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - const selector = { - ns: db.s.namespace.withCollection(name).toString(), - key: fieldHash, - name: indexName - }; - - // Ensure we have a correct finalUnique - const finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options === 'boolean' ? {} : options; - - // Add all the options - const keysToOmit = Object.keys(selector); - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - selector[optionName] = options[optionName]; - } - } - - if (selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; - for (let i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -/** - * Create index using the createIndexes command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - */ -function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - const keysToOmit = Object.keys(indexes[0]).concat([ - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' - ]); - - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - indexes[0][optionName] = options[optionName]; - } - } - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Create command, apply write concern to command - const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); - - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; - - // Build the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result.ok === 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); -} - -module.exports = { - createListener, - createIndex, - ensureIndex, - evaluate, - executeCommand, - executeDbAdminCommand, - indexInformation, - profilingInfo, - validateDatabaseName -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/delete_many.js b/reverse_engineering/node_modules/mongodb/lib/operations/delete_many.js deleted file mode 100644 index 32ae500..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/delete_many.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const removeDocuments = require('./common_functions').removeDocuments; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -class DeleteManyOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = false; - removeDocuments(coll, filter, options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); - - r.deletedCount = r.result.n; - callback(null, r); - }); - } -} - -defineAspects(DeleteManyOperation, [Aspect.EXPLAINABLE]); - -module.exports = DeleteManyOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/delete_one.js b/reverse_engineering/node_modules/mongodb/lib/operations/delete_one.js deleted file mode 100644 index 9aec05b..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/delete_one.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const removeDocuments = require('./common_functions').removeDocuments; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -class DeleteOneOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = true; - removeDocuments(coll, filter, options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); - - r.deletedCount = r.result.n; - callback(null, r); - }); - } -} - -defineAspects(DeleteOneOperation, [Aspect.EXPLAINABLE]); - -module.exports = DeleteOneOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/distinct.js b/reverse_engineering/node_modules/mongodb/lib/operations/distinct.js deleted file mode 100644 index fcac930..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/distinct.js +++ /dev/null @@ -1,93 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const maxWireVersion = require('../core/utils').maxWireVersion; -const MongoError = require('../error').MongoError; - -/** - * Return a list of distinct values for the given key across a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {string} key Field of the document to find distinct values for. - * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ -class DistinctOperation extends CommandOperationV2 { - /** - * Construct a Distinct operation. - * - * @param {Collection} a Collection instance. - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ - constructor(collection, key, query, options) { - super(collection, options); - - this.collection = collection; - this.key = key; - this.query = query; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(server, callback) { - const coll = this.collection; - const key = this.key; - const query = this.query; - const options = this.options; - - // Distinct command - const cmd = { - distinct: coll.collectionName, - key: key, - query: query - }; - - // Add maxTimeMS if defined - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, coll, options); - - // Have we specified collation - try { - decorateWithCollation(cmd, coll, options); - } catch (err) { - return callback(err, null); - } - - if (this.explain && maxWireVersion(server) < 4) { - callback(new MongoError(`server does not support explain on distinct`)); - return; - } - - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } - - callback(null, this.options.full || this.explain ? result : result.values); - }); - } -} - -defineAspects(DistinctOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.EXPLAINABLE -]); - -module.exports = DistinctOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/drop.js b/reverse_engineering/node_modules/mongodb/lib/operations/drop.js deleted file mode 100644 index be03716..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/drop.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; - -class DropOperation extends CommandOperation { - constructor(db, options) { - const finalOptions = Object.assign({}, options, db.s.options); - - if (options.session) { - finalOptions.session = options.session; - } - - super(db, finalOptions); - } - - execute(callback) { - super.execute((err, result) => { - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - } -} - -defineAspects(DropOperation, Aspect.WRITE_OPERATION); - -class DropCollectionOperation extends DropOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - this.namespace = `${db.namespace}.${name}`; - } - - _buildCommand() { - return { drop: this.name }; - } -} - -class DropDatabaseOperation extends DropOperation { - _buildCommand() { - return { dropDatabase: 1 }; - } -} - -module.exports = { - DropOperation, - DropCollectionOperation, - DropDatabaseOperation -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/drop_index.js b/reverse_engineering/node_modules/mongodb/lib/operations/drop_index.js deleted file mode 100644 index a6ca783..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/drop_index.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; - -class DropIndexOperation extends CommandOperation { - constructor(collection, indexName, options) { - super(collection.s.db, options, collection); - - this.collection = collection; - this.indexName = indexName; - } - - _buildCommand() { - const collection = this.collection; - const indexName = this.indexName; - const options = this.options; - - let cmd = { dropIndexes: collection.collectionName, index: indexName }; - - // Decorate command with writeConcern if supported - cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); - - return cmd; - } - - execute(callback) { - // Execute command - super.execute((err, result) => { - if (typeof callback !== 'function') return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); - } -} - -defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/drop_indexes.js b/reverse_engineering/node_modules/mongodb/lib/operations/drop_indexes.js deleted file mode 100644 index ed404ee..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/drop_indexes.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const DropIndexOperation = require('./drop_index'); -const handleCallback = require('../utils').handleCallback; - -class DropIndexesOperation extends DropIndexOperation { - constructor(collection, options) { - super(collection, '*', options); - } - - execute(callback) { - super.execute(err => { - if (err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); - } -} - -defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexesOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/estimated_document_count.js b/reverse_engineering/node_modules/mongodb/lib/operations/estimated_document_count.js deleted file mode 100644 index 1def94d..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/estimated_document_count.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -const MONGODB_ERROR_CODES = require('../error_codes').MONGODB_ERROR_CODES; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const maxWireVersion = require('../core/utils').maxWireVersion; -const CountDocumentsOperation = require('./count_documents'); - -class EstimatedDocumentCountOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options); - this.collection = collection; - this.collectionName = collection.s.namespace.collection; - } - - execute(server, callback) { - if (maxWireVersion(server) < 12) { - return this.executeLegacy(server, callback); - } - // if the user specifies a filter, use a CountDocumentsOperation instead - if (this.options.query) { - const op = new CountDocumentsOperation(this.collection, this.options.query, this.options); - return op.execute(server, callback); - } - const pipeline = [{ $collStats: { count: {} } }, { $group: { _id: 1, n: { $sum: '$count' } } }]; - const cmd = { aggregate: this.collectionName, pipeline, cursor: {} }; - - if (typeof this.options.maxTimeMS === 'number') { - cmd.maxTimeMS = this.options.maxTimeMS; - } - - super.executeCommand(server, cmd, (err, response) => { - if (err && err.code !== MONGODB_ERROR_CODES.NamespaceNotFound) { - callback(err); - return; - } - - callback( - undefined, - (response && - response.cursor && - response.cursor.firstBatch && - response.cursor.firstBatch[0].n) || - 0 - ); - }); - } - - executeLegacy(server, callback) { - const cmd = { count: this.collectionName }; - - const options = this.options; - if (options.query) { - cmd.query = options.query; - } - if (options.hint) { - cmd.hint = options.hint; - } - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - if (typeof options.skip === 'number') { - cmd.skip = options.skip; - } - if (typeof options.limit === 'number') { - cmd.limit = options.limit; - } - - super.executeCommand(server, cmd, (err, response) => { - if (err) { - callback(err); - return; - } - - callback(null, response.n); - }); - } -} - -defineAspects(EstimatedDocumentCountOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = EstimatedDocumentCountOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/execute_db_admin_command.js b/reverse_engineering/node_modules/mongodb/lib/operations/execute_db_admin_command.js deleted file mode 100644 index d15fc8e..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/execute_db_admin_command.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ExecuteDbAdminCommandOperation extends OperationBase { - constructor(db, selector, options) { - super(options); - - this.db = db; - this.selector = selector; - } - - execute(callback) { - const db = this.db; - const selector = this.selector; - const options = this.options; - - const namespace = new MongoDBNamespace('admin', '$cmd'); - db.s.topology.command(namespace, selector, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = ExecuteDbAdminCommandOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/execute_operation.js b/reverse_engineering/node_modules/mongodb/lib/operations/execute_operation.js deleted file mode 100644 index c225598..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/execute_operation.js +++ /dev/null @@ -1,164 +0,0 @@ -'use strict'; - -const maybePromise = require('../utils').maybePromise; -const MongoError = require('../core/error').MongoError; -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const ReadPreference = require('../core/topologies/read_preference'); -const isRetryableError = require('../core/error').isRetryableError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const isUnifiedTopology = require('../core/utils').isUnifiedTopology; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {Operation} operation The operation to execute - * @param {function} callback The command result callback - */ -function executeOperation(topology, operation, cb) { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!(operation instanceof OperationBase)) { - throw new TypeError('This method requires a valid operation instance'); - } - - return maybePromise(topology, cb, callback => { - if (isUnifiedTopology(topology) && topology.shouldCheckForSessionSupport()) { - // Recursive call to executeOperation after a server selection - return selectServerForSessionSupport(topology, operation, callback); - } - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, owner; - if (topology.hasSessionSupport()) { - if (operation.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - operation.session = session; - } else if (operation.session.hasEnded) { - return callback(new MongoError('Use of expired sessions is not permitted')); - } - } else if (operation.session) { - // If the user passed an explicit session and we are still, after server selection, - // trying to run against a topology that doesn't support sessions we error out. - return callback(new MongoError('Current topology does not support sessions')); - } - - function executeCallback(err, result) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } - - callback(err, result); - } - - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - executeWithServerSelection(topology, operation, executeCallback); - } else { - operation.execute(executeCallback); - } - } catch (error) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } - - callback(error); - } - }); -} - -function supportsRetryableReads(server) { - return maxWireVersion(server) >= 6; -} - -function executeWithServerSelection(topology, operation, callback) { - const readPreference = operation.readPreference || ReadPreference.primary; - const inTransaction = operation.session && operation.session.inTransaction(); - - if (inTransaction && !readPreference.equals(ReadPreference.primary)) { - callback( - new MongoError( - `Read preference in a transaction must be primary, not: ${readPreference.mode}` - ) - ); - - return; - } - - const serverSelectionOptions = { - readPreference, - session: operation.session - }; - - function callbackWithRetry(err, result) { - if (err == null) { - return callback(null, result); - } - - if (!isRetryableError(err)) { - return callback(err); - } - - // select a new server, and attempt to retry the operation - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err || !supportsRetryableReads(server)) { - callback(err, null); - return; - } - - operation.execute(server, callback); - }); - } - - // select a server, and execute the operation against it - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err) { - callback(err, null); - return; - } - const shouldRetryReads = - topology.s.options.retryReads !== false && - operation.session && - !inTransaction && - supportsRetryableReads(server) && - operation.canRetryRead; - - if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { - operation.execute(server, callbackWithRetry); - return; - } - - operation.execute(server, callback); - }); -} - -// The Unified Topology runs serverSelection before executing every operation -// Session support is determined by the result of a monitoring check triggered by this selection -function selectServerForSessionSupport(topology, operation, callback) { - topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - return callback(err); - } - - executeOperation(topology, operation, callback); - }); -} - -module.exports = executeOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/find.js b/reverse_engineering/node_modules/mongodb/lib/operations/find.js deleted file mode 100644 index 97ecdb8..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/find.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const ReadPreference = require('../core').ReadPreference; -const maxWireVersion = require('../core/utils').maxWireVersion; -const MongoError = require('../core/error').MongoError; - -class FindOperation extends OperationBase { - constructor(collection, ns, command, options) { - super(options); - - this.ns = ns; - this.cmd = command; - this.readPreference = ReadPreference.resolve(collection, this.options); - } - - execute(server, callback) { - // copied from `CommandOperationV2`, to be subclassed in the future - this.server = server; - - // updates readPreference if setReadPreference was called on the cursor - this.readPreference = ReadPreference.resolve(this, this.options); - - if (typeof this.cmd.allowDiskUse !== 'undefined' && maxWireVersion(server) < 4) { - callback(new MongoError('The `allowDiskUse` option is not supported on MongoDB < 3.2')); - return; - } - - if (this.explain) { - // We need to manually ensure explain is in the options. - this.options.explain = this.explain.verbosity; - } - - // TOOD: use `MongoDBNamespace` through and through - const cursorState = this.cursorState || {}; - server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); - } -} - -defineAspects(FindOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.EXPLAINABLE -]); - -module.exports = FindOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/find_and_modify.js b/reverse_engineering/node_modules/mongodb/lib/operations/find_and_modify.js deleted file mode 100644 index 3886688..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/find_and_modify.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const ReadPreference = require('../core').ReadPreference; -const maxWireVersion = require('../core/utils').maxWireVersion; -const MongoError = require('../error').MongoError; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const decorateWithExplain = require('../utils').decorateWithExplain; - -class FindAndModifyOperation extends OperationBase { - constructor(collection, query, sort, doc, options) { - super(options); - - this.collection = collection; - this.query = query; - this.sort = sort; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const sort = formattedOrderClause(this.sort); - const doc = this.doc; - let options = this.options; - - // Create findAndModify command object - let queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - options = applyRetryableWrites(options, coll.s.db); - options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (options.writeConcern) { - queryObject.writeConcern = options.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (options.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = options.bypassDocumentValidation; - } - - options.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, options); - } catch (err) { - return callback(err, null); - } - - if (options.hint) { - // TODO: once this method becomes a CommandOperationV2 we will have the server - // in place to check. - const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0; - if (unacknowledgedWrite || maxWireVersion(coll.s.topology) < 8) { - callback( - new MongoError('The current topology does not support a hint on findAndModify commands') - ); - - return; - } - - queryObject.hint = options.hint; - } - - if (this.explain) { - if (maxWireVersion(coll.s.topology) < 4) { - callback(new MongoError(`server does not support explain on findAndModify`)); - return; - } - queryObject = decorateWithExplain(queryObject, this.explain); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); - } -} - -defineAspects(FindAndModifyOperation, [Aspect.EXPLAINABLE]); - -module.exports = FindAndModifyOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/find_one.js b/reverse_engineering/node_modules/mongodb/lib/operations/find_one.js deleted file mode 100644 index 3e4b3cf..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/find_one.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const handleCallback = require('../utils').handleCallback; -const OperationBase = require('./operation').OperationBase; -const toError = require('../utils').toError; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -class FindOneOperation extends OperationBase { - constructor(collection, query, options) { - super(options); - - this.collection = collection; - this.query = query; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const options = this.options; - - try { - const cursor = coll - .find(query, options) - .limit(-1) - .batchSize(1); - - // Return the item - cursor.next((err, item) => { - if (err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); - } catch (e) { - callback(e); - } - } -} - -defineAspects(FindOneOperation, [Aspect.EXPLAINABLE]); - -module.exports = FindOneOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_delete.js b/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_delete.js deleted file mode 100644 index eaf3287..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_delete.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndDeleteOperation extends FindAndModifyOperation { - constructor(collection, filter, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.remove = true; - - // Basic validation - if (filter == null || typeof filter !== 'object') { - throw new TypeError('Filter parameter must be an object'); - } - - super(collection, filter, finalOptions.sort, null, finalOptions); - } -} - -module.exports = FindOneAndDeleteOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_replace.js b/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_replace.js deleted file mode 100644 index 3720bae..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_replace.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -const MongoError = require('../core').MongoError; -const FindAndModifyOperation = require('./find_and_modify'); -const hasAtomicOperators = require('../utils').hasAtomicOperators; - -class FindOneAndReplaceOperation extends FindAndModifyOperation { - constructor(collection, filter, replacement, options) { - if ('returnDocument' in options && 'returnOriginal' in options) { - throw new MongoError( - 'findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined' - ); - } - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = options.returnDocument === 'after' || options.returnOriginal === false; - finalOptions.upsert = options.upsert === true; - - if (filter == null || typeof filter !== 'object') { - throw new TypeError('Filter parameter must be an object'); - } - - if (replacement == null || typeof replacement !== 'object') { - throw new TypeError('Replacement parameter must be an object'); - } - - if (hasAtomicOperators(replacement)) { - throw new TypeError('Replacement document must not contain atomic operators'); - } - - super(collection, filter, finalOptions.sort, replacement, finalOptions); - } -} - -module.exports = FindOneAndReplaceOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_update.js b/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_update.js deleted file mode 100644 index 9408aca..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/find_one_and_update.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -const MongoError = require('../core').MongoError; -const FindAndModifyOperation = require('./find_and_modify'); -const hasAtomicOperators = require('../utils').hasAtomicOperators; - -class FindOneAndUpdateOperation extends FindAndModifyOperation { - constructor(collection, filter, update, options) { - if ('returnDocument' in options && 'returnOriginal' in options) { - throw new MongoError( - 'findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined' - ); - } - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = options.returnDocument === 'after' || options.returnOriginal === false; - finalOptions.upsert = options.upsert === true; - - if (filter == null || typeof filter !== 'object') { - throw new TypeError('Filter parameter must be an object'); - } - - if (update == null || typeof update !== 'object') { - throw new TypeError('Update parameter must be an object'); - } - - if (!hasAtomicOperators(update)) { - throw new TypeError('Update document requires atomic operators'); - } - - super(collection, filter, finalOptions.sort, update, finalOptions); - } -} - -module.exports = FindOneAndUpdateOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/geo_haystack_search.js b/reverse_engineering/node_modules/mongodb/lib/operations/geo_haystack_search.js deleted file mode 100644 index 7c8654d..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/geo_haystack_search.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const decorateCommand = require('../utils').decorateCommand; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ -class GeoHaystackSearchOperation extends OperationBase { - /** - * Construct a GeoHaystackSearch operation. - * - * @param {Collection} a Collection instance. - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ - constructor(collection, x, y, options) { - super(options); - - this.collection = collection; - this.x = x; - this.y = y; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const x = this.x; - const y = this.y; - let options = this.options; - - // Build command object - let commandObject = { - geoSearch: coll.collectionName, - near: [x, y] - }; - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = ReadPreference.resolve(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, res) => { - if (err) return handleCallback(callback, err); - if (res.err || res.errmsg) handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); - } -} - -defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); - -module.exports = GeoHaystackSearchOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/index_exists.js b/reverse_engineering/node_modules/mongodb/lib/operations/index_exists.js deleted file mode 100644 index bd9dc0e..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/index_exists.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; - -class IndexExistsOperation extends OperationBase { - constructor(collection, indexes, options) { - super(options); - - this.collection = collection; - this.indexes = indexes; - } - - execute(callback) { - const coll = this.collection; - const indexes = this.indexes; - const options = this.options; - - indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); - } -} - -module.exports = IndexExistsOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/index_information.js b/reverse_engineering/node_modules/mongodb/lib/operations/index_information.js deleted file mode 100644 index b18a603..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/index_information.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexInformationOperation extends OperationBase { - constructor(db, name, options) { - super(options); - - this.db = db; - this.name = name; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - indexInformation(db, name, options, callback); - } -} - -module.exports = IndexInformationOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/indexes.js b/reverse_engineering/node_modules/mongodb/lib/operations/indexes.js deleted file mode 100644 index e29a88a..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/indexes.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexesOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - let options = this.options; - - options = Object.assign({}, { full: true }, options); - indexInformation(coll.s.db, coll.collectionName, options, callback); - } -} - -module.exports = IndexesOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/insert_many.js b/reverse_engineering/node_modules/mongodb/lib/operations/insert_many.js deleted file mode 100644 index fdfc0d4..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/insert_many.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const BulkWriteOperation = require('./bulk_write'); -const MongoError = require('../core').MongoError; -const prepareDocs = require('./common_functions').prepareDocs; - -class InsertManyOperation extends OperationBase { - constructor(collection, docs, options) { - super(options); - - this.collection = collection; - this.docs = docs; - } - - execute(callback) { - const coll = this.collection; - let docs = this.docs; - const options = this.options; - - if (!Array.isArray(docs)) { - return callback( - MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) - ); - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // Generate the bulk write operations - const operations = docs.map(document => ({ insertOne: { document } })); - - const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); - - bulkWriteOperation.execute((err, result) => { - if (err) return callback(err, null); - callback(null, mapInsertManyResults(docs, result)); - }); - } -} - -function mapInsertManyResults(docs, r) { - const finalResult = { - result: { ok: 1, n: r.insertedCount }, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: r.insertedIds - }; - - if (r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } - - return finalResult; -} - -module.exports = InsertManyOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/insert_one.js b/reverse_engineering/node_modules/mongodb/lib/operations/insert_one.js deleted file mode 100644 index 5e70880..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/insert_one.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; -const insertDocuments = require('./common_functions').insertDocuments; - -class InsertOneOperation extends OperationBase { - constructor(collection, doc, options) { - super(options); - - this.collection = collection; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const doc = this.doc; - const options = this.options; - - if (Array.isArray(doc)) { - return callback( - MongoError.create({ message: 'doc parameter must be an object', driver: true }) - ); - } - - insertDocuments(coll, [doc], options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - // Workaround for pre 2.6 servers - if (r == null) return callback(null, { result: { ok: 1 } }); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if (callback) callback(null, r); - }); - } -} - -module.exports = InsertOneOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/is_capped.js b/reverse_engineering/node_modules/mongodb/lib/operations/is_capped.js deleted file mode 100644 index 3bfd9ff..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/is_capped.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const OptionsOperation = require('./options_operation'); -const handleCallback = require('../utils').handleCallback; - -class IsCappedOperation extends OptionsOperation { - constructor(collection, options) { - super(collection, options); - } - - execute(callback) { - super.execute((err, document) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, !!(document && document.capped)); - }); - } -} - -module.exports = IsCappedOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/list_collections.js b/reverse_engineering/node_modules/mongodb/lib/operations/list_collections.js deleted file mode 100644 index ee01d31..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/list_collections.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; -const CONSTANTS = require('../constants'); - -const LIST_COLLECTIONS_WIRE_VERSION = 3; - -function listCollectionsTransforms(databaseName) { - const matching = `${databaseName}.`; - - return { - doc: doc => { - const index = doc.name.indexOf(matching); - // Remove database name if available - if (doc.name && index === 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; - } - }; -} - -class ListCollectionsOperation extends CommandOperationV2 { - constructor(db, filter, options) { - super(db, options, { fullResponse: true }); - - this.db = db; - this.filter = filter; - this.nameOnly = !!this.options.nameOnly; - - if (typeof this.options.batchSize === 'number') { - this.batchSize = this.options.batchSize; - } - } - - execute(server, callback) { - if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { - let filter = this.filter; - const databaseName = this.db.s.namespace.db; - - // If we have legacy mode and have not provided a full db name filter it - if ( - typeof filter.name === 'string' && - !new RegExp('^' + databaseName + '\\.').test(filter.name) - ) { - filter = Object.assign({}, filter); - filter.name = this.db.s.namespace.withCollection(filter.name).toString(); - } - - // No filter, filter by current database - if (filter == null) { - filter.name = `/${databaseName}/`; - } - - // Rewrite the filter to use $and to filter out indexes - if (filter.name) { - filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; - } else { - filter = { name: /^((?!\$).)*$/ }; - } - - const transforms = listCollectionsTransforms(databaseName); - server.query( - `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, - { query: filter }, - { batchSize: this.batchSize || 1000 }, - {}, - (err, result) => { - if ( - result && - result.message && - result.message.documents && - Array.isArray(result.message.documents) - ) { - result.message.documents = result.message.documents.map(transforms.doc); - } - - callback(err, result); - } - ); - - return; - } - - const command = { - listCollections: 1, - filter: this.filter, - cursor: this.batchSize ? { batchSize: this.batchSize } : {}, - nameOnly: this.nameOnly - }; - - return super.executeCommand(server, command, callback); - } -} - -defineAspects(ListCollectionsOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListCollectionsOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/list_databases.js b/reverse_engineering/node_modules/mongodb/lib/operations/list_databases.js deleted file mode 100644 index 62b2606..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/list_databases.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ListDatabasesOperation extends CommandOperationV2 { - constructor(db, options) { - super(db, options); - this.ns = new MongoDBNamespace('admin', '$cmd'); - } - - execute(server, callback) { - const cmd = { listDatabases: 1 }; - if (this.options.nameOnly) { - cmd.nameOnly = Number(cmd.nameOnly); - } - - if (this.options.filter) { - cmd.filter = this.options.filter; - } - - if (typeof this.options.authorizedDatabases === 'boolean') { - cmd.authorizedDatabases = this.options.authorizedDatabases; - } - - super.executeCommand(server, cmd, callback); - } -} - -defineAspects(ListDatabasesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListDatabasesOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/list_indexes.js b/reverse_engineering/node_modules/mongodb/lib/operations/list_indexes.js deleted file mode 100644 index 302a31b..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/list_indexes.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; - -const LIST_INDEXES_WIRE_VERSION = 3; - -class ListIndexesOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options, { fullResponse: true }); - - this.collectionNamespace = collection.s.namespace; - } - - execute(server, callback) { - const serverWireVersion = maxWireVersion(server); - if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { - const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); - const collectionNS = this.collectionNamespace.toString(); - - server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); - return; - } - - const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; - super.executeCommand( - server, - { listIndexes: this.collectionNamespace.collection, cursor }, - callback - ); - } -} - -defineAspects(ListIndexesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListIndexesOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/map_reduce.js b/reverse_engineering/node_modules/mongodb/lib/operations/map_reduce.js deleted file mode 100644 index 3a2cf26..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/map_reduce.js +++ /dev/null @@ -1,209 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const isObject = require('../utils').isObject; -const loadDb = require('../dynamic_loaders').loadDb; -const OperationBase = require('./operation').OperationBase; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const decorateWithExplain = require('../utils').decorateWithExplain; -const maxWireVersion = require('../core/utils').maxWireVersion; -const MongoError = require('../error').MongoError; - -const exclusionList = [ - 'explain', - 'readPreference', - 'session', - 'bypassDocumentValidation', - 'w', - 'wtimeout', - 'j', - 'writeConcern' -]; - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {(function|string)} map The mapping function. - * @property {(function|string)} reduce The reduce function. - * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ -class MapReduceOperation extends OperationBase { - /** - * Constructs a MapReduce operation. - * - * @param {Collection} a Collection instance. - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ - constructor(collection, map, reduce, options) { - super(options); - - this.collection = collection; - this.map = map; - this.reduce = reduce; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const map = this.map; - const reduce = this.reduce; - let options = this.options; - - let mapCommandHash = { - mapReduce: coll.collectionName, - map: map, - reduce: reduce - }; - - // Add any other options passed in - for (let n in options) { - if ('scope' === n) { - mapCommandHash[n] = processScope(options[n]); - } else { - // Only include if not in exclusion list - if (exclusionList.indexOf(n) === -1) { - mapCommandHash[n] = options[n]; - } - } - } - - options = Object.assign({}, options); - - // Ensure we have the right read preference inheritance - options.readPreference = ReadPreference.resolve(coll, options); - - // If we have a read preference and inline is not set as output fail hard - if ( - options.readPreference !== false && - options.readPreference !== 'primary' && - options['out'] && - options['out'].inline !== 1 && - options['out'] !== 'inline' - ) { - // Force readPreference to primary - options.readPreference = 'primary'; - // Decorate command with writeConcern if supported - applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); - } else { - decorateWithReadConcern(mapCommandHash, coll, options); - } - - // Is bypassDocumentValidation specified - if (options.bypassDocumentValidation === true) { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Have we specified collation - try { - decorateWithCollation(mapCommandHash, coll, options); - } catch (err) { - return callback(err, null); - } - - if (this.explain) { - if (maxWireVersion(coll.s.topology) < 9) { - callback(new MongoError(`server does not support explain on mapReduce`)); - return; - } - mapCommandHash = decorateWithExplain(mapCommandHash, this.explain); - } - - // Execute command - executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { - if (err) return handleCallback(callback, err); - // Check if we have an error - if (1 !== result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); - } - - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, result); - - // Create statistics value - const stats = {}; - if (result.timeMillis) stats['processtime'] = result.timeMillis; - if (result.counts) stats['counts'] = result.counts; - if (result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if (result.results) { - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, { results: result.results, stats: stats }); - } - - // The returned collection - let collection = null; - - // If we have an object it's a different db - if (result.result != null && typeof result.result === 'object') { - const doc = result.result; - // Return a collection from another db - let Db = loadDb(); - collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( - doc.collection - ); - } else { - // Create a collection object that wraps the result collection - collection = coll.s.db.collection(result.result); - } - - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); - } - - // Return stats as third set of values - handleCallback(callback, err, { collection: collection, stats: stats }); - }); - } -} - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope(scope) { - if (!isObject(scope) || scope._bsontype === 'ObjectID') { - return scope; - } - - const keys = Object.keys(scope); - let key; - const new_scope = {}; - - for (let i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if ('function' === typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -defineAspects(MapReduceOperation, [Aspect.EXPLAINABLE]); - -module.exports = MapReduceOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/operation.js b/reverse_engineering/node_modules/mongodb/lib/operations/operation.js deleted file mode 100644 index 94ccd81..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/operation.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -const Explain = require('../explain').Explain; -const MongoError = require('../core/error').MongoError; - -const Aspect = { - READ_OPERATION: Symbol('READ_OPERATION'), - WRITE_OPERATION: Symbol('WRITE_OPERATION'), - RETRYABLE: Symbol('RETRYABLE'), - EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION'), - NO_INHERIT_OPTIONS: Symbol('NO_INHERIT_OPTIONS'), - EXPLAINABLE: Symbol('EXPLAINABLE') -}; - -/** - * This class acts as a parent class for any operation and is responsible for setting this.options, - * as well as setting and getting a session. - * Additionally, this class implements `hasAspect`, which determines whether an operation has - * a specific aspect. - */ -class OperationBase { - constructor(options) { - this.options = Object.assign({}, options); - - if (this.hasAspect(Aspect.EXPLAINABLE)) { - this.explain = Explain.fromOptions(options); - } else if (this.options.explain !== undefined) { - throw new MongoError(`explain is not supported on this command`); - } - } - - hasAspect(aspect) { - if (this.constructor.aspects == null) { - return false; - } - return this.constructor.aspects.has(aspect); - } - - set session(session) { - Object.assign(this.options, { session }); - } - - get session() { - return this.options.session; - } - - clearSession() { - delete this.options.session; - } - - get canRetryRead() { - return true; - } - - execute() { - throw new TypeError('`execute` must be implemented for OperationBase subclasses'); - } -} - -function defineAspects(operation, aspects) { - if (!Array.isArray(aspects) && !(aspects instanceof Set)) { - aspects = [aspects]; - } - aspects = new Set(aspects); - Object.defineProperty(operation, 'aspects', { - value: aspects, - writable: false - }); - return aspects; -} - -module.exports = { - Aspect, - defineAspects, - OperationBase -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/options_operation.js b/reverse_engineering/node_modules/mongodb/lib/operations/options_operation.js deleted file mode 100644 index 9a739a5..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/options_operation.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; - -class OptionsOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - const opts = this.options; - - coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { - if (err) return handleCallback(callback, err); - if (collections.length === 0) { - return handleCallback( - callback, - MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) - ); - } - - handleCallback(callback, err, collections[0].options || null); - }); - } -} - -module.exports = OptionsOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/profiling_level.js b/reverse_engineering/node_modules/mongodb/lib/operations/profiling_level.js deleted file mode 100644 index 3f7639b..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/profiling_level.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ProfilingLevelOperation extends CommandOperation { - constructor(db, command, options) { - super(db, options); - } - - _buildCommand() { - const command = { profile: -1 }; - - return command; - } - - execute(callback) { - super.execute((err, doc) => { - if (err == null && doc.ok === 1) { - const was = doc.was; - if (was === 0) return callback(null, 'off'); - if (was === 1) return callback(null, 'slow_only'); - if (was === 2) return callback(null, 'all'); - return callback(new Error('Error: illegal profiling level value ' + was), null); - } else { - err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); - } - }); - } -} - -module.exports = ProfilingLevelOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/re_index.js b/reverse_engineering/node_modules/mongodb/lib/operations/re_index.js deleted file mode 100644 index dc44522..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/re_index.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const serverType = require('../core/sdam/common').serverType; -const ServerType = require('../core/sdam/common').ServerType; -const MongoError = require('../core').MongoError; - -class ReIndexOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options); - this.collectionName = collection.collectionName; - } - - execute(server, callback) { - if (serverType(server) !== ServerType.Standalone) { - callback(new MongoError(`reIndex can only be executed on standalone servers.`)); - return; - } - super.executeCommand(server, { reIndex: this.collectionName }, (err, result) => { - if (err) { - callback(err); - return; - } - callback(null, !!result.ok); - }); - } -} - -defineAspects(ReIndexOperation, [Aspect.EXECUTE_WITH_SELECTION]); - -module.exports = ReIndexOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/remove_user.js b/reverse_engineering/node_modules/mongodb/lib/operations/remove_user.js deleted file mode 100644 index 9e8376b..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/remove_user.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const WriteConcern = require('../write_concern'); - -class RemoveUserOperation extends CommandOperation { - constructor(db, username, options) { - const commandOptions = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern != null) { - commandOptions.writeConcern = writeConcern; - } - - if (options.dbName) { - commandOptions.dbName = options.dbName; - } - - // Add maxTimeMS to options if set - if (typeof options.maxTimeMS === 'number') { - commandOptions.maxTimeMS = options.maxTimeMS; - } - - super(db, commandOptions); - - this.username = username; - } - - _buildCommand() { - const username = this.username; - - // Build the command to execute - const command = { dropUser: username }; - - return command; - } - - execute(callback) { - // Attempt to execute command - super.execute((err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, err, result.ok ? true : false); - }); - } -} - -defineAspects(RemoveUserOperation, Aspect.WRITE_OPERATION); - -module.exports = RemoveUserOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/rename.js b/reverse_engineering/node_modules/mongodb/lib/operations/rename.js deleted file mode 100644 index 8098fe6..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/rename.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const checkCollectionName = require('../utils').checkCollectionName; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const toError = require('../utils').toError; - -class RenameOperation extends OperationBase { - constructor(collection, newName, options) { - super(options); - - this.collection = collection; - this.newName = newName; - } - - execute(callback) { - const coll = this.collection; - const newName = this.newName; - const options = this.options; - - let Collection = loadCollection(); - // Check the collection name - checkCollectionName(newName); - // Build the command - const renameCollection = coll.namespace; - const toCollection = coll.s.namespace.withCollection(newName).toString(); - const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; - const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); - - // Execute against admin - executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { - if (err) return handleCallback(callback, err, null); - // We have an error - if (doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback( - callback, - null, - new Collection( - coll.s.db, - coll.s.topology, - coll.s.namespace.db, - newName, - coll.s.pkFactory, - coll.s.options - ) - ); - } catch (err) { - return handleCallback(callback, toError(err), null); - } - }); - } -} - -module.exports = RenameOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/replace_one.js b/reverse_engineering/node_modules/mongodb/lib/operations/replace_one.js deleted file mode 100644 index 93ec0ef..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/replace_one.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; -const hasAtomicOperators = require('../utils').hasAtomicOperators; - -class ReplaceOneOperation extends OperationBase { - constructor(collection, filter, replacement, options) { - super(options); - - if (hasAtomicOperators(replacement)) { - throw new TypeError('Replacement document must not contain atomic operators'); - } - - this.collection = collection; - this.filter = filter; - this.replacement = replacement; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const replacement = this.replacement; - const options = this.options; - - // Set single document update - options.multi = false; - - // Execute update - updateDocuments(coll, filter, replacement, options, (err, r) => - replaceCallback(err, r, replacement, callback) - ); - } -} - -function replaceCallback(err, r, doc, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - r.ops = [doc]; // TODO: Should we still have this? - if (callback) callback(null, r); -} - -module.exports = ReplaceOneOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/run_command.js b/reverse_engineering/node_modules/mongodb/lib/operations/run_command.js deleted file mode 100644 index 5525ba2..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/run_command.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const defineAspects = require('./operation').defineAspects; -const Aspect = require('./operation').Aspect; - -class RunCommandOperation extends CommandOperationV2 { - constructor(parent, command, options) { - super(parent, options); - this.command = command; - } - execute(server, callback) { - const command = this.command; - this.executeCommand(server, command, callback); - } -} -defineAspects(RunCommandOperation, [Aspect.EXECUTE_WITH_SELECTION, Aspect.NO_INHERIT_OPTIONS]); - -module.exports = RunCommandOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/set_profiling_level.js b/reverse_engineering/node_modules/mongodb/lib/operations/set_profiling_level.js deleted file mode 100644 index b31cc13..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/set_profiling_level.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const levelValues = new Set(['off', 'slow_only', 'all']); - -class SetProfilingLevelOperation extends CommandOperation { - constructor(db, level, options) { - let profile = 0; - - if (level === 'off') { - profile = 0; - } else if (level === 'slow_only') { - profile = 1; - } else if (level === 'all') { - profile = 2; - } - - super(db, options); - this.level = level; - this.profile = profile; - } - - _buildCommand() { - const profile = this.profile; - - // Set up the profile number - const command = { profile }; - - return command; - } - - execute(callback) { - const level = this.level; - - if (!levelValues.has(level)) { - return callback(new Error('Error: illegal profiling level value ' + level)); - } - - super.execute((err, doc) => { - if (err == null && doc.ok === 1) return callback(null, level); - return err != null - ? callback(err, null) - : callback(new Error('Error with profile command'), null); - }); - } -} - -module.exports = SetProfilingLevelOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/stats.js b/reverse_engineering/node_modules/mongodb/lib/operations/stats.js deleted file mode 100644 index ff79126..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/stats.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; - -/** - * Get all the collection statistics. - * - * @class - * @property {Collection} a Collection instance. - * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ -class StatsOperation extends CommandOperation { - /** - * Construct a Stats operation. - * - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - const options = this.options; - - // Build command object - const command = { - collStats: collection.collectionName - }; - - // Check if we have the scale value - if (options['scale'] != null) { - command['scale'] = options['scale']; - } - - return command; - } -} - -defineAspects(StatsOperation, Aspect.READ_OPERATION); - -module.exports = StatsOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/update_many.js b/reverse_engineering/node_modules/mongodb/lib/operations/update_many.js deleted file mode 100644 index 6d2252d..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/update_many.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; -const hasAtomicOperators = require('../utils').hasAtomicOperators; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -class UpdateManyOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - if (!hasAtomicOperators(update)) { - throw new TypeError('Update document requires atomic operators'); - } - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = true; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); - }); - } -} - -defineAspects(UpdateManyOperation, [Aspect.EXPLAINABLE]); - -module.exports = UpdateManyOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/update_one.js b/reverse_engineering/node_modules/mongodb/lib/operations/update_one.js deleted file mode 100644 index e05cb93..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/update_one.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; -const hasAtomicOperators = require('../utils').hasAtomicOperators; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -class UpdateOneOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - if (!hasAtomicOperators(update)) { - throw new TypeError('Update document requires atomic operators'); - } - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = false; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); - }); - } -} - -defineAspects(UpdateOneOperation, [Aspect.EXPLAINABLE]); - -module.exports = UpdateOneOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/operations/validate_collection.js b/reverse_engineering/node_modules/mongodb/lib/operations/validate_collection.js deleted file mode 100644 index bc16cd2..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/operations/validate_collection.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ValidateCollectionOperation extends CommandOperation { - constructor(admin, collectionName, options) { - // Decorate command with extra options - let command = { validate: collectionName }; - const keys = Object.keys(options); - for (let i = 0; i < keys.length; i++) { - if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - super(admin.s.db, options, null, command); - this.collectionName = collectionName; - } - - execute(callback) { - const collectionName = this.collectionName; - - super.execute((err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); - } -} - -module.exports = ValidateCollectionOperation; diff --git a/reverse_engineering/node_modules/mongodb/lib/read_concern.js b/reverse_engineering/node_modules/mongodb/lib/read_concern.js deleted file mode 100644 index b48b8e0..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/read_concern.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -/** - * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. - * @class - * @property {string} level The read concern level - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html - */ -class ReadConcern { - /** - * Constructs a ReadConcern from the read concern properties. - * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) - */ - constructor(level) { - if (level != null) { - this.level = level; - } - } - - /** - * Construct a ReadConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {ReadConcern} - */ - static fromOptions(options) { - if (options == null) { - return; - } - - if (options.readConcern) { - if (options.readConcern instanceof ReadConcern) { - return options.readConcern; - } - - return new ReadConcern(options.readConcern.level); - } - - if (options.level) { - return new ReadConcern(options.level); - } - } - - static get MAJORITY() { - return 'majority'; - } - - static get AVAILABLE() { - return 'available'; - } - - static get LINEARIZABLE() { - return 'linearizable'; - } - - static get SNAPSHOT() { - return 'snapshot'; - } -} - -module.exports = ReadConcern; diff --git a/reverse_engineering/node_modules/mongodb/lib/topologies/mongos.js b/reverse_engineering/node_modules/mongodb/lib/topologies/mongos.js deleted file mode 100644 index 784d3b4..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/topologies/mongos.js +++ /dev/null @@ -1,446 +0,0 @@ -'use strict'; - -const TopologyBase = require('./topology_base').TopologyBase; -const MongoError = require('../core').MongoError; -const CMongos = require('../core').Mongos; -const Cursor = require('../cursor'); -const Server = require('./server'); -const Store = require('./topology_base').Store; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=0] How long a send or receive on a socket can take before timing out - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @fires Mongos#commandStarted - * @fires Mongos#commandSucceeded - * @fires Mongos#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Mongos} a Mongos instance. - */ -class Mongos extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Internal state - this.s = { - // Create the Mongos - coreTopology: new CMongos(seedlist, clonedOptions), - // Server capabilities - sCapabilities: null, - // Debug turned on - debug: clonedOptions.debug, - // Store option defaults - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Actual store of callbacks - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Force close the topology - self.close(true); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect'); - self.s.store.execute(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - var events = ['timeout', 'error', 'close', 'fullsetup']; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.on('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - - // Set up serverConfig listeners - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - // Join and leave events - self.s.coreTopology.on('joined', relay('joined')); - self.s.coreTopology.on('left', relay('left')); - - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Mongos.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/reverse_engineering/node_modules/mongodb/lib/topologies/native_topology.js b/reverse_engineering/node_modules/mongodb/lib/topologies/native_topology.js deleted file mode 100644 index 6ccfff5..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/topologies/native_topology.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict'; - -const Topology = require('../core').Topology; -const ServerCapabilities = require('./topology_base').ServerCapabilities; -const Cursor = require('../cursor'); -const translateOptions = require('../utils').translateOptions; - -class NativeTopology extends Topology { - constructor(servers, options) { - options = options || {}; - - let clonedOptions = Object.assign( - {}, - { - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - maxPoolSize: - typeof options.maxPoolSize === 'number' - ? options.maxPoolSize - : typeof options.poolSize === 'number' - ? options.poolSize - : 10, - minPoolSize: - typeof options.minPoolSize === 'number' - ? options.minPoolSize - : typeof options.minSize === 'number' - ? options.minSize - : 0, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - clonedOptions.serverApi = options.serverApi; - - clonedOptions.useUnifiedTopology = options.useUnifiedTopology; - - super(servers, clonedOptions); - } - - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - super.command(ns.toString(), cmd, options, callback); - } - - // Insert - insert(ns, ops, options, callback) { - super.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - super.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - super.remove(ns.toString(), ops, options, callback); - } -} - -module.exports = NativeTopology; diff --git a/reverse_engineering/node_modules/mongodb/lib/topologies/replset.js b/reverse_engineering/node_modules/mongodb/lib/topologies/replset.js deleted file mode 100644 index 90ca543..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/topologies/replset.js +++ /dev/null @@ -1,490 +0,0 @@ -'use strict'; - -const Server = require('./server'); -const Cursor = require('../cursor'); -const MongoError = require('../core').MongoError; -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const CReplSet = require('../core').ReplSet; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'replicaSet', - 'rs_name', - 'secondaryAcceptableLatencyMS', - 'connectWithNoPrimary', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslCRL', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'strategy', - 'debug', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'maxStalenessSeconds', - 'promiseLibrary', - 'minSize', - 'monitorCommands' -]; - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=10000] Time between each replicaset status check. - * @param {string} [options.replicaSet] The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @fires ReplSet#commandStarted - * @fires ReplSet#commandSucceeded - * @fires ReplSet#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {ReplSet} a ReplSet instance. - */ -class ReplSet extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Create the ReplSet - var coreTopology = new CReplSet(seedlist, clonedOptions); - - // Listen to reconnect event - coreTopology.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - coreTopology: coreTopology, - // Server capabilities - sCapabilities: null, - // Debug tag - tag: options.tag, - // Store options - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Store - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - - // Debug - if (clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable: true, - get: function() { - return coreTopology; - } - }); - } - } - - // Connect method - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - }; - }; - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if (t === 'start') { - self.emit('ha_connect', t, state); - } else if (t === 'end') { - self.emit('ha_ismaster', t, state); - } - }; - - // Set up serverConfig listeners - self.s.coreTopology.on('joined', replsetRelay('joined')); - self.s.coreTopology.on('left', relay('left')); - self.s.coreTopology.on('ping', relay('ping')); - self.s.coreTopology.on('ha', relayHa); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self, self); - }); - - self.s.coreTopology.on('all', function() { - self.emit('all', null, self); - }); - - // Connect handler - var connectHandler = function() { - // Set up listeners - self.s.coreTopology.once('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.once('close', errorHandler('close')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.coreTopology.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.coreTopology.destroy(); - - // Try to callback - try { - callback(err); - } catch (err) { - if (!self.s.coreTopology.isConnected()) - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } - - close(forceClosed, callback) { - ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); - super.close(forceClosed, callback); - } -} - -Object.defineProperty(ReplSet.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/reverse_engineering/node_modules/mongodb/lib/topologies/server.js b/reverse_engineering/node_modules/mongodb/lib/topologies/server.js deleted file mode 100644 index 7750720..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/topologies/server.js +++ /dev/null @@ -1,449 +0,0 @@ -'use strict'; - -const CServer = require('../core').Server; -const Cursor = require('../cursor'); -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const MongoError = require('../core').MongoError; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'reconnectInterval', - 'monitoring', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bsonRegExp', - 'compression', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=0] How long a send or receive on a socket can take before timing out - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster - * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#commandStarted - * @fires Server#commandSucceeded - * @fires Server#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Server} a Server instance. - */ -class Server extends TopologyBase { - constructor(host, port, options) { - super(); - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Promise library - const promiseLibrary = options.promiseLibrary; - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if (host.indexOf('/') !== -1) { - if (port != null && typeof port === 'object') { - options = port; - port = null; - } - } else if (port == null) { - throw MongoError.create({ message: 'port must be specified', driver: true }); - } - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - host: host, - port: port, - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Define the internal properties - this.s = { - // Create an instance of a server instance from core module - coreTopology: new CServer(clonedOptions), - // Server capabilities - sCapabilities: null, - // Cloned options - clonedOptions: clonedOptions, - // Reconnect - reconnect: clonedOptions.reconnect, - // Emit error - emitError: clonedOptions.emitError, - // Pool size - poolSize: clonedOptions.size, - // Store Options - storeOptions: storeOptions, - // Store - store: store, - // Host - host: host, - // Port - port: port, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = this.s.clonedOptions; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.coreTopology.removeListener(e, connectHandlers[e]); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect', self); - self.s.store.execute(); - }; - - // Reconnect failed - var reconnectFailedHandler = function(err) { - self.emit('reconnectFailed', err); - self.s.store.flush(err); - }; - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - // Only called on destroy - self.s.coreTopology.on('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Clear out all the current handlers left over - [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Add the event handlers - self.s.coreTopology.once('timeout', connectHandlers.timeout); - self.s.coreTopology.once('error', connectHandlers.error); - self.s.coreTopology.once('close', connectHandlers.close); - self.s.coreTopology.once('connect', connectHandler); - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); - self.s.coreTopology.on('monitoring', relay('monitoring')); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Server.prototype, 'poolSize', { - enumerable: true, - get: function() { - return this.s.coreTopology.connections().length; - } -}); - -Object.defineProperty(Server.prototype, 'autoReconnect', { - enumerable: true, - get: function() { - return this.s.reconnect; - } -}); - -Object.defineProperty(Server.prototype, 'host', { - enumerable: true, - get: function() { - return this.s.host; - } -}); - -Object.defineProperty(Server.prototype, 'port', { - enumerable: true, - get: function() { - return this.s.port; - } -}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Server#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Server#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Server#commandFailed - * @type {object} - */ - -module.exports = Server; diff --git a/reverse_engineering/node_modules/mongodb/lib/topologies/topology_base.js b/reverse_engineering/node_modules/mongodb/lib/topologies/topology_base.js deleted file mode 100644 index 938f1a2..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/topologies/topology_base.js +++ /dev/null @@ -1,417 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'), - MongoError = require('../core').MongoError, - f = require('util').format, - ReadPreference = require('../core').ReadPreference, - ClientSession = require('../core').Sessions.ClientSession; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; - - // Internal state - this.s = { - storedOps: storedOps, - storeOptions: storeOptions, - topology: topology - }; - - Object.defineProperty(this, 'length', { - enumerable: true, - get: function() { - return self.s.storedOps.length; - } - }); -}; - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); -}; - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); -}; - -Store.prototype.flush = function(err) { - while (this.s.storedOps.length > 0) { - this.s.storedOps - .shift() - .c( - err || - MongoError.create({ message: f('no connection available for operation'), driver: true }) - ); - } -}; - -var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; -var secondaryOptions = ['secondary', 'secondaryPreferred']; - -Store.prototype.execute = function(options) { - options = options || {}; - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Unpack options - var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; - var executeSecondary = - typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; - - // Execute all the stored ops - while (ops.length > 0) { - var op = ops.shift(); - - if (op.t === 'cursor') { - if (executePrimary && executeSecondary) { - op.o[op.m].apply(op.o, op.p); - } else if ( - executePrimary && - op.o.options && - op.o.options.readPreference && - primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } else if ( - !executePrimary && - executeSecondary && - op.o.options && - op.o.options.readPreference && - secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } - } else if (op.t === 'auth') { - this.s.topology[op.t].apply(this.s.topology, op.o); - } else { - if (executePrimary && executeSecondary) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - executePrimary && - op.op && - op.op.readPreference && - primaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - !executePrimary && - executeSecondary && - op.op && - op.op.readPreference && - secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } - } -}; - -Store.prototype.all = function() { - return this.s.storedOps; -}; - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - get: function() { - return value; - } - }); - }; - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - var commandsTakeWriteConcern = false; - var commandsTakeCollation = false; - - if (ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if (ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if (ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if (ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - if (ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = true; - } - - // If no min or max wire version set to 0 - if (ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if (ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, 'hasAggregationCursor', aggregationCursor); - setup_get_property(this, 'hasWriteCommands', writeCommands); - setup_get_property(this, 'hasTextSearch', textSearch); - setup_get_property(this, 'hasAuthCommands', authCommands); - setup_get_property(this, 'hasListCollectionsCommand', listCollections); - setup_get_property(this, 'hasListIndexesCommand', listIndexes); - setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); - setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); - setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); - setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); - setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); -}; - -class TopologyBase extends EventEmitter { - constructor() { - super(); - this.setMaxListeners(Infinity); - } - - // Sessions related methods - hasSessionSupport() { - return this.logicalSessionTimeoutMinutes != null; - } - - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - endSessions(sessions, callback) { - return this.s.coreTopology.endSessions(sessions, callback); - } - - get clientMetadata() { - return this.s.coreTopology.s.options.metadata; - } - - // Server capabilities - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.s.coreTopology.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - this.s.coreTopology.command(ns.toString(), cmd, ReadPreference.translate(options), callback); - } - - // Insert - insert(ns, ops, options, callback) { - this.s.coreTopology.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - this.s.coreTopology.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - this.s.coreTopology.remove(ns.toString(), ops, options, callback); - } - - // IsConnected - isConnected(options) { - options = options || {}; - options = ReadPreference.translate(options); - - return this.s.coreTopology.isConnected(options); - } - - // IsDestroyed - isDestroyed() { - return this.s.coreTopology.isDestroyed(); - } - - // Cursor - cursor(ns, cmd, options) { - options = options || {}; - options = ReadPreference.translate(options); - options.disconnectHandler = this.s.store; - options.topology = this; - - return this.s.coreTopology.cursor(ns, cmd, options); - } - - lastIsMaster() { - return this.s.coreTopology.lastIsMaster(); - } - - selectServer(selector, options, callback) { - return this.s.coreTopology.selectServer(selector, options, callback); - } - - /** - * Unref all sockets - * @method - */ - unref() { - return this.s.coreTopology.unref(); - } - - /** - * All raw connections - * @method - * @return {array} - */ - connections() { - return this.s.coreTopology.connections(); - } - - close(forceClosed, callback) { - // If we have sessions, we want to individually move them to the session pool, - // and then send a single endSessions call. - this.s.sessions.forEach(session => session.endSession()); - - if (this.s.sessionPool) { - this.s.sessionPool.endAllPooledSessions(); - } - - // We need to wash out all stored processes - if (forceClosed === true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - this.s.coreTopology.destroy( - { - force: typeof forceClosed === 'boolean' ? forceClosed : false - }, - callback - ); - } -} - -// Properties -Object.defineProperty(TopologyBase.prototype, 'bson', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.bson; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'parserType', { - enumerable: true, - get: function() { - return this.s.coreTopology.parserType; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.coreTopology.logicalSessionTimeoutMinutes; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'type', { - enumerable: true, - get: function() { - return this.s.coreTopology.type; - } -}); - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; -exports.TopologyBase = TopologyBase; diff --git a/reverse_engineering/node_modules/mongodb/lib/url_parser.js b/reverse_engineering/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index 52a9936..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,637 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference; -const parser = require('url'); -const f = require('util').format; -const Logger = require('./core').Logger; -const dns = require('dns'); -const ReadConcern = require('./read_concern'); -const qs = require('querystring'); -const MongoParseError = require('./core/error').MongoParseError; - -module.exports = function(url, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - let result; - try { - result = parser.parse(url, true); - } catch (e) { - return callback(new Error('URL malformed, cannot be parsed')); - } - - if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { - return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); - } - - if (result.protocol === 'mongodb:') { - return parseHandler(url, options, callback); - } - - // Otherwise parse this as an SRV record - if (result.hostname.split('.').length < 3) { - return callback(new Error('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - - const hostname = url.substring('mongodb+srv://'.length).split('/')[0]; - if (hostname.match(',')) { - return callback(new Error('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); - } - - let srvAddress = `_mongodb._tcp.${result.host}`; - dns.resolveSrv(srvAddress, function(err, addresses) { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new Error('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback(new Error('Server record does not share hostname with parent URI')); - } - } - - let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; - let connectionStrings = addresses.map(function(address, i) { - if (i === 0) return `${base}${address.name}:${address.port}`; - else return `${address.name}:${address.port}`; - }); - - let connectionString = connectionStrings.join(',') + '/'; - let connectionStringOptions = []; - - // Add the default database if needed - if (result.path) { - let defaultDb = result.path.slice(1); - if (defaultDb.indexOf('?') !== -1) { - defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); - } - - connectionString += defaultDb; - } - - // Default to SSL true - if (!options.ssl && !result.search) { - connectionStringOptions.push('ssl=true'); - } else if (!options.ssl && result.search && !result.search.match('ssl')) { - connectionStringOptions.push('ssl=true'); - } - - // Keep original uri options - if (result.search) { - connectionStringOptions.push(result.search.replace('?', '')); - } - - dns.resolveTxt(result.host, function(err, record) { - if (err && err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') return callback(err); - if (err && err.code === 'ENODATA') record = null; - - if (record) { - if (record.length > 1) { - return callback(new MongoParseError('Multiple text records not allowed')); - } - - record = record[0].join(''); - const parsedRecord = qs.parse(record); - const items = Object.keys(parsedRecord); - if (Object.keys(items).some(k => k.toLowerCase() === 'loadbalanced')) { - return callback(new MongoParseError('Load balancer mode requires driver version 4+')); - } - if (items.some(item => item !== 'authSource' && item !== 'replicaSet')) { - return callback( - new MongoParseError('Text record must only set `authSource` or `replicaSet`') - ); - } - - if (items.length > 0) { - connectionStringOptions.push(record); - } - } - - // Add any options to the connection string - if (connectionStringOptions.length) { - connectionString += `?${connectionStringOptions.join('&')}`; - } - - parseHandler(connectionString, options, callback); - }); - }); -}; - -function matchesParentDomain(srvAddress, parentDomain) { - let regex = /^.*?\./; - let srv = `.${srvAddress.replace(regex, '')}`; - let parent = `.${parentDomain.replace(regex, '')}`; - if (srv.endsWith(parent)) return true; - else return false; -} - -function parseHandler(address, options, callback) { - let result, err; - try { - result = parseConnectionString(address, options); - } catch (e) { - err = e; - } - - return err ? callback(err, null) : callback(null, result); -} - -function parseConnectionString(url, options) { - // Variables - let connection_part = ''; - let auth_part = ''; - let query_string_part = ''; - let dbName = 'admin'; - - // Url parser result - let result = parser.parse(url, true); - if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { - throw new Error('No hostname or hostnames provided in connection string'); - } - - if (result.port === '0') { - throw new Error('Invalid port (zero) with hostname'); - } - - if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { - throw new Error('Invalid port (larger than 65535) with hostname'); - } - - if ( - result.path && - result.path.length > 0 && - result.path[0] !== '/' && - url.indexOf('.sock') === -1 - ) { - throw new Error('Missing delimiting slash between hosts and options'); - } - - if (result.query) { - for (let name in result.query) { - if (name.indexOf('::') !== -1) { - throw new Error('Double colon in host identifier'); - } - - if (result.query[name] === '') { - throw new Error('Query parameter ' + name + ' is an incomplete value pair'); - } - } - } - - if (result.auth) { - let parts = result.auth.split(':'); - if (url.indexOf(result.auth) !== -1 && parts.length > 2) { - throw new Error('Username with password containing an unescaped colon'); - } - - if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { - throw new Error('Username containing an unescaped at-sign'); - } - } - - // Remove query - let clean = url.split('?').shift(); - - // Extract the list of hosts - let strings = clean.split(','); - let hosts = []; - - for (let i = 0; i < strings.length; i++) { - let hostString = strings[i]; - - if (hostString.indexOf('mongodb') !== -1) { - if (hostString.indexOf('@') !== -1) { - hosts.push(hostString.split('@').pop()); - } else { - hosts.push(hostString.substr('mongodb://'.length)); - } - } else if (hostString.indexOf('/') !== -1) { - hosts.push(hostString.split('/').shift()); - } else if (hostString.indexOf('/') === -1) { - hosts.push(hostString.trim()); - } - } - - for (let i = 0; i < hosts.length; i++) { - let r = parser.parse(f('mongodb://%s', hosts[i].trim())); - if (r.path && r.path.indexOf('.sock') !== -1) continue; - if (r.path && r.path.indexOf(':') !== -1) { - // Not connecting to a socket so check for an extra slash in the hostname. - // Using String#split as perf is better than match. - if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { - throw new Error('Slash in host identifier'); - } else { - throw new Error('Double colon in host identifier'); - } - } - } - - // If we have a ? mark cut the query elements off - if (url.indexOf('?') !== -1) { - query_string_part = url.substr(url.indexOf('?') + 1); - connection_part = url.substring('mongodb://'.length, url.indexOf('?')); - } else { - connection_part = url.substring('mongodb://'.length); - } - - // Check if we have auth params - if (connection_part.indexOf('@') !== -1) { - auth_part = connection_part.split('@')[0]; - connection_part = connection_part.split('@')[1]; - } - - // Check there is not more than one unescaped slash - if (connection_part.split('/').length > 2) { - throw new Error( - "Unsupported host '" + - connection_part.split('?')[0] + - "', hosts must be URL encoded and contain at most one unencoded slash" - ); - } - - // Check if the connection string has a db - if (connection_part.indexOf('.sock') !== -1) { - if (connection_part.indexOf('.sock/') !== -1) { - dbName = connection_part.split('.sock/')[1]; - // Check if multiple database names provided, or just an illegal trailing backslash - if (dbName.indexOf('/') !== -1) { - if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - connection_part = connection_part.split( - '/', - connection_part.indexOf('.sock') + '.sock'.length - ); - } - } else if (connection_part.indexOf('/') !== -1) { - // Check if multiple database names provided, or just an illegal trailing backslash - if (connection_part.split('/').length > 2) { - if (connection_part.split('/')[2].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - dbName = connection_part.split('/')[1]; - connection_part = connection_part.split('/')[0]; - } - - // URI decode the host information - connection_part = decodeURIComponent(connection_part); - - // Result object - let object = {}; - - // Pick apart the authentication part of the string - let authPart = auth_part || ''; - let auth = authPart.split(':', 2); - - // Decode the authentication URI components and verify integrity - let user = decodeURIComponent(auth[0]); - if (auth[0] !== encodeURIComponent(user)) { - throw new Error('Username contains an illegal unescaped character'); - } - auth[0] = user; - - if (auth[1]) { - let pass = decodeURIComponent(auth[1]); - if (auth[1] !== encodeURIComponent(pass)) { - throw new Error('Password contains an illegal unescaped character'); - } - auth[1] = pass; - } - - // Add auth to final object if we have 2 elements - if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; - // if user provided auth options, use that - if (options && options.auth != null) object.auth = options.auth; - - // Variables used for temporary storage - let hostPart; - let urlOptions; - let servers; - let compression; - let serverOptions = { socketOptions: {} }; - let dbOptions = { read_preference_tags: [] }; - let replSetServersOptions = { socketOptions: {} }; - let mongosOptions = { socketOptions: {} }; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = mongosOptions; - - // Let's check if we are using a domain socket - if (url.match(/\.sock/)) { - // Split out the socket part - let domainSocket = url.substring( - url.indexOf('mongodb://') + 'mongodb://'.length, - url.lastIndexOf('.sock') + '.sock'.length - ); - // Clean out any auth stuff if any - if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; - domainSocket = decodeURIComponent(domainSocket); - servers = [{ domain_socket: domainSocket }]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - let deduplicatedServers = {}; - - // Parse all server results - servers = hostPart - .split(',') - .map(function(h) { - let _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - let hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate server - if (deduplicatedServers[_host + '_' + _port]) return null; - deduplicatedServers[_host + '_' + _port] = 1; - - // Return the mapped object - return { host: _host, port: _port }; - }) - .filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - - if (urlOptions.some(k => k.toLowerCase() === 'loadbalanced')) { - throw new MongoParseError('Load balancer mode requires driver version 4+'); - } - - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if (!opt) return; - var splitOpt = opt.split('='), - name = splitOpt[0], - value = splitOpt[1]; - - // Options implementations - switch (name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = value === 'true'; - dbOptions.slaveOk = value === 'true'; - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'appname': - object.appname = decodeURIComponent(value); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = value === 'true'; - break; - case 'ssl': - if (value === 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - mongosOptions.ssl = value; - break; - } - serverOptions.ssl = value === 'true'; - replSetServersOptions.ssl = value === 'true'; - mongosOptions.ssl = value === 'true'; - break; - case 'sslValidate': - serverOptions.sslValidate = value === 'true'; - replSetServersOptions.sslValidate = value === 'true'; - mongosOptions.sslValidate = value === 'true'; - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = value === 'true'; - break; - case 'fsync': - dbOptions.fsync = value === 'true'; - break; - case 'journal': - dbOptions.j = value === 'true'; - break; - case 'safe': - dbOptions.safe = value === 'true'; - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = value === 'true'; - break; - case 'readConcernLevel': - dbOptions.readConcern = new ReadConcern(value); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if (isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if (value === 'GSSAPI') { - // If no password provided decode only the principal - if (object.auth == null) { - let urlDecodeAuthPart = decodeURIComponent(authPart); - if (urlDecodeAuthPart.indexOf('@') === -1) - throw new Error('GSSAPI requires a provided principal'); - object.auth = { user: urlDecodeAuthPart, password: null }; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if (value === 'MONGODB-X509') { - object.auth = { user: decodeURIComponent(authPart) }; - } - - // Only support GSSAPI or MONGODB-CR for now - if ( - value !== 'GSSAPI' && - value !== 'MONGODB-X509' && - value !== 'MONGODB-CR' && - value !== 'DEFAULT' && - value !== 'SCRAM-SHA-1' && - value !== 'SCRAM-SHA-256' && - value !== 'PLAIN' - ) - throw new Error( - 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' - ); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - { - // Split up into key, value pairs - let values = value.split(','); - let o = {}; - // For each value split into key, value - values.forEach(function(x) { - let v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; - if (typeof o.CANONICALIZE_HOST_NAME === 'string') - dbOptions.gssapiCanonicalizeHostName = - o.CANONICALIZE_HOST_NAME === 'true' ? true : false; - } - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if (!ReadPreference.isValid(value)) - throw new Error( - 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' - ); - dbOptions.readPreference = value; - break; - case 'maxStalenessSeconds': - dbOptions.maxStalenessSeconds = parseInt(value, 10); - break; - case 'readPreferenceTags': - { - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - let tagObject = {}; - if (value == null || value === '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - let tags = value.split(/,/); - for (let i = 0; i < tags.length; i++) { - let parts = tags[i].trim().split(/:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - } - break; - case 'compressors': - { - compression = serverOptions.compression || {}; - let compressors = value.split(','); - if ( - !compressors.every(function(compressor) { - return compressor === 'snappy' || compressor === 'zlib'; - }) - ) { - throw new Error('Compressors must be at least one of snappy or zlib'); - } - - compression.compressors = compressors; - serverOptions.compression = compression; - } - break; - case 'zlibCompressionLevel': - { - compression = serverOptions.compression || {}; - let zlibCompressionLevel = parseInt(value, 10); - if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { - throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); - } - - compression.zlibCompressionLevel = zlibCompressionLevel; - serverOptions.compression = compression; - } - break; - case 'retryWrites': - dbOptions.retryWrites = value === 'true'; - break; - case 'minSize': - dbOptions.minSize = parseInt(value, 10); - break; - default: - { - let logger = Logger('URL Parser'); - logger.warn(`${name} is not supported as a connection string option`); - } - break; - } - }); - - // No tags: should be null (not []) - if (dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if ( - (dbOptions.w === -1 || dbOptions.w === 0) && - (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) - ) - throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); - - // If no read preference set it to primary - if (!dbOptions.readPreference) { - dbOptions.readPreference = 'primary'; - } - - // make sure that user-provided options are applied with priority - dbOptions = Object.assign(dbOptions, options); - - // Add servers to result - object.servers = servers; - - // Returned parsed object - return object; -} diff --git a/reverse_engineering/node_modules/mongodb/lib/utils.js b/reverse_engineering/node_modules/mongodb/lib/utils.js deleted file mode 100644 index 0611972..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,997 +0,0 @@ -'use strict'; -const MongoError = require('./core/error').MongoError; -const WriteConcern = require('./write_concern'); - -var shallowClone = function(obj) { - var copy = {}; - for (var name in obj) copy[name] = obj[name]; - return copy; -}; - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable: true, - get: function() { - return value; - } - }); -}; - -var formatSortValue = (exports.formatSortValue = function(sortDirection) { - var value = ('' + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], " + - "['field2', '(ascending|descending)']]" - ); - } -}); - -var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { - var orderBy = new Map(); - if (sortValue == null) return null; - if (Array.isArray(sortValue)) { - if (sortValue.length === 0) { - return null; - } - - for (var i = 0; i < sortValue.length; i++) { - if (sortValue[i].constructor === String) { - orderBy.set(`${sortValue[i]}`, 1); - } else { - orderBy.set(`${sortValue[i][0]}`, formatSortValue(sortValue[i][1])); - } - } - } else if (sortValue != null && typeof sortValue === 'object') { - if (sortValue instanceof Map) { - orderBy = sortValue; - } else { - var sortKeys = Object.keys(sortValue); - for (var k of sortKeys) { - orderBy.set(k, sortValue[k]); - } - } - } else if (typeof sortValue === 'string') { - orderBy.set(`${sortValue}`, 1); - } else { - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return orderBy; -}); - -var checkCollectionName = function checkCollectionName(collectionName) { - if ('string' !== typeof collectionName) { - throw new MongoError('collection name must be a String'); - } - - if (!collectionName || collectionName.indexOf('..') !== -1) { - throw new MongoError('collection names cannot be empty'); - } - - if ( - collectionName.indexOf('$') !== -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null - ) { - throw new MongoError("collection names must not contain '$'"); - } - - if (collectionName.match(/^\.|\.$/) != null) { - throw new MongoError("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the collection name - if (collectionName.indexOf('\x00') !== -1) { - throw new MongoError('collection names cannot contain a null character'); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if (callback == null) return; - - if (callback) { - return value2 ? callback(err, value1, value2) : callback(err, value1); - } - } catch (err) { - process.nextTick(function() { - throw err; - }); - return false; - } - - return true; -}; - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({ message: msg, driver: true }); - - // Get all object keys - var keys = typeof error === 'object' ? Object.keys(error) : []; - - for (var i = 0; i < keys.length; i++) { - try { - e[keys[i]] = error[keys[i]]; - } catch (err) { - // continue - } - } - - return e; -}; - -/** - * @ignore - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if (typeof hint === 'string') { - finalHint = hint; - } else if (Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if (hint != null && typeof hint === 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if ('string' === typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if (Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if ('string' === typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if (Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if (isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if (isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join('_'), - keys: keys, - fieldHash: fieldHash - }; -}; - -var isObject = (exports.isObject = function(arg) { - return '[object Object]' === Object.prototype.toString.call(arg); -}); - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -}; - -var decorateCommand = function(command, options, exclude) { - for (var name in options) { - if (exclude.indexOf(name) === -1) command[name] = options[name]; - } - - return command; -}; - -var mergeOptions = function(target, source) { - for (var name in source) { - target[name] = source[name]; - } - - return target; -}; - -// Merge options with translation -var translateOptions = function(target, source) { - var translations = { - // SSL translation options - sslCA: 'ca', - sslCRL: 'crl', - sslValidate: 'rejectUnauthorized', - sslKey: 'key', - sslCert: 'cert', - sslPass: 'passphrase', - // SocketTimeout translation options - socketTimeoutMS: 'socketTimeout', - connectTimeoutMS: 'connectionTimeout', - // Replicaset options - replicaSet: 'setName', - rs_name: 'setName', - secondaryAcceptableLatencyMS: 'acceptableLatency', - connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', - // Mongos options - acceptableLatencyMS: 'localThresholdMS' - }; - - for (var name in source) { - if (translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } - - return target; -}; - -var filterOptions = function(options, names) { - var filterOptions = {}; - - for (var name in options) { - if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; - } - - // Filtered options - return filterOptions; -}; - -// Write concern keys -const WRITE_CONCERN_KEYS = ['w', 'j', 'wtimeout', 'fsync', 'writeConcern']; - -/** - * If there is no WriteConcern related options defined on target then inherit from source. - * Otherwise, do not inherit **any** options from source. - * @internal - * @param {object} target - options object conditionally receiving the writeConcern options - * @param {object} source - options object containing the potentially inherited writeConcern options - */ -function conditionallyMergeWriteConcern(target, source) { - let found = false; - for (const wcKey of WRITE_CONCERN_KEYS) { - if (wcKey in target) { - // Found a writeConcern option - found = true; - break; - } - } - - if (!found) { - for (const wcKey of WRITE_CONCERN_KEYS) { - if (source[wcKey]) { - if (!('writeConcern' in target)) { - target.writeConcern = {}; - } - target.writeConcern[wcKey] = source[wcKey]; - } - } - } - - return target; -} - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {function} operation The operation to execute - * @param {array} args Arguments to apply the provided operation - * @param {object} [options] Options that modify the behavior of the method - */ -const executeLegacyOperation = (topology, operation, args, options) => { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!Array.isArray(args)) { - throw new TypeError('This method requires an array of arguments to apply'); - } - - options = options || {}; - const Promise = topology.s.promiseLibrary; - let callback = args[args.length - 1]; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, opOptions, owner; - if (!options.skipSessions && topology.hasSessionSupport()) { - opOptions = args[args.length - 2]; - if (opOptions == null || opOptions.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - const optionsIndex = args.length - 2; - args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); - } else if (opOptions.session && opOptions.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner && !options.returnsCursor) { - session.endSession(() => { - delete opOptions.session; - if (err) return reject(err); - resolve(result); - }); - } else { - if (err) return reject(err); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - callback = args.pop(); - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - args.push(handler); - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - throw e; - } - } - - // Return a Promise - if (args[args.length - 1] != null) { - throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - args[args.length - 1] = handler; - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - } - }); -}; - -/** - * Applies retryWrites: true to a command if retryWrites is set on the command's database. - * - * @param {object} target The target command to which we will apply retryWrites. - * @param {object} db The database from which we can inherit a retryWrites value. - */ -function applyRetryableWrites(target, db) { - if (db && db.s.options.retryWrites) { - target.retryWrites = true; - } - - return target; -} - -/** - * Applies a write concern to a command based on well defined inheritance rules, optionally - * detecting support for the write concern in the first place. - * - * @param {Object} target the target command we will be applying the write concern to - * @param {Object} sources sources where we can inherit default write concerns from - * @param {Object} [options] optional settings passed into a command for write concern overrides - * @returns {Object} the (now) decorated target - */ -function applyWriteConcern(target, sources, options) { - options = options || {}; - const db = sources.db; - const coll = sources.collection; - - if (options.session && options.session.inTransaction()) { - // writeConcern is not allowed within a multi-statement transaction - if (target.writeConcern) { - delete target.writeConcern; - } - - return target; - } - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - return Object.assign(target, { writeConcern }); - } - - if (coll && coll.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); - } - - if (db && db.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); - } - - return target; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies collation to a given command. - * - * @param {object} [command] the command on which to apply collation - * @param {(Cursor|Collection)} [target] target of command - * @param {object} [options] options containing collation settings - */ -function decorateWithCollation(command, target, options) { - const topology = (target.s && target.s.topology) || target.topology; - - if (!topology) { - throw new TypeError('parameter "target" is missing a topology'); - } - - const capabilities = topology.capabilities(); - if (options.collation && typeof options.collation === 'object') { - if (capabilities && capabilities.commandsTakeCollation) { - command.collation = options.collation; - } else { - throw new MongoError(`Current topology does not support collation`); - } - } -} - -/** - * Applies a read concern to a given command. - * - * @param {object} command the command on which to apply the read concern - * @param {Collection} coll the parent collection of the operation calling this method - */ -function decorateWithReadConcern(command, coll, options) { - if (options && options.session && options.session.inTransaction()) { - return; - } - let readConcern = Object.assign({}, command.readConcern || {}); - if (coll.s.readConcern) { - Object.assign(readConcern, coll.s.readConcern); - } - - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern: readConcern }); - } -} - -/** - * Applies an explain to a given command. - * @internal - * - * @param {object} command - the command on which to apply the explain - * @param {Explain} explain - the options containing the explain verbosity - * @return the new command - */ -function decorateWithExplain(command, explain) { - if (command.explain) { - return command; - } - - return { explain: command, verbosity: explain.verbosity }; -} - -const nodejsMajorVersion = +process.version.split('.')[0].substring(1); -const emitProcessWarning = msg => - nodejsMajorVersion <= 6 - ? process.emitWarning(msg, 'DeprecationWarning', MONGODB_WARNING_CODE) - : process.emitWarning(msg, { type: 'DeprecationWarning', code: MONGODB_WARNING_CODE }); -// eslint-disable-next-line no-console -const emitConsoleWarning = msg => console.error(msg); -const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; - -/** - * Default message handler for generating deprecation warnings. - * - * @param {string} name function name - * @param {string} option option name - * @return {string} warning message - * @ignore - * @api private - */ -function defaultMsgHandler(name, option) { - return `${name} option [${option}] is deprecated and will be removed in a later version.`; -} - -/** - * Deprecates a given function's options. - * - * @param {object} config configuration for deprecation - * @param {string} config.name function name - * @param {Array} config.deprecatedOptions options to deprecate - * @param {number} config.optionsIndex index of options object in function arguments array - * @param {function} [config.msgHandler] optional custom message handler to generate warnings - * @param {function} fn the target function of deprecation - * @return {function} modified function that warns once per deprecated option, and executes original function - * @ignore - * @api private - */ -function deprecateOptions(config, fn) { - if (process.noDeprecation === true) { - return fn; - } - - const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; - - const optionsWarned = new Set(); - function deprecated() { - const options = arguments[config.optionsIndex]; - - // ensure options is a valid, non-empty object, otherwise short-circuit - if (!isObject(options) || Object.keys(options).length === 0) { - return fn.apply(this, arguments); - } - - config.deprecatedOptions.forEach(deprecatedOption => { - if ( - Object.prototype.hasOwnProperty.call(options, deprecatedOption) && - !optionsWarned.has(deprecatedOption) - ) { - optionsWarned.add(deprecatedOption); - const msg = msgHandler(config.name, deprecatedOption); - emitDeprecationWarning(msg); - if (this && this.getLogger) { - const logger = this.getLogger(); - if (logger) { - logger.warn(msg); - } - } - } - }); - - return fn.apply(this, arguments); - } - - // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 - // The wrapper will keep the same prototype as fn to maintain prototype chain - Object.setPrototypeOf(deprecated, fn); - if (fn.prototype) { - // Setting this (rather than using Object.setPrototype, as above) ensures - // that calling the unwrapped constructor gives an instanceof the wrapped - // constructor. - deprecated.prototype = fn.prototype; - } - - return deprecated; -} - -const SUPPORTS = {}; -// Test asyncIterator support -try { - require('./async/async_iterator'); - SUPPORTS.ASYNC_ITERATOR = true; -} catch (e) { - SUPPORTS.ASYNC_ITERATOR = false; -} - -class MongoDBNamespace { - constructor(db, collection) { - this.db = db; - this.collection = collection; - } - - toString() { - return this.collection ? `${this.db}.${this.collection}` : this.db; - } - - withCollection(collection) { - return new MongoDBNamespace(this.db, collection); - } - - static fromString(namespace) { - if (!namespace) { - throw new Error(`Cannot parse namespace from "${namespace}"`); - } - - const index = namespace.indexOf('.'); - return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); - } -} - -function* makeCounter(seed) { - let count = seed || 0; - while (true) { - const newCount = count; - count += 1; - yield newCount; - } -} - -/** - * Helper function for either accepting a callback, or returning a promise - * - * @param {Object} parent an instance of parent with promiseLibrary. - * @param {object} parent.s an object containing promiseLibrary. - * @param {function} parent.s.promiseLibrary an object containing promiseLibrary. - * @param {[Function]} callback an optional callback. - * @param {Function} fn A function that takes a callback - * @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise. - */ -function maybePromise(parent, callback, fn) { - const PromiseLibrary = (parent && parent.s && parent.s.promiseLibrary) || Promise; - - let result; - if (typeof callback !== 'function') { - result = new PromiseLibrary((resolve, reject) => { - callback = (err, res) => { - if (err) return reject(err); - resolve(res); - }; - }); - } - - fn(function(err, res) { - if (err != null) { - try { - callback(err); - } catch (error) { - return process.nextTick(() => { - throw error; - }); - } - return; - } - - callback(err, res); - }); - - return result; -} - -function now() { - const hrtime = process.hrtime(); - return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); -} - -function calculateDurationInMs(started) { - if (typeof started !== 'number') { - throw TypeError('numeric value required to calculate duration'); - } - - const elapsed = now() - started; - return elapsed < 0 ? 0 : elapsed; -} - -/** - * Creates an interval timer which is able to be woken up sooner than - * the interval. The timer will also debounce multiple calls to wake - * ensuring that the function is only ever called once within a minimum - * interval window. - * - * @param {function} fn An async function to run on an interval, must accept a `callback` as its only parameter - * @param {object} [options] Optional settings - * @param {number} [options.interval] The interval at which to run the provided function - * @param {number} [options.minInterval] The minimum time which must pass between invocations of the provided function - * @param {boolean} [options.immediate] Execute the function immediately when the interval is started - */ -function makeInterruptableAsyncInterval(fn, options) { - let timerId; - let lastCallTime; - let lastWakeTime; - let stopped = false; - - options = options || {}; - const interval = options.interval || 1000; - const minInterval = options.minInterval || 500; - const immediate = typeof options.immediate === 'boolean' ? options.immediate : false; - const clock = typeof options.clock === 'function' ? options.clock : now; - - function wake() { - const currentTime = clock(); - const timeSinceLastWake = currentTime - lastWakeTime; - const timeSinceLastCall = currentTime - lastCallTime; - const timeUntilNextCall = interval - timeSinceLastCall; - lastWakeTime = currentTime; - - // For the streaming protocol: there is nothing obviously stopping this - // interval from being woken up again while we are waiting "infinitely" - // for `fn` to be called again`. Since the function effectively - // never completes, the `timeUntilNextCall` will continue to grow - // negatively unbounded, so it will never trigger a reschedule here. - - // debounce multiple calls to wake within the `minInterval` - if (timeSinceLastWake < minInterval) { - return; - } - - // reschedule a call as soon as possible, ensuring the call never happens - // faster than the `minInterval` - if (timeUntilNextCall > minInterval) { - reschedule(minInterval); - } - - // This is possible in virtualized environments like AWS Lambda where our - // clock is unreliable. In these cases the timer is "running" but never - // actually completes, so we want to execute immediately and then attempt - // to reschedule. - if (timeUntilNextCall < 0) { - executeAndReschedule(); - } - } - - function stop() { - stopped = true; - if (timerId) { - clearTimeout(timerId); - timerId = null; - } - - lastCallTime = 0; - lastWakeTime = 0; - } - - function reschedule(ms) { - if (stopped) return; - clearTimeout(timerId); - timerId = setTimeout(executeAndReschedule, ms || interval); - } - - function executeAndReschedule() { - lastWakeTime = 0; - lastCallTime = clock(); - - fn(err => { - if (err) throw err; - reschedule(interval); - }); - } - - if (immediate) { - executeAndReschedule(); - } else { - lastCallTime = clock(); - reschedule(); - } - - return { wake, stop }; -} - -function hasAtomicOperators(doc) { - if (Array.isArray(doc)) { - return doc.reduce((err, u) => err || hasAtomicOperators(u), null); - } - - return ( - Object.keys(typeof doc.toBSON !== 'function' ? doc : doc.toBSON()) - .map(k => k[0]) - .indexOf('$') >= 0 - ); -} - -/** - * When the driver used emitWarning the code will be equal to this. - * @public - * - * @example - * ```js - * process.on('warning', (warning) => { - * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') - * }) - * ``` - */ -const MONGODB_WARNING_CODE = 'MONGODB DRIVER'; - -/** - * @internal - * @param {string} message - message to warn about - */ -function emitWarning(message) { - if (process.emitWarning) { - return nodejsMajorVersion <= 6 - ? process.emitWarning(message, undefined, MONGODB_WARNING_CODE) - : process.emitWarning(message, { code: MONGODB_WARNING_CODE }); - } else { - // Approximate the style of print out on node versions pre 8.x - // eslint-disable-next-line no-console - return console.error(`[${MONGODB_WARNING_CODE}] Warning:`, message); - } -} - -const emittedWarnings = new Set(); -/** - * Will emit a warning once for the duration of the application. - * Uses the message to identify if it has already been emitted - * so using string interpolation can cause multiple emits - * @internal - * @param {string} message - message to warn about - */ -function emitWarningOnce(message) { - if (!emittedWarnings.has(message)) { - emittedWarnings.add(message); - return emitWarning(message); - } -} - -function isSuperset(set, subset) { - set = Array.isArray(set) ? new Set(set) : set; - subset = Array.isArray(subset) ? new Set(subset) : subset; - for (const elem of subset) { - if (!set.has(elem)) { - return false; - } - } - return true; -} - -function isRecord(value, requiredKeys) { - const toString = Object.prototype.toString; - const hasOwnProperty = Object.prototype.hasOwnProperty; - const isObject = v => toString.call(v) === '[object Object]'; - if (!isObject(value)) { - return false; - } - - const ctor = value.constructor; - if (ctor && ctor.prototype) { - if (!isObject(ctor.prototype)) { - return false; - } - - // Check to see if some method exists from the Object exists - if (!hasOwnProperty.call(ctor.prototype, 'isPrototypeOf')) { - return false; - } - } - - if (requiredKeys) { - const keys = Object.keys(value); - return isSuperset(keys, requiredKeys); - } - - return true; -} - -/** - * Make a deep copy of an object - * - * NOTE: This is not meant to be the perfect implementation of a deep copy, - * but instead something that is good enough for the purposes of - * command monitoring. - */ -function deepCopy(value) { - if (value == null) { - return value; - } else if (Array.isArray(value)) { - return value.map(item => deepCopy(item)); - } else if (isRecord(value)) { - const res = {}; - for (const key in value) { - res[key] = deepCopy(value[key]); - } - return res; - } - - const ctor = value.constructor; - if (ctor) { - switch (ctor.name.toLowerCase()) { - case 'date': - return new ctor(Number(value)); - case 'map': - return new Map(value); - case 'set': - return new Set(value); - case 'buffer': - return Buffer.from(value); - } - } - - return value; -} -/** - * @param {{version: string}} pkg - * @returns {{ major: number; minor: number; patch: number }} - */ -function parsePackageVersion(pkg) { - const versionParts = pkg.version.split('.').map(n => Number.parseInt(n, 10)); - return { major: versionParts[0], minor: versionParts[1], patch: versionParts[2] }; -} - -module.exports = { - filterOptions, - mergeOptions, - translateOptions, - shallowClone, - getSingleProperty, - checkCollectionName, - toError, - formattedOrderClause, - parseIndexOptions, - normalizeHintField, - handleCallback, - decorateCommand, - isObject, - debugOptions, - MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, - conditionallyMergeWriteConcern, - executeLegacyOperation, - applyRetryableWrites, - applyWriteConcern, - isPromiseLike, - decorateWithCollation, - decorateWithReadConcern, - decorateWithExplain, - deprecateOptions, - SUPPORTS, - MongoDBNamespace, - emitDeprecationWarning, - makeCounter, - maybePromise, - now, - calculateDurationInMs, - makeInterruptableAsyncInterval, - hasAtomicOperators, - MONGODB_WARNING_CODE, - emitWarning, - emitWarningOnce, - deepCopy, - parsePackageVersion -}; diff --git a/reverse_engineering/node_modules/mongodb/lib/write_concern.js b/reverse_engineering/node_modules/mongodb/lib/write_concern.js deleted file mode 100644 index 8fa4874..0000000 --- a/reverse_engineering/node_modules/mongodb/lib/write_concern.js +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -const kWriteConcernKeys = new Set(['w', 'wtimeout', 'j', 'journal', 'fsync']); -let utils; - -/** - * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. - * @class - * @property {(number|string)} w The write concern - * @property {number} wtimeout The write concern timeout - * @property {boolean} j The journal write concern - * @property {boolean} fsync The file sync write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/index.html - */ -class WriteConcern { - /** - * Constructs a WriteConcern from the write concern properties. - * @param {(number|string)} [w] The write concern - * @param {number} [wtimeout] The write concern timeout - * @param {boolean} [j] The journal write concern - * @param {boolean} [fsync] The file sync write concern - */ - constructor(w, wtimeout, j, fsync) { - if (w != null) { - this.w = w; - } - if (wtimeout != null) { - this.wtimeout = wtimeout; - } - if (j != null) { - this.j = j; - } - if (fsync != null) { - this.fsync = fsync; - } - } - - /** - * Construct a WriteConcern given an options object. - * - * @param {object} [options] The options object from which to extract the write concern. - * @param {(number|string)} [options.w] **Deprecated** Use `options.writeConcern` instead - * @param {number} [options.wtimeout] **Deprecated** Use `options.writeConcern` instead - * @param {boolean} [options.j] **Deprecated** Use `options.writeConcern` instead - * @param {boolean} [options.fsync] **Deprecated** Use `options.writeConcern` instead - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @return {WriteConcern} - */ - static fromOptions(options) { - if ( - options == null || - (options.writeConcern == null && - options.w == null && - options.wtimeout == null && - options.j == null && - options.journal == null && - options.fsync == null) - ) { - return; - } - - if (options.writeConcern) { - if (typeof options.writeConcern === 'string') { - return new WriteConcern(options.writeConcern); - } - - if (!Object.keys(options.writeConcern).some(key => kWriteConcernKeys.has(key))) { - return; - } - - return new WriteConcern( - options.writeConcern.w, - options.writeConcern.wtimeout, - options.writeConcern.j || options.writeConcern.journal, - options.writeConcern.fsync - ); - } - - // this is down here to prevent circular dependency - if (!utils) utils = require('./utils'); - - utils.emitWarningOnce( - `Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.` - ); - return new WriteConcern( - options.w, - options.wtimeout, - options.j || options.journal, - options.fsync - ); - } -} - -module.exports = WriteConcern; diff --git a/reverse_engineering/node_modules/mongodb/package.json b/reverse_engineering/node_modules/mongodb/package.json deleted file mode 100644 index 905faa7..0000000 --- a/reverse_engineering/node_modules/mongodb/package.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "name": "mongodb", - "version": "3.7.3", - "description": "The official MongoDB driver for Node.js", - "main": "index.js", - "files": [ - "index.js", - "lib" - ], - "repository": { - "type": "git", - "url": "git@github.com:mongodb/node-mongodb-native.git" - }, - "keywords": [ - "mongodb", - "driver", - "official" - ], - "author": { - "name": "The MongoDB NodeJS Team", - "email": "dbx-node@mongodb.com" - }, - "peerDependenciesMeta": { - "kerberos": { - "optional": true - }, - "mongodb-client-encryption": { - "optional": true - }, - "mongodb-extjson": { - "optional": true - }, - "snappy": { - "optional": true - }, - "bson-ext": { - "optional": true - }, - "aws4": { - "optional": true - } - }, - "dependencies": { - "bl": "^2.2.1", - "bson": "^1.1.4", - "denque": "^1.4.1", - "optional-require": "^1.1.8", - "safe-buffer": "^5.1.2" - }, - "devDependencies": { - "@types/chai": "^4.2.16", - "@types/mocha": "^8.2.2", - "@types/node": "^14.14.37", - "array-includes": "^3.1.3", - "chai": "^4.1.1", - "chai-subset": "^1.6.0", - "chalk": "^2.4.2", - "co": "4.6.0", - "eslint": "^7.10.0", - "eslint-config-prettier": "^6.11.0", - "eslint-plugin-es": "^3.0.1", - "eslint-plugin-prettier": "^3.1.3", - "jsdoc": "^3.5.5", - "lodash.camelcase": "^4.3.0", - "mocha": "5.2.0", - "mocha-sinon": "^2.1.0", - "mongodb-extjson": "^2.1.1", - "mongodb-mock-server": "^1.0.1", - "nyc": "^15.1.0", - "object.entries": "^1.1.3", - "prettier": "^1.19.1", - "semver": "^5.5.0", - "sinon": "^4.3.0", - "sinon-chai": "^3.2.0", - "snappy": "^6.3.4", - "spec-xunit-file": "0.0.1-3", - "standard-version": "^9.2.0", - "tslib": "^2.2.0", - "typescript": "^4.2.4", - "util.promisify": "^1.0.1", - "worker-farm": "^1.5.0", - "wtfnode": "^0.8.0", - "yargs": "^14.2.0" - }, - "license": "Apache-2.0", - "engines": { - "node": ">=4" - }, - "bugs": { - "url": "https://jira.mongodb.org/projects/NODE/issues/" - }, - "scripts": { - "build:evergreen": "node .evergreen/generate_evergreen_tasks.js", - "build:unified": "tsc -p test/functional/unified-spec-runner/tsconfig.unified.json", - "check:atlas": "mocha --opts '{}' ./test/manual/atlas_connectivity.test.js", - "check:bench": "node test/benchmarks/driverBench/", - "check:coverage": "nyc npm run check:test", - "check:kerberos": "mocha --opts '{}' -t 60000 test/manual/kerberos.test.js", - "check:ldap": "mocha --opts '{}' test/manual/ldap.test.js", - "check:lint": "eslint -v && eslint lib test", - "check:test": "mocha --recursive test/functional test/unit", - "check:tls": "mocha --opts '{}' test/manual/tls_support.test.js", - "format": "npm run check:lint -- --fix", - "release": "standard-version -i HISTORY.md", - "test": "npm run check:lint && mocha --recursive test/functional test/unit" - }, - "homepage": "https://github.com/mongodb/node-mongodb-native", - "optionalDependencies": { - "saslprep": "^1.0.0" - } -} diff --git a/reverse_engineering/node_modules/ms/index.js b/reverse_engineering/node_modules/ms/index.js deleted file mode 100644 index 6a522b1..0000000 --- a/reverse_engineering/node_modules/ms/index.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} diff --git a/reverse_engineering/node_modules/ms/license.md b/reverse_engineering/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/reverse_engineering/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Zeit, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/ms/package.json b/reverse_engineering/node_modules/ms/package.json deleted file mode 100644 index 6a31c81..0000000 --- a/reverse_engineering/node_modules/ms/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "ms", - "version": "2.0.0", - "description": "Tiny milisecond conversion utility", - "repository": "zeit/ms", - "main": "./index", - "files": [ - "index.js" - ], - "scripts": { - "precommit": "lint-staged", - "lint": "eslint lib/* bin/*", - "test": "mocha tests.js" - }, - "eslintConfig": { - "extends": "eslint:recommended", - "env": { - "node": true, - "es6": true - } - }, - "lint-staged": { - "*.js": [ - "npm run lint", - "prettier --single-quote --write", - "git add" - ] - }, - "license": "MIT", - "devDependencies": { - "eslint": "3.19.0", - "expect.js": "0.3.1", - "husky": "0.13.3", - "lint-staged": "3.4.1", - "mocha": "3.4.1" - } -} diff --git a/reverse_engineering/node_modules/ms/readme.md b/reverse_engineering/node_modules/ms/readme.md deleted file mode 100644 index 84a9974..0000000 --- a/reverse_engineering/node_modules/ms/readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# ms - -[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) -[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) - -Use this package to easily convert various time formats to milliseconds. - -## Examples - -```js -ms('2 days') // 172800000 -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2.5 hrs') // 9000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5s') // 5000 -ms('1y') // 31557600000 -ms('100') // 100 -``` - -### Convert from milliseconds - -```js -ms(60000) // "1m" -ms(2 * 60000) // "2m" -ms(ms('10 hours')) // "10h" -``` - -### Time format written-out - -```js -ms(60000, { long: true }) // "1 minute" -ms(2 * 60000, { long: true }) // "2 minutes" -ms(ms('10 hours'), { long: true }) // "10 hours" -``` - -## Features - -- Works both in [node](https://nodejs.org) and in the browser. -- If a number is supplied to `ms`, a string with a unit is returned. -- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). -- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. - -## Caught a bug? - -1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device -2. Link the package to the global module directory: `npm link` -3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! - -As always, you can run the tests using: `npm test` diff --git a/reverse_engineering/node_modules/optional-require/README.md b/reverse_engineering/node_modules/optional-require/README.md deleted file mode 100644 index d002696..0000000 --- a/reverse_engineering/node_modules/optional-require/README.md +++ /dev/null @@ -1,89 +0,0 @@ -[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] -[![Dependency Status][daviddm-image]][daviddm-url] [![devDependency Status][daviddm-dev-image]][daviddm-dev-url] - -# Optional Require - -node.js require that let you handle module not found error without try/catch. Allows you to gracefully require a module only if it exists and contains no error. - -## Why not try/catch? - -So why not just do: - -```ts -let some; -try { - some = require("some-optional-module"); -} catch { - // do nothing -} -``` - -1. You need to keep the variable outside: `let some` before try/catch -2. If `"some-optional-module"` contains error itself, above code will silently ignore it, leaving you, and more importantly, your users, puzzling on why it's not working. - -## Usage - -TypeScript: - -```ts -import { optionalRequire } from "optional-require"; - -const some = optionalRequire("some-optional-module"); -``` - -JavaScript: - -```js -const { optionalRequire } = require("optional-require"); - -const foo = optionalRequire("foo") || {}; -const bar = optionalRequire("bar", true); // true enables console.log a message when not found -const xyz = optionalRequire("xyz", "test"); // "test" enables console.log a message with "test" added. -const fbPath = optionalRequire.resolve("foo", "foo doesn't exist"); -// relative module path works - *but* you need to pass in `require` from your file -const rel = optionalRequire("../foo/bar", { require }); -``` - -### Binding `require` - -The default `optionalRequire` uses `require` from the context of this module. While you can pass in your `require` in `options`, if you want to create your own function that's bound to your `require`, you can do it with `makeOptionalRequire`: - -```ts -import { makeOptionalRequire } from "optional-require"; - -const optionalRequire = makeOptionalRequire(require); - -// now you can optional require files in same dir as your file -const myModule = optionalRequire("./my-module"); -``` - -### Legacy Usage - -In older versions, this module exports `makeOptionalRequire` directly and this is the legacy usage in JavaScript, which is still supported: - -```js -const optionalRequire = require("optional-require")(require); - -const foo = optionalRequire("foo") || {}; -const bar = optionalRequire("bar", true); // true enables console.log a message when not found -const xyz = optionalRequire("xyz", "test"); // "test" enables console.log a message with "test" added. -const fbPath = optionalRequire.resolve("foo", "foo doesn't exist"); -const rel = optionalRequire("../foo/bar"); // relative module path works -``` - -## API - - - -# LICENSE - -Apache-2.0 © [Joel Chen](https://github.com/jchip) - -[travis-image]: https://travis-ci.org/jchip/optional-require.svg?branch=master -[travis-url]: https://travis-ci.org/jchip/optional-require -[npm-image]: https://badge.fury.io/js/optional-require.svg -[npm-url]: https://npmjs.org/package/optional-require -[daviddm-image]: https://david-dm.org/jchip/optional-require/status.svg -[daviddm-url]: https://david-dm.org/jchip/optional-require -[daviddm-dev-image]: https://david-dm.org/jchip/optional-require/dev-status.svg -[daviddm-dev-url]: https://david-dm.org/jchip/optional-require?type=dev diff --git a/reverse_engineering/node_modules/optional-require/dist/index.d.ts b/reverse_engineering/node_modules/optional-require/dist/index.d.ts deleted file mode 100644 index f6bae60..0000000 --- a/reverse_engineering/node_modules/optional-require/dist/index.d.ts +++ /dev/null @@ -1,138 +0,0 @@ -/// -/** - * function to log in case require module was not found - * - * @params message - message to log - * @params path - path of the module that user tried to require - */ -export declare type LogFunction = (message: string, path: string) => void; -/** - * Options for calling optionalRequire - */ -export declare type OptionalRequireOpts = { - /** - * `notFound` is a function. If error from require was `MODULE_NOT_FOUND`, then: - * - * - call `notFound` if it's provided - * - else return the `default` value. - * - * @remark in case the error was not `MODULE_NOT_FOUND`, will instead call the `fail` function - * if it's provided. - * - * @param err - the error from require - */ - notFound?: (err: Error) => unknown; - /** - * `fail` is a function. If error from require was something other than `MODULE_NOT_FOUND`, - * for example, the module contains syntax error, then: - * - * - call `fail` if it's provided - * - else rethrow the error - * - * @remark This is a separate callback from `notFound` so user can handle - * real `MODULE_NOT_FOUND` exception separately, or let the `default` be returned. - * - * @param err - the error from require - */ - fail?: (err: Error) => unknown; - /** - * The value to return if error was `MODULE_NOT_FOUND` but `notFound` is not provided. - */ - default?: unknown; - /** - * Tell optional require to log a message if the module is not found. - * - note: it doesn't log if the error is not due to the module not found - * - * This field can have these values: - * 1. `true` - log with default message - * 2. string - a string to prepend to the message being logged - * - * @remarks to further customize logging, set the `log` function. - */ - message?: true | string; - /** - * function to log the module not found message, default log function uses `console.log` - */ - log?: LogFunction; - /** - * `require` is the node.js require function from caller's context. - * - * If not provided, then use the one received when creating the optional require function - */ - require?: NodeRequire; - /** - * If `true`, then do an optional `require.resolve` and return the full path - */ - resolve?: boolean; -}; -export declare function setDefaultLog(log: LogFunction): void; -/** - * try to require a module with optional handling in case it's not found or fail to require - * - * @param callerRequire - `require` from caller context - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case of exceptions - * @returns require result - */ -export declare function tryRequire(callerRequire: NodeRequire, path: string, optsOrMsg?: OptionalRequireOpts | string | true): unknown; -/** - * try to resolve a module with optional handling in case it's not found or fail to require - * - * @param callerRequire - `require` from caller context - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case of exceptions - * @returns resolve result - */ -export declare function tryResolve(callerRequire: NodeRequire, path: string, optsOrMsg?: OptionalRequireOpts | string | true): string; -/** - * function to require a module with optional handling in case it's not found or fail to require - */ -export declare type OptionalRequireFunction = { - /** - * @param path - path to module to require - * @param optsOrMsg - options or message to log when module not found - */ - (path: string, optsOrMsg?: OptionalRequireOpts | string | true): T; - /** - * resolve the module's full path - * - * @param path - path to module to resolve - * @param optsOrMsg - options or message to log when module not found - * @returns resolve result - */ - resolve: (path: string, opsOrMsg?: OptionalRequireOpts | string | true) => string; - /** - * function to log message, default to use `console.log`, you can replace this with - * another function. - */ - log: LogFunction; -}; -/** - * Make an optional require function, using the `require` from caller's context. - * - * @param callerRequire - `require` from caller's context - * @param log - function to log if module is not found - * @returns required module - */ -export declare function makeOptionalRequire(callerRequire: NodeRequire, log?: (message: string, path: string) => void): OptionalRequireFunction; -/** - * A default optionalRequire function using `require` from optional-require's context. - * - * @remarks because `require` is from optional-require's context, you won't be able to - * do `optionalRequire("./my-module")`. - * - * You can still override the `require` using `options.require` with the one from your - * calling context. - * - */ -export declare const optionalRequire: OptionalRequireFunction; -/** - * An optionalRequire function using `require` from CWD context - * - * @remarks because `require` is from CWD context, if you do `optionalRequireCwd("./my-module")` - * then it will look for `my-module` in CWD. - * - * @remarks You can still override the `require` using `options.require` with the one from your - * calling context. - */ -export declare const optionalRequireCwd: OptionalRequireFunction; diff --git a/reverse_engineering/node_modules/optional-require/dist/index.js b/reverse_engineering/node_modules/optional-require/dist/index.js deleted file mode 100644 index 3c2aae7..0000000 --- a/reverse_engineering/node_modules/optional-require/dist/index.js +++ /dev/null @@ -1,204 +0,0 @@ -"use strict"; -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.optionalRequireCwd = exports.optionalRequire = exports.makeOptionalRequire = exports.tryResolve = exports.tryRequire = exports.setDefaultLog = void 0; -var assert_1 = __importDefault(require("assert")); -var require_at_1 = __importDefault(require("require-at")); -/* eslint-disable max-params, complexity, no-eval */ -// `require` from this module's context -// Using `eval` to avoid tripping bundlers like webpack -var xrequire = eval("require"); -// Copied from https://github.com/yarnpkg/berry/blob/d5454007c9c76becfa97b36a92de299a3694afd5/packages/yarnpkg-pnp/sources/loader/makeApi.ts#L27 -// Splits a require request into its components, or return null if the request is a file path -var pnpDependencyNameRegExp = /^(?![a-zA-Z]:[\\/]|\\\\|\.{0,2}(?:\/|$))((?:node:)?(?:@[^/]+\/)?[^/]+)\/*(.*|)$/; -/** - * Change a module name request into a Yarn Berry PnP dependency name, - * since the dependency name is what will be included in the error message. - * For example, `optionalRequire('my-package/package.json')` will print a message like - * `Your application tried to access my-package,` without the `/package.json` at the end of it. - * This function grabs the dependency name only, or returns `null` if it can't find it. - * @param {string} name Requested name - * @returns {string} Dependency name - */ -function getPnpDependencyName(name) { - var dependencyNameMatch = name.match(pnpDependencyNameRegExp); - if (!dependencyNameMatch) - return null; - return dependencyNameMatch[1]; -} -/** - * Check if an error from require is really due to the module not found, - * and not because the module itself trying to require another module - * that's not found. - * - * @param err - the error - * @param name - name of the module being required - * @returns true or false - */ -function findModuleNotFound(err, name) { - // Check the first line of the error message - var msg = err.message.split("\n")[0]; - /* istanbul ignore if */ - if (!msg) { - return false; - } - // Check for "Cannot find module 'foo'" - if (msg.includes("'" + name + "'")) { - return true; - } - var pnpDependencyName = getPnpDependencyName(name); - if (pnpDependencyName) { - return ( - // Check for "Your application tried to access foo (a peer dependency) ..." (Yarn Berry PnP) - // https://github.com/yarnpkg/berry/blob/e81dc0d29bb2f41818d9c5c1c74bab1406fb979b/packages/yarnpkg-pnp/sources/loader/makeApi.ts#L680 - msg.includes(" " + pnpDependencyName + " ") || - // Check for "Your application tried to access foo. While ..." (Yarn Berry PnP) - // https://github.com/yarnpkg/berry/blob/e81dc0d29bb2f41818d9c5c1c74bab1406fb979b/packages/yarnpkg-pnp/sources/loader/makeApi.ts#L704 - msg.includes(" " + pnpDependencyName + ". ") || - // Check for "Your application tried to access foo, but ..." (Yarn Berry PnP) - // https://github.com/yarnpkg/berry/blob/e81dc0d29bb2f41818d9c5c1c74bab1406fb979b/packages/yarnpkg-pnp/sources/loader/makeApi.ts#L718 - msg.includes(" " + pnpDependencyName + ", ")); - } - return false; -} -/** - * Default log function - * - * @param message - message to log - * @param path - path of the module to require - */ -function defaultLog(message, path) { - console.log("Just FYI: " + message + "; Path \"" + path + "\""); -} -var __defaultLog = defaultLog; -function setDefaultLog(log) { - __defaultLog = log; -} -exports.setDefaultLog = setDefaultLog; -function _getOptions(optsOrMsg, requireFunction, log) { - if (requireFunction === void 0) { requireFunction = xrequire; } - if (typeof optsOrMsg === "object") { - var opts = __assign({ require: requireFunction, log: log }, optsOrMsg); - (0, assert_1.default)(!(opts.hasOwnProperty("notFound") && opts.hasOwnProperty("default")), "optionalRequire: options set with both `notFound` and `default`"); - return opts; - } - else { - return { require: requireFunction, log: log, message: optsOrMsg }; - } -} -/** - * Internal optional require implementation - * - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case module not found - * @returns require or resolve result - */ -function _optionalRequire(path, opts) { - try { - return opts.resolve ? opts.require.resolve(path) : opts.require(path); - } - catch (e) { - // exception that's not due to the module itself not found - if (e.code !== "MODULE_NOT_FOUND" || !findModuleNotFound(e, path)) { - // if the module we are requiring fail because it try to require a - // module that's not found, then we have to report this as failed. - if (typeof opts.fail === "function") { - return opts.fail(e); - } - throw e; - } - if (opts.message) { - var message = opts.message === true ? "" : opts.message + " - "; - var r = opts.resolve ? "resolved" : "found"; - opts.log(message + "optional module not " + r, path); - } - if (typeof opts.notFound === "function") { - return opts.notFound(e); - } - return opts.default; - } -} -/** - * try to require a module with optional handling in case it's not found or fail to require - * - * @param callerRequire - `require` from caller context - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case of exceptions - * @returns require result - */ -function tryRequire(callerRequire, path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, __defaultLog); - opts.resolve = false; - return _optionalRequire(path, opts); -} -exports.tryRequire = tryRequire; -/** - * try to resolve a module with optional handling in case it's not found or fail to require - * - * @param callerRequire - `require` from caller context - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case of exceptions - * @returns resolve result - */ -function tryResolve(callerRequire, path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, __defaultLog); - opts.resolve = true; - return _optionalRequire(path, opts); -} -exports.tryResolve = tryResolve; -/** - * Make an optional require function, using the `require` from caller's context. - * - * @param callerRequire - `require` from caller's context - * @param log - function to log if module is not found - * @returns required module - */ -function makeOptionalRequire(callerRequire, log) { - var x = function (path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, x.log); - return _optionalRequire(path, opts); - }; - x.resolve = function (path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, x.log); - opts.resolve = true; - return _optionalRequire(path, opts); - }; - x.log = log || __defaultLog; - return x; -} -exports.makeOptionalRequire = makeOptionalRequire; -/** - * A default optionalRequire function using `require` from optional-require's context. - * - * @remarks because `require` is from optional-require's context, you won't be able to - * do `optionalRequire("./my-module")`. - * - * You can still override the `require` using `options.require` with the one from your - * calling context. - * - */ -exports.optionalRequire = makeOptionalRequire(xrequire); -/** - * An optionalRequire function using `require` from CWD context - * - * @remarks because `require` is from CWD context, if you do `optionalRequireCwd("./my-module")` - * then it will look for `my-module` in CWD. - * - * @remarks You can still override the `require` using `options.require` with the one from your - * calling context. - */ -exports.optionalRequireCwd = makeOptionalRequire((0, require_at_1.default)(process.cwd())); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/optional-require/dist/index.js.map b/reverse_engineering/node_modules/optional-require/dist/index.js.map deleted file mode 100644 index 5ed9046..0000000 --- a/reverse_engineering/node_modules/optional-require/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,kDAA4B;AAC5B,0DAAmC;AAEnC,oDAAoD;AAEpD,uCAAuC;AACvC,uDAAuD;AACvD,IAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;AAEjC,gJAAgJ;AAChJ,6FAA6F;AAC7F,IAAM,uBAAuB,GAAG,iFAAiF,CAAC;AAElH;;;;;;;;GAQG;AACH,SAAS,oBAAoB,CAAC,IAAY;IACxC,IAAM,mBAAmB,GAAG,IAAI,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAChE,IAAI,CAAC,mBAAmB;QAAE,OAAO,IAAI,CAAC;IACtC,OAAO,mBAAmB,CAAC,CAAC,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,kBAAkB,CAAC,GAAU,EAAE,IAAY;IAClD,4CAA4C;IAC5C,IAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IACvC,wBAAwB;IACxB,IAAI,CAAC,GAAG,EAAE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BAAkB,GAAG,mBAAmB,CAAC,IAAA,oBAAS,EAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/optional-require/index.d.ts b/reverse_engineering/node_modules/optional-require/index.d.ts deleted file mode 100644 index d9976c7..0000000 --- a/reverse_engineering/node_modules/optional-require/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./dist/index.d"; -import { makeOptionalRequire } from "./dist/index.d"; - -// @ts-ignore -export = makeOptionalRequire; diff --git a/reverse_engineering/node_modules/optional-require/index.js b/reverse_engineering/node_modules/optional-require/index.js deleted file mode 100644 index fd56f6e..0000000 --- a/reverse_engineering/node_modules/optional-require/index.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; - -/** - * Compatibility bridge to the new typescript code. - * - */ - -const lib = require("./dist"); - -module.exports = function() { return lib.makeOptionalRequire.apply(lib, arguments); } - -module.exports.tryRequire = lib.tryRequire; -module.exports.tryResolve = lib.tryResolve; -module.exports.try = lib.tryRequire; -module.exports.resolve = lib.tryResolve; -module.exports.makeOptionalRequire = lib.makeOptionalRequire; -module.exports.optionalRequire = lib.optionalRequire; -module.exports.optionalRequireCwd = lib.optionalRequireCwd; -module.exports.optionalRequireTop = lib.optionalRequireTop; - -let __defaultLog; - -Object.defineProperty(module.exports, "log", { - set(func) { - __defaultLog = func; - lib.setDefaultLog(func); - }, - - get() { - return __defaultLog; - }, -}); diff --git a/reverse_engineering/node_modules/optional-require/package.json b/reverse_engineering/node_modules/optional-require/package.json deleted file mode 100644 index 9299d2c..0000000 --- a/reverse_engineering/node_modules/optional-require/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "optional-require", - "version": "1.1.8", - "description": "NodeJS Require that let you handle module not found error without try/catch", - "main": "index.js", - "types": "index.d.ts", - "scripts": { - "build": "tsc", - "test": "xrun --serial build xarc/test-only", - "coverage": "xrun --serial build xarc/test-cov", - "publish-util-pre": "publish-util-prepublishonly", - "prepublishOnly": "xrun --serial [[build, docs], xarc/check, publish-util-pre]", - "docs": "xrun xarc/docs && touch docs/.nojekyll", - "postpack": "publish-util-postpack" - }, - "repository": { - "type": "git", - "url": "https://github.com/jchip/optional-require.git" - }, - "keywords": [ - "optional require", - "optional", - "require" - ], - "files": [ - "dist", - "index.js", - "index.d.ts" - ], - "engines": { - "node": ">=4" - }, - "author": "Joel Chen", - "license": "Apache-2.0", - "dependencies": { - "require-at": "^1.0.6" - } -} diff --git a/reverse_engineering/node_modules/p-limit/index.d.ts b/reverse_engineering/node_modules/p-limit/index.d.ts deleted file mode 100644 index 6bbfad4..0000000 --- a/reverse_engineering/node_modules/p-limit/index.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -export interface Limit { - /** - @param fn - Promise-returning/async function. - @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. - @returns The promise returned by calling `fn(...arguments)`. - */ - ( - fn: (...arguments: Arguments) => PromiseLike | ReturnType, - ...arguments: Arguments - ): Promise; - - /** - The number of promises that are currently running. - */ - readonly activeCount: number; - - /** - The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). - */ - readonly pendingCount: number; - - /** - Discard pending promises that are waiting to run. - - This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. - - Note: This does not cancel promises that are already running. - */ - clearQueue(): void; -} - -/** -Run multiple promise-returning & async functions with limited concurrency. - -@param concurrency - Concurrency limit. Minimum: `1`. -@returns A `limit` function. -*/ -export default function pLimit(concurrency: number): Limit; diff --git a/reverse_engineering/node_modules/p-limit/index.js b/reverse_engineering/node_modules/p-limit/index.js deleted file mode 100644 index 6a72a4c..0000000 --- a/reverse_engineering/node_modules/p-limit/index.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; -const pTry = require('p-try'); - -const pLimit = concurrency => { - if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { - return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); - } - - const queue = []; - let activeCount = 0; - - const next = () => { - activeCount--; - - if (queue.length > 0) { - queue.shift()(); - } - }; - - const run = (fn, resolve, ...args) => { - activeCount++; - - const result = pTry(fn, ...args); - - resolve(result); - - result.then(next, next); - }; - - const enqueue = (fn, resolve, ...args) => { - if (activeCount < concurrency) { - run(fn, resolve, ...args); - } else { - queue.push(run.bind(null, fn, resolve, ...args)); - } - }; - - const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); - Object.defineProperties(generator, { - activeCount: { - get: () => activeCount - }, - pendingCount: { - get: () => queue.length - }, - clearQueue: { - value: () => { - queue.length = 0; - } - } - }); - - return generator; -}; - -module.exports = pLimit; -module.exports.default = pLimit; diff --git a/reverse_engineering/node_modules/p-limit/license b/reverse_engineering/node_modules/p-limit/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/p-limit/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/p-limit/package.json b/reverse_engineering/node_modules/p-limit/package.json deleted file mode 100644 index 99a814f..0000000 --- a/reverse_engineering/node_modules/p-limit/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "p-limit", - "version": "2.3.0", - "description": "Run multiple promise-returning & async functions with limited concurrency", - "license": "MIT", - "repository": "sindresorhus/p-limit", - "funding": "https://github.com/sponsors/sindresorhus", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=6" - }, - "scripts": { - "test": "xo && ava && tsd-check" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "promise", - "limit", - "limited", - "concurrency", - "throttle", - "throat", - "rate", - "batch", - "ratelimit", - "task", - "queue", - "async", - "await", - "promises", - "bluebird" - ], - "dependencies": { - "p-try": "^2.0.0" - }, - "devDependencies": { - "ava": "^1.2.1", - "delay": "^4.1.0", - "in-range": "^1.0.0", - "random-int": "^1.0.0", - "time-span": "^2.0.0", - "tsd-check": "^0.3.0", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/p-limit/readme.md b/reverse_engineering/node_modules/p-limit/readme.md deleted file mode 100644 index 64aa476..0000000 --- a/reverse_engineering/node_modules/p-limit/readme.md +++ /dev/null @@ -1,101 +0,0 @@ -# p-limit [![Build Status](https://travis-ci.org/sindresorhus/p-limit.svg?branch=master)](https://travis-ci.org/sindresorhus/p-limit) - -> Run multiple promise-returning & async functions with limited concurrency - -## Install - -``` -$ npm install p-limit -``` - -## Usage - -```js -const pLimit = require('p-limit'); - -const limit = pLimit(1); - -const input = [ - limit(() => fetchSomething('foo')), - limit(() => fetchSomething('bar')), - limit(() => doSomething()) -]; - -(async () => { - // Only one promise is run at once - const result = await Promise.all(input); - console.log(result); -})(); -``` - -## API - -### pLimit(concurrency) - -Returns a `limit` function. - -#### concurrency - -Type: `number`\ -Minimum: `1`\ -Default: `Infinity` - -Concurrency limit. - -### limit(fn, ...args) - -Returns the promise returned by calling `fn(...args)`. - -#### fn - -Type: `Function` - -Promise-returning/async function. - -#### args - -Any arguments to pass through to `fn`. - -Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. - -### limit.activeCount - -The number of promises that are currently running. - -### limit.pendingCount - -The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). - -### limit.clearQueue() - -Discard pending promises that are waiting to run. - -This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. - -Note: This does not cancel promises that are already running. - -## FAQ - -### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? - -This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. - -## Related - -- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control -- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions -- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions -- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency -- [More…](https://github.com/sindresorhus/promise-fun) - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/reverse_engineering/node_modules/p-locate/index.d.ts b/reverse_engineering/node_modules/p-locate/index.d.ts deleted file mode 100644 index 14115e1..0000000 --- a/reverse_engineering/node_modules/p-locate/index.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -declare namespace pLocate { - interface Options { - /** - Number of concurrently pending promises returned by `tester`. Minimum: `1`. - - @default Infinity - */ - readonly concurrency?: number; - - /** - Preserve `input` order when searching. - - Disable this to improve performance if you don't care about the order. - - @default true - */ - readonly preserveOrder?: boolean; - } -} - -declare const pLocate: { - /** - Get the first fulfilled promise that satisfies the provided testing function. - - @param input - An iterable of promises/values to test. - @param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. - @returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. - - @example - ``` - import pathExists = require('path-exists'); - import pLocate = require('p-locate'); - - const files = [ - 'unicorn.png', - 'rainbow.png', // Only this one actually exists on disk - 'pony.png' - ]; - - (async () => { - const foundPath = await pLocate(files, file => pathExists(file)); - - console.log(foundPath); - //=> 'rainbow' - })(); - ``` - */ - ( - input: Iterable | ValueType>, - tester: (element: ValueType) => PromiseLike | boolean, - options?: pLocate.Options - ): Promise; - - // TODO: Remove this for the next major release, refactor the whole definition to: - // declare function pLocate( - // input: Iterable | ValueType>, - // tester: (element: ValueType) => PromiseLike | boolean, - // options?: pLocate.Options - // ): Promise; - // export = pLocate; - default: typeof pLocate; -}; - -export = pLocate; diff --git a/reverse_engineering/node_modules/p-locate/index.js b/reverse_engineering/node_modules/p-locate/index.js deleted file mode 100644 index e13ce15..0000000 --- a/reverse_engineering/node_modules/p-locate/index.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; -const pLimit = require('p-limit'); - -class EndError extends Error { - constructor(value) { - super(); - this.value = value; - } -} - -// The input can also be a promise, so we await it -const testElement = async (element, tester) => tester(await element); - -// The input can also be a promise, so we `Promise.all()` them both -const finder = async element => { - const values = await Promise.all(element); - if (values[1] === true) { - throw new EndError(values[0]); - } - - return false; -}; - -const pLocate = async (iterable, tester, options) => { - options = { - concurrency: Infinity, - preserveOrder: true, - ...options - }; - - const limit = pLimit(options.concurrency); - - // Start all the promises concurrently with optional limit - const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); - - // Check the promises either serially or concurrently - const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); - - try { - await Promise.all(items.map(element => checkLimit(finder, element))); - } catch (error) { - if (error instanceof EndError) { - return error.value; - } - - throw error; - } -}; - -module.exports = pLocate; -// TODO: Remove this for the next major release -module.exports.default = pLocate; diff --git a/reverse_engineering/node_modules/p-locate/license b/reverse_engineering/node_modules/p-locate/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/p-locate/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/p-locate/package.json b/reverse_engineering/node_modules/p-locate/package.json deleted file mode 100644 index e3de275..0000000 --- a/reverse_engineering/node_modules/p-locate/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "p-locate", - "version": "4.1.0", - "description": "Get the first fulfilled promise that satisfies the provided testing function", - "license": "MIT", - "repository": "sindresorhus/p-locate", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "promise", - "locate", - "find", - "finder", - "search", - "searcher", - "test", - "array", - "collection", - "iterable", - "iterator", - "race", - "fulfilled", - "fastest", - "async", - "await", - "promises", - "bluebird" - ], - "dependencies": { - "p-limit": "^2.2.0" - }, - "devDependencies": { - "ava": "^1.4.1", - "delay": "^4.1.0", - "in-range": "^1.0.0", - "time-span": "^3.0.0", - "tsd": "^0.7.2", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/p-locate/readme.md b/reverse_engineering/node_modules/p-locate/readme.md deleted file mode 100644 index f8e2c2e..0000000 --- a/reverse_engineering/node_modules/p-locate/readme.md +++ /dev/null @@ -1,90 +0,0 @@ -# p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/p-locate) - -> Get the first fulfilled promise that satisfies the provided testing function - -Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). - - -## Install - -``` -$ npm install p-locate -``` - - -## Usage - -Here we find the first file that exists on disk, in array order. - -```js -const pathExists = require('path-exists'); -const pLocate = require('p-locate'); - -const files = [ - 'unicorn.png', - 'rainbow.png', // Only this one actually exists on disk - 'pony.png' -]; - -(async () => { - const foundPath = await pLocate(files, file => pathExists(file)); - - console.log(foundPath); - //=> 'rainbow' -})(); -``` - -*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* - - -## API - -### pLocate(input, tester, [options]) - -Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. - -#### input - -Type: `Iterable` - -An iterable of promises/values to test. - -#### tester(element) - -Type: `Function` - -This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. - -#### options - -Type: `Object` - -##### concurrency - -Type: `number`
-Default: `Infinity`
-Minimum: `1` - -Number of concurrently pending promises returned by `tester`. - -##### preserveOrder - -Type: `boolean`
-Default: `true` - -Preserve `input` order when searching. - -Disable this to improve performance if you don't care about the order. - - -## Related - -- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently -- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently -- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled -- [More…](https://github.com/sindresorhus/promise-fun) - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/reverse_engineering/node_modules/p-try/index.d.ts b/reverse_engineering/node_modules/p-try/index.d.ts deleted file mode 100644 index 2a7319e..0000000 --- a/reverse_engineering/node_modules/p-try/index.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -declare const pTry: { - /** - Start a promise chain. - - @param fn - The function to run to start the promise chain. - @param arguments - Arguments to pass to `fn`. - @returns The value of calling `fn(...arguments)`. If the function throws an error, the returned `Promise` will be rejected with that error. - - @example - ``` - import pTry = require('p-try'); - - (async () => { - try { - const value = await pTry(() => { - return synchronousFunctionThatMightThrow(); - }); - console.log(value); - } catch (error) { - console.error(error); - } - })(); - ``` - */ - ( - fn: (...arguments: ArgumentsType) => PromiseLike | ValueType, - ...arguments: ArgumentsType - ): Promise; - - // TODO: remove this in the next major version, refactor the whole definition to: - // declare function pTry( - // fn: (...arguments: ArgumentsType) => PromiseLike | ValueType, - // ...arguments: ArgumentsType - // ): Promise; - // export = pTry; - default: typeof pTry; -}; - -export = pTry; diff --git a/reverse_engineering/node_modules/p-try/index.js b/reverse_engineering/node_modules/p-try/index.js deleted file mode 100644 index db858da..0000000 --- a/reverse_engineering/node_modules/p-try/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -const pTry = (fn, ...arguments_) => new Promise(resolve => { - resolve(fn(...arguments_)); -}); - -module.exports = pTry; -// TODO: remove this in the next major version -module.exports.default = pTry; diff --git a/reverse_engineering/node_modules/p-try/license b/reverse_engineering/node_modules/p-try/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/p-try/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/p-try/package.json b/reverse_engineering/node_modules/p-try/package.json deleted file mode 100644 index 81c4d32..0000000 --- a/reverse_engineering/node_modules/p-try/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "p-try", - "version": "2.2.0", - "description": "`Start a promise chain", - "license": "MIT", - "repository": "sindresorhus/p-try", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=6" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "promise", - "try", - "resolve", - "function", - "catch", - "async", - "await", - "promises", - "settled", - "ponyfill", - "polyfill", - "shim", - "bluebird" - ], - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.1", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/p-try/readme.md b/reverse_engineering/node_modules/p-try/readme.md deleted file mode 100644 index 4d7bd64..0000000 --- a/reverse_engineering/node_modules/p-try/readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# p-try [![Build Status](https://travis-ci.org/sindresorhus/p-try.svg?branch=master)](https://travis-ci.org/sindresorhus/p-try) - -> Start a promise chain - -[How is it useful?](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/) - - -## Install - -``` -$ npm install p-try -``` - - -## Usage - -```js -const pTry = require('p-try'); - -(async () => { - try { - const value = await pTry(() => { - return synchronousFunctionThatMightThrow(); - }); - console.log(value); - } catch (error) { - console.error(error); - } -})(); -``` - - -## API - -### pTry(fn, ...arguments) - -Returns a `Promise` resolved with the value of calling `fn(...arguments)`. If the function throws an error, the returned `Promise` will be rejected with that error. - -Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. - -#### fn - -The function to run to start the promise chain. - -#### arguments - -Arguments to pass to `fn`. - - -## Related - -- [p-finally](https://github.com/sindresorhus/p-finally) - `Promise#finally()` ponyfill - Invoked when the promise is settled regardless of outcome -- [More…](https://github.com/sindresorhus/promise-fun) - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/reverse_engineering/node_modules/path-exists/index.d.ts b/reverse_engineering/node_modules/path-exists/index.d.ts deleted file mode 100644 index 54b7ab8..0000000 --- a/reverse_engineering/node_modules/path-exists/index.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -declare const pathExists: { - /** - Check if a path exists. - - @returns Whether the path exists. - - @example - ``` - // foo.ts - import pathExists = require('path-exists'); - - (async () => { - console.log(await pathExists('foo.ts')); - //=> true - })(); - ``` - */ - (path: string): Promise; - - /** - Synchronously check if a path exists. - - @returns Whether the path exists. - */ - sync(path: string): boolean; -}; - -export = pathExists; diff --git a/reverse_engineering/node_modules/path-exists/index.js b/reverse_engineering/node_modules/path-exists/index.js deleted file mode 100644 index 1943921..0000000 --- a/reverse_engineering/node_modules/path-exists/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; -const fs = require('fs'); -const {promisify} = require('util'); - -const pAccess = promisify(fs.access); - -module.exports = async path => { - try { - await pAccess(path); - return true; - } catch (_) { - return false; - } -}; - -module.exports.sync = path => { - try { - fs.accessSync(path); - return true; - } catch (_) { - return false; - } -}; diff --git a/reverse_engineering/node_modules/path-exists/license b/reverse_engineering/node_modules/path-exists/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/path-exists/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/path-exists/package.json b/reverse_engineering/node_modules/path-exists/package.json deleted file mode 100644 index 0755256..0000000 --- a/reverse_engineering/node_modules/path-exists/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "path-exists", - "version": "4.0.0", - "description": "Check if a path exists", - "license": "MIT", - "repository": "sindresorhus/path-exists", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "path", - "exists", - "exist", - "file", - "filepath", - "fs", - "filesystem", - "file-system", - "access", - "stat" - ], - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.2", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/path-exists/readme.md b/reverse_engineering/node_modules/path-exists/readme.md deleted file mode 100644 index 81f9845..0000000 --- a/reverse_engineering/node_modules/path-exists/readme.md +++ /dev/null @@ -1,52 +0,0 @@ -# path-exists [![Build Status](https://travis-ci.org/sindresorhus/path-exists.svg?branch=master)](https://travis-ci.org/sindresorhus/path-exists) - -> Check if a path exists - -NOTE: `fs.existsSync` has been un-deprecated in Node.js since 6.8.0. If you only need to check synchronously, this module is not needed. - -While [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback) is being [deprecated](https://github.com/iojs/io.js/issues/103), there's still a genuine use-case of being able to check if a path exists for other purposes than doing IO with it. - -Never use this before handling a file though: - -> In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. - - -## Install - -``` -$ npm install path-exists -``` - - -## Usage - -```js -// foo.js -const pathExists = require('path-exists'); - -(async () => { - console.log(await pathExists('foo.js')); - //=> true -})(); -``` - - -## API - -### pathExists(path) - -Returns a `Promise` of whether the path exists. - -### pathExists.sync(path) - -Returns a `boolean` of whether the path exists. - - -## Related - -- [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/reverse_engineering/node_modules/pause-stream/.npmignore b/reverse_engineering/node_modules/pause-stream/.npmignore deleted file mode 100644 index 13abef4..0000000 --- a/reverse_engineering/node_modules/pause-stream/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -node_modules/* -npm_debug.log diff --git a/reverse_engineering/node_modules/pause-stream/LICENSE b/reverse_engineering/node_modules/pause-stream/LICENSE deleted file mode 100644 index 6a477d4..0000000 --- a/reverse_engineering/node_modules/pause-stream/LICENSE +++ /dev/null @@ -1,231 +0,0 @@ -Dual Licensed MIT and Apache 2 - -The MIT License - -Copyright (c) 2013 Dominic Tarr - -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom -the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - ----------------------------------------------------------------------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright (c) 2013 Dominic Tarr - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/reverse_engineering/node_modules/pause-stream/index.js b/reverse_engineering/node_modules/pause-stream/index.js deleted file mode 100644 index 0e0bf96..0000000 --- a/reverse_engineering/node_modules/pause-stream/index.js +++ /dev/null @@ -1,3 +0,0 @@ -//through@2 handles this by default! -module.exports = require('through') - diff --git a/reverse_engineering/node_modules/pause-stream/package.json b/reverse_engineering/node_modules/pause-stream/package.json deleted file mode 100644 index 2a22646..0000000 --- a/reverse_engineering/node_modules/pause-stream/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "pause-stream", - "version": "0.0.11", - "description": "a ThroughStream that strictly buffers all readable events when paused.", - "main": "index.js", - "directories": { - "test": "test" - }, - "devDependencies": { - "stream-tester": "0.0.2", - "stream-spec": "~0.2.0" - }, - "scripts": { - "test": "node test/index.js && node test/pause-end.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/dominictarr/pause-stream.git" - }, - "keywords": [ - "stream", - "pipe", - "pause", - "drain", - "buffer" - ], - "author": "Dominic Tarr (dominictarr.com)", - "license": [ - "MIT", - "Apache2" - ], - "dependencies": { - "through": "~2.3" - } -} diff --git a/reverse_engineering/node_modules/pause-stream/readme.markdown b/reverse_engineering/node_modules/pause-stream/readme.markdown deleted file mode 100644 index 2366939..0000000 --- a/reverse_engineering/node_modules/pause-stream/readme.markdown +++ /dev/null @@ -1,29 +0,0 @@ -# PauseStream - -This is a `Stream` that will strictly buffer when paused. -Connect it to anything you need buffered. - -``` js - var ps = require('pause-stream')(); - - badlyBehavedStream.pipe(ps.pause()) - - aLittleLater(function (err, data) { - ps.pipe(createAnotherStream(data)) - ps.resume() - }) -``` - -`PauseStream` will buffer whenever paused. -it will buffer when yau have called `pause` manually. -but also when it's downstream `dest.write()===false`. -it will attempt to drain the buffer when you call resume -or the downstream emits `'drain'` - -`PauseStream` is tested using [stream-spec](https://github.com/dominictarr/stream-spec) -and [stream-tester](https://github.com/dominictarr/stream-tester) - -This is now the default case of -[through](https://github.com/dominictarr/through) - -https://github.com/dominictarr/pause-stream/commit/4a6fe3dc2c11091b1efbfde912e0473719ed9cc0 diff --git a/reverse_engineering/node_modules/pause-stream/test/index.js b/reverse_engineering/node_modules/pause-stream/test/index.js deleted file mode 100644 index db8778d..0000000 --- a/reverse_engineering/node_modules/pause-stream/test/index.js +++ /dev/null @@ -1,17 +0,0 @@ -var spec = require('stream-spec') -var tester = require('stream-tester') -var ps = require('..')() - -spec(ps) - .through({strict: false}) - .validateOnExit() - -var master = tester.createConsistent - -tester.createRandomStream(1000) //1k random numbers - .pipe(master = tester.createConsistentStream()) - .pipe(tester.createUnpauseStream()) - .pipe(ps) - .pipe(tester.createPauseStream()) - .pipe(master.createSlave()) - diff --git a/reverse_engineering/node_modules/pause-stream/test/pause-end.js b/reverse_engineering/node_modules/pause-stream/test/pause-end.js deleted file mode 100644 index a6c27ef..0000000 --- a/reverse_engineering/node_modules/pause-stream/test/pause-end.js +++ /dev/null @@ -1,33 +0,0 @@ - -var pause = require('..') -var assert = require('assert') - -var ps = pause() -var read = [], ended = false - -ps.on('data', function (i) { - read.push(i) -}) - -ps.on('end', function () { - ended = true -}) - -assert.deepEqual(read, []) - -ps.write(0) -ps.write(1) -ps.write(2) - -assert.deepEqual(read, [0, 1, 2]) - -ps.pause() - -assert.deepEqual(read, [0, 1, 2]) - -ps.end() -assert.equal(ended, false) -ps.resume() -assert.equal(ended, true) - - diff --git a/reverse_engineering/node_modules/process-nextick-args/index.js b/reverse_engineering/node_modules/process-nextick-args/index.js deleted file mode 100644 index 3eecf11..0000000 --- a/reverse_engineering/node_modules/process-nextick-args/index.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -if (typeof process === 'undefined' || - !process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = { nextTick: nextTick }; -} else { - module.exports = process -} - -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} - diff --git a/reverse_engineering/node_modules/process-nextick-args/license.md b/reverse_engineering/node_modules/process-nextick-args/license.md deleted file mode 100644 index c67e353..0000000 --- a/reverse_engineering/node_modules/process-nextick-args/license.md +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2015 Calvin Metcalf - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE.** diff --git a/reverse_engineering/node_modules/process-nextick-args/package.json b/reverse_engineering/node_modules/process-nextick-args/package.json deleted file mode 100644 index 6070b72..0000000 --- a/reverse_engineering/node_modules/process-nextick-args/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "process-nextick-args", - "version": "2.0.1", - "description": "process.nextTick but always with args", - "main": "index.js", - "files": [ - "index.js" - ], - "scripts": { - "test": "node test.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/calvinmetcalf/process-nextick-args.git" - }, - "author": "", - "license": "MIT", - "bugs": { - "url": "https://github.com/calvinmetcalf/process-nextick-args/issues" - }, - "homepage": "https://github.com/calvinmetcalf/process-nextick-args", - "devDependencies": { - "tap": "~0.2.6" - } -} diff --git a/reverse_engineering/node_modules/process-nextick-args/readme.md b/reverse_engineering/node_modules/process-nextick-args/readme.md deleted file mode 100644 index ecb432c..0000000 --- a/reverse_engineering/node_modules/process-nextick-args/readme.md +++ /dev/null @@ -1,18 +0,0 @@ -process-nextick-args -===== - -[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args) - -```bash -npm install --save process-nextick-args -``` - -Always be able to pass arguments to process.nextTick, no matter the platform - -```js -var pna = require('process-nextick-args'); - -pna.nextTick(function (a, b, c) { - console.log(a, b, c); -}, 'step', 3, 'profit'); -``` diff --git a/reverse_engineering/node_modules/readable-stream/.travis.yml b/reverse_engineering/node_modules/readable-stream/.travis.yml deleted file mode 100644 index f62cdac..0000000 --- a/reverse_engineering/node_modules/readable-stream/.travis.yml +++ /dev/null @@ -1,34 +0,0 @@ -sudo: false -language: node_js -before_install: - - (test $NPM_LEGACY && npm install -g npm@2 && npm install -g npm@3) || true -notifications: - email: false -matrix: - fast_finish: true - include: - - node_js: '0.8' - env: NPM_LEGACY=true - - node_js: '0.10' - env: NPM_LEGACY=true - - node_js: '0.11' - env: NPM_LEGACY=true - - node_js: '0.12' - env: NPM_LEGACY=true - - node_js: 1 - env: NPM_LEGACY=true - - node_js: 2 - env: NPM_LEGACY=true - - node_js: 3 - env: NPM_LEGACY=true - - node_js: 4 - - node_js: 5 - - node_js: 6 - - node_js: 7 - - node_js: 8 - - node_js: 9 -script: "npm run test" -env: - global: - - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc= - - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI= diff --git a/reverse_engineering/node_modules/readable-stream/CONTRIBUTING.md b/reverse_engineering/node_modules/readable-stream/CONTRIBUTING.md deleted file mode 100644 index f478d58..0000000 --- a/reverse_engineering/node_modules/readable-stream/CONTRIBUTING.md +++ /dev/null @@ -1,38 +0,0 @@ -# Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -* (a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -* (b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -* (c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -* (d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. - -## Moderation Policy - -The [Node.js Moderation Policy] applies to this WG. - -## Code of Conduct - -The [Node.js Code of Conduct][] applies to this WG. - -[Node.js Code of Conduct]: -https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md -[Node.js Moderation Policy]: -https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/reverse_engineering/node_modules/readable-stream/GOVERNANCE.md b/reverse_engineering/node_modules/readable-stream/GOVERNANCE.md deleted file mode 100644 index 16ffb93..0000000 --- a/reverse_engineering/node_modules/readable-stream/GOVERNANCE.md +++ /dev/null @@ -1,136 +0,0 @@ -### Streams Working Group - -The Node.js Streams is jointly governed by a Working Group -(WG) -that is responsible for high-level guidance of the project. - -The WG has final authority over this project including: - -* Technical direction -* Project governance and process (including this policy) -* Contribution policy -* GitHub repository hosting -* Conduct guidelines -* Maintaining the list of additional Collaborators - -For the current list of WG members, see the project -[README.md](./README.md#current-project-team-members). - -### Collaborators - -The readable-stream GitHub repository is -maintained by the WG and additional Collaborators who are added by the -WG on an ongoing basis. - -Individuals making significant and valuable contributions are made -Collaborators and given commit-access to the project. These -individuals are identified by the WG and their addition as -Collaborators is discussed during the WG meeting. - -_Note:_ If you make a significant contribution and are not considered -for commit-access log an issue or contact a WG member directly and it -will be brought up in the next WG meeting. - -Modifications of the contents of the readable-stream repository are -made on -a collaborative basis. Anybody with a GitHub account may propose a -modification via pull request and it will be considered by the project -Collaborators. All pull requests must be reviewed and accepted by a -Collaborator with sufficient expertise who is able to take full -responsibility for the change. In the case of pull requests proposed -by an existing Collaborator, an additional Collaborator is required -for sign-off. Consensus should be sought if additional Collaborators -participate and there is disagreement around a particular -modification. See _Consensus Seeking Process_ below for further detail -on the consensus model used for governance. - -Collaborators may opt to elevate significant or controversial -modifications, or modifications that have not found consensus to the -WG for discussion by assigning the ***WG-agenda*** tag to a pull -request or issue. The WG should serve as the final arbiter where -required. - -For the current list of Collaborators, see the project -[README.md](./README.md#members). - -### WG Membership - -WG seats are not time-limited. There is no fixed size of the WG. -However, the expected target is between 6 and 12, to ensure adequate -coverage of important areas of expertise, balanced with the ability to -make decisions efficiently. - -There is no specific set of requirements or qualifications for WG -membership beyond these rules. - -The WG may add additional members to the WG by unanimous consensus. - -A WG member may be removed from the WG by voluntary resignation, or by -unanimous consensus of all other WG members. - -Changes to WG membership should be posted in the agenda, and may be -suggested as any other agenda item (see "WG Meetings" below). - -If an addition or removal is proposed during a meeting, and the full -WG is not in attendance to participate, then the addition or removal -is added to the agenda for the subsequent meeting. This is to ensure -that all members are given the opportunity to participate in all -membership decisions. If a WG member is unable to attend a meeting -where a planned membership decision is being made, then their consent -is assumed. - -No more than 1/3 of the WG members may be affiliated with the same -employer. If removal or resignation of a WG member, or a change of -employment by a WG member, creates a situation where more than 1/3 of -the WG membership shares an employer, then the situation must be -immediately remedied by the resignation or removal of one or more WG -members affiliated with the over-represented employer(s). - -### WG Meetings - -The WG meets occasionally on a Google Hangout On Air. A designated moderator -approved by the WG runs the meeting. Each meeting should be -published to YouTube. - -Items are added to the WG agenda that are considered contentious or -are modifications of governance, contribution policy, WG membership, -or release process. - -The intention of the agenda is not to approve or review all patches; -that should happen continuously on GitHub and be handled by the larger -group of Collaborators. - -Any community member or contributor can ask that something be added to -the next meeting's agenda by logging a GitHub Issue. Any Collaborator, -WG member or the moderator can add the item to the agenda by adding -the ***WG-agenda*** tag to the issue. - -Prior to each WG meeting the moderator will share the Agenda with -members of the WG. WG members can add any items they like to the -agenda at the beginning of each meeting. The moderator and the WG -cannot veto or remove items. - -The WG may invite persons or representatives from certain projects to -participate in a non-voting capacity. - -The moderator is responsible for summarizing the discussion of each -agenda item and sends it as a pull request after the meeting. - -### Consensus Seeking Process - -The WG follows a -[Consensus -Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) -decision-making model. - -When an agenda item has appeared to reach a consensus the moderator -will ask "Does anyone object?" as a final call for dissent from the -consensus. - -If an agenda item cannot reach a consensus a WG member can call for -either a closing vote or a vote to table the issue to the next -meeting. The call for a vote must be seconded by a majority of the WG -or else the discussion will continue. Simple majority wins. - -Note that changes to WG membership require a majority consensus. See -"WG Membership" above. diff --git a/reverse_engineering/node_modules/readable-stream/LICENSE b/reverse_engineering/node_modules/readable-stream/LICENSE deleted file mode 100644 index 2873b3b..0000000 --- a/reverse_engineering/node_modules/readable-stream/LICENSE +++ /dev/null @@ -1,47 +0,0 @@ -Node.js is licensed for use as follows: - -""" -Copyright Node.js contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" - -This license applies to parts of Node.js originating from the -https://github.com/joyent/node repository: - -""" -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" diff --git a/reverse_engineering/node_modules/readable-stream/README.md b/reverse_engineering/node_modules/readable-stream/README.md deleted file mode 100644 index 23fe3f3..0000000 --- a/reverse_engineering/node_modules/readable-stream/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# readable-stream - -***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) - - -[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) -[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) - - -[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) - -```bash -npm install --save readable-stream -``` - -***Node-core streams for userland*** - -This package is a mirror of the Streams2 and Streams3 implementations in -Node-core. - -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html). - -If you want to guarantee a stable streams base, regardless of what version of -Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). - -As of version 2.0.0 **readable-stream** uses semantic versioning. - -# Streams Working Group - -`readable-stream` is maintained by the Streams Working Group, which -oversees the development and maintenance of the Streams API within -Node.js. The responsibilities of the Streams Working Group include: - -* Addressing stream issues on the Node.js issue tracker. -* Authoring and editing stream documentation within the Node.js project. -* Reviewing changes to stream subclasses within the Node.js project. -* Redirecting changes to streams from the Node.js project to this - project. -* Assisting in the implementation of stream providers within Node.js. -* Recommending versions of `readable-stream` to be included in Node.js. -* Messaging about the future of streams to give the community advance - notice of changes. - - -## Team Members - -* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <christopher.s.dickinson@gmail.com> - - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B -* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> - - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 -* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org> - - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D -* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <newmansam@outlook.com> -* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> -* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me> -* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> - - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E -* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> diff --git a/reverse_engineering/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/reverse_engineering/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md deleted file mode 100644 index 83275f1..0000000 --- a/reverse_engineering/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md +++ /dev/null @@ -1,60 +0,0 @@ -# streams WG Meeting 2015-01-30 - -## Links - -* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg -* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106 -* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/ - -## Agenda - -Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting. - -* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105) -* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101) -* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102) -* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99) - -## Minutes - -### adopt a charter - -* group: +1's all around - -### What versioning scheme should be adopted? -* group: +1’s 3.0.0 -* domenic+group: pulling in patches from other sources where appropriate -* mikeal: version independently, suggesting versions for io.js -* mikeal+domenic: work with TC to notify in advance of changes -simpler stream creation - -### streamline creation of streams -* sam: streamline creation of streams -* domenic: nice simple solution posted - but, we lose the opportunity to change the model - may not be backwards incompatible (double check keys) - - **action item:** domenic will check - -### remove implicit flowing of streams on(‘data’) -* add isFlowing / isPaused -* mikeal: worrying that we’re documenting polyfill methods – confuses users -* domenic: more reflective API is probably good, with warning labels for users -* new section for mad scientists (reflective stream access) -* calvin: name the “third state” -* mikeal: maybe borrow the name from whatwg? -* domenic: we’re missing the “third state” -* consensus: kind of difficult to name the third state -* mikeal: figure out differences in states / compat -* mathias: always flow on data – eliminates third state - * explore what it breaks - -**action items:** -* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream) -* ask rod/build for infrastructure -* **chris**: explore the “flow on data” approach -* add isPaused/isFlowing -* add new docs section -* move isPaused to that section - - diff --git a/reverse_engineering/node_modules/readable-stream/duplex-browser.js b/reverse_engineering/node_modules/readable-stream/duplex-browser.js deleted file mode 100644 index f8b2db8..0000000 --- a/reverse_engineering/node_modules/readable-stream/duplex-browser.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/_stream_duplex.js'); diff --git a/reverse_engineering/node_modules/readable-stream/duplex.js b/reverse_engineering/node_modules/readable-stream/duplex.js deleted file mode 100644 index 46924cb..0000000 --- a/reverse_engineering/node_modules/readable-stream/duplex.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./readable').Duplex diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_duplex.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100644 index 57003c3..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -'use strict'; - -/**/ - -var pna = require('process-nextick-args'); -/**/ - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ - -module.exports = Duplex; - -/**/ -var util = Object.create(require('core-util-is')); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); - -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); - - pna.nextTick(cb, err); -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_passthrough.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_passthrough.js deleted file mode 100644 index 612edb4..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_passthrough.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = Object.create(require('core-util-is')); -util.inherits = require('inherits'); -/**/ - -util.inherits(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); -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_readable.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_readable.js deleted file mode 100644 index 0f80764..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_readable.js +++ /dev/null @@ -1,1019 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -/**/ - -var pna = require('process-nextick-args'); -/**/ - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = require('events').EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = require('./internal/streams/stream'); -/**/ - -/**/ - -var Buffer = require('safe-buffer').Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ - -/**/ -var util = Object.create(require('core-util-is')); -util.inherits = require('inherits'); -/**/ - -/**/ -var debugUtil = require('util'); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = require('./internal/streams/BufferList'); -var destroyImpl = require('./internal/streams/destroy'); -var StringDecoder; - -util.inherits(Readable, Stream); - -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); - - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); - - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // has it been destroyed - this.destroyed = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); - -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } 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; - } - } - - return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - 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); -} - -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || 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 we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - - return ret; -}; - -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - 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); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this, unpipeInfo); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - 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 (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } - - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; - } -}); - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_transform.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_transform.js deleted file mode 100644 index fcfc105..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_transform.js +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -'use strict'; - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = Object.create(require('core-util-is')); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } - - ts.writechunk = null; - ts.writecb = null; - - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - - cb(er); - - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; - } - - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_writable.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_writable.js deleted file mode 100644 index b0b0220..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_writable.js +++ /dev/null @@ -1,687 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - -'use strict'; - -/**/ - -var pna = require('process-nextick-args'); -/**/ - -module.exports = Writable; - -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var util = Object.create(require('core-util-is')); -util.inherits = require('inherits'); -/**/ - -/**/ -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ -var Stream = require('./internal/streams/stream'); -/**/ - -/**/ - -var Buffer = require('safe-buffer').Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ - -var destroyImpl = require('./internal/streams/destroy'); - -util.inherits(Writable, Stream); - -function nop() {} - -function WritableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); - - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // if _final has been called - this.finalCalled = false; - - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // has it been destroyed - this.destroyed = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); - -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - - if (typeof options.writev === 'function') this._writev = options.writev; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; - -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); -} - -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - - return ret; -}; - -Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; - } else { - state.corkedRequestsFree = corkReq; - } -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); - -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/BufferList.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/BufferList.js deleted file mode 100644 index aefc68b..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/BufferList.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = require('safe-buffer').Buffer; -var util = require('util'); - -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} - -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; - - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - - return BufferList; -}(); - -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/destroy.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/destroy.js deleted file mode 100644 index 5a0a0d8..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/destroy.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; - -/**/ - -var pna = require('process-nextick-args'); -/**/ - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - pna.nextTick(emitErrorNT, this, err); - } - return this; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } - - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } - }); - - return this; -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream-browser.js deleted file mode 100644 index 9332a3f..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream-browser.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('events').EventEmitter; diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream.js deleted file mode 100644 index ce2ad5b..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('stream'); diff --git a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/LICENSE b/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/README.md b/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg -[travis-url]: https://travis-ci.org/feross/safe-buffer -[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg -[npm-url]: https://npmjs.org/package/safe-buffer -[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg -[downloads-url]: https://npmjs.org/package/safe-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### Safer Node.js Buffer API - -**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, -`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** - -**Uses the built-in implementation when available.** - -## install - -``` -npm install safe-buffer -``` - -## usage - -The goal of this package is to provide a safe replacement for the node.js `Buffer`. - -It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to -the top of your node.js modules: - -```js -var Buffer = require('safe-buffer').Buffer - -// Existing buffer code will continue to work without issues: - -new Buffer('hey', 'utf8') -new Buffer([1, 2, 3], 'utf8') -new Buffer(obj) -new Buffer(16) // create an uninitialized buffer (potentially unsafe) - -// But you can use these new explicit APIs to make clear what you want: - -Buffer.from('hey', 'utf8') // convert from many types to a Buffer -Buffer.alloc(16) // create a zero-filled buffer (safe) -Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) -``` - -## api - -### Class Method: Buffer.from(array) - - -* `array` {Array} - -Allocates a new `Buffer` using an `array` of octets. - -```js -const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); - // creates a new Buffer containing ASCII bytes - // ['b','u','f','f','e','r'] -``` - -A `TypeError` will be thrown if `array` is not an `Array`. - -### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - - -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or - a `new ArrayBuffer()` -* `byteOffset` {Number} Default: `0` -* `length` {Number} Default: `arrayBuffer.length - byteOffset` - -When passed a reference to the `.buffer` property of a `TypedArray` instance, -the newly created `Buffer` will share the same allocated memory as the -TypedArray. - -```js -const arr = new Uint16Array(2); -arr[0] = 5000; -arr[1] = 4000; - -const buf = Buffer.from(arr.buffer); // shares the memory with arr; - -console.log(buf); - // Prints: - -// changing the TypedArray changes the Buffer also -arr[1] = 6000; - -console.log(buf); - // Prints: -``` - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const ab = new ArrayBuffer(10); -const buf = Buffer.from(ab, 0, 2); -console.log(buf.length); - // Prints: 2 -``` - -A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. - -### Class Method: Buffer.from(buffer) - - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = Buffer.from('buffer'); -const buf2 = Buffer.from(buf1); - -buf1[0] = 0x61; -console.log(buf1.toString()); - // 'auffer' -console.log(buf2.toString()); - // 'buffer' (copy is not changed) -``` - -A `TypeError` will be thrown if `buffer` is not a `Buffer`. - -### Class Method: Buffer.from(str[, encoding]) - - -* `str` {String} String to encode. -* `encoding` {String} Encoding to use, Default: `'utf8'` - -Creates a new `Buffer` containing the given JavaScript string `str`. If -provided, the `encoding` parameter identifies the character encoding. -If not provided, `encoding` defaults to `'utf8'`. - -```js -const buf1 = Buffer.from('this is a tést'); -console.log(buf1.toString()); - // prints: this is a tést -console.log(buf1.toString('ascii')); - // prints: this is a tC)st - -const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); -console.log(buf2.toString()); - // prints: this is a tést -``` - -A `TypeError` will be thrown if `str` is not a string. - -### Class Method: Buffer.alloc(size[, fill[, encoding]]) - - -* `size` {Number} -* `fill` {Value} Default: `undefined` -* `encoding` {String} Default: `utf8` - -Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the -`Buffer` will be *zero-filled*. - -```js -const buf = Buffer.alloc(5); -console.log(buf); - // -``` - -The `size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -If `fill` is specified, the allocated `Buffer` will be initialized by calling -`buf.fill(fill)`. See [`buf.fill()`][] for more information. - -```js -const buf = Buffer.alloc(5, 'a'); -console.log(buf); - // -``` - -If both `fill` and `encoding` are specified, the allocated `Buffer` will be -initialized by calling `buf.fill(fill, encoding)`. For example: - -```js -const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -console.log(buf); - // -``` - -Calling `Buffer.alloc(size)` can be significantly slower than the alternative -`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance -contents will *never contain sensitive data*. - -A `TypeError` will be thrown if `size` is not a number. - -### Class Method: Buffer.allocUnsafe(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must -be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit -architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is -thrown. A zero-length Buffer will be created if a `size` less than or equal to -0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -```js -const buf = Buffer.allocUnsafe(5); -console.log(buf); - // - // (octets will be different, every time) -buf.fill(0); -console.log(buf); - // -``` - -A `TypeError` will be thrown if `size` is not a number. - -Note that the `Buffer` module pre-allocates an internal `Buffer` instance of -size `Buffer.poolSize` that is used as a pool for the fast allocation of new -`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated -`new Buffer(size)` constructor) only when `size` is less than or equal to -`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default -value of `Buffer.poolSize` is `8192` but can be modified. - -Use of this pre-allocated internal memory pool is a key difference between -calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. -Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer -pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal -Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The -difference is subtle but can be important when an application requires the -additional performance that `Buffer.allocUnsafe(size)` provides. - -### Class Method: Buffer.allocUnsafeSlow(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The -`size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, -allocations under 4KB are, by default, sliced from a single pre-allocated -`Buffer`. This allows applications to avoid the garbage collection overhead of -creating many individually allocated Buffers. This approach improves both -performance and memory usage by eliminating the need to track and cleanup as -many `Persistent` objects. - -However, in the case where a developer may need to retain a small chunk of -memory from a pool for an indeterminate amount of time, it may be appropriate -to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then -copy out the relevant bits. - -```js -// need to keep around a few small chunks of memory -const store = []; - -socket.on('readable', () => { - const data = socket.read(); - // allocate for retained data - const sb = Buffer.allocUnsafeSlow(10); - // copy the data into the new allocation - data.copy(sb, 0, 0, 10); - store.push(sb); -}); -``` - -Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* -a developer has observed undue memory retention in their applications. - -A `TypeError` will be thrown if `size` is not a number. - -### All the Rest - -The rest of the `Buffer` API is exactly the same as in node.js. -[See the docs](https://nodejs.org/api/buffer.html). - - -## Related links - -- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) -- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) - -## Why is `Buffer` unsafe? - -Today, the node.js `Buffer` constructor is overloaded to handle many different argument -types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), -`ArrayBuffer`, and also `Number`. - -The API is optimized for convenience: you can throw any type at it, and it will try to do -what you want. - -Because the Buffer constructor is so powerful, you often see code like this: - -```js -// Convert UTF-8 strings to hex -function toHex (str) { - return new Buffer(str).toString('hex') -} -``` - -***But what happens if `toHex` is called with a `Number` argument?*** - -### Remote Memory Disclosure - -If an attacker can make your program call the `Buffer` constructor with a `Number` -argument, then they can make it allocate uninitialized memory from the node.js process. -This could potentially disclose TLS private keys, user data, or database passwords. - -When the `Buffer` constructor is passed a `Number` argument, it returns an -**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like -this, you **MUST** overwrite the contents before returning it to the user. - -From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): - -> `new Buffer(size)` -> -> - `size` Number -> -> The underlying memory for `Buffer` instances created in this way is not initialized. -> **The contents of a newly created `Buffer` are unknown and could contain sensitive -> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. - -(Emphasis our own.) - -Whenever the programmer intended to create an uninitialized `Buffer` you often see code -like this: - -```js -var buf = new Buffer(16) - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### Would this ever be a problem in real code? - -Yes. It's surprisingly common to forget to check the type of your variables in a -dynamically-typed language like JavaScript. - -Usually the consequences of assuming the wrong type is that your program crashes with an -uncaught exception. But the failure mode for forgetting to check the type of arguments to -the `Buffer` constructor is more catastrophic. - -Here's an example of a vulnerable service that takes a JSON payload and converts it to -hex: - -```js -// Take a JSON payload {str: "some string"} and convert it to hex -var server = http.createServer(function (req, res) { - var data = '' - req.setEncoding('utf8') - req.on('data', function (chunk) { - data += chunk - }) - req.on('end', function () { - var body = JSON.parse(data) - res.end(new Buffer(body.str).toString('hex')) - }) -}) - -server.listen(8080) -``` - -In this example, an http client just has to send: - -```json -{ - "str": 1000 -} -``` - -and it will get back 1,000 bytes of uninitialized memory from the server. - -This is a very serious bug. It's similar in severity to the -[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process -memory by remote attackers. - - -### Which real-world packages were vulnerable? - -#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) - -[Mathias Buus](https://github.com/mafintosh) and I -([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, -[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow -anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get -them to reveal 20 bytes at a time of uninitialized memory from the node.js process. - -Here's -[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) -that fixed it. We released a new fixed version, created a -[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all -vulnerable versions on npm so users will get a warning to upgrade to a newer version. - -#### [`ws`](https://www.npmjs.com/package/ws) - -That got us wondering if there were other vulnerable packages. Sure enough, within a short -period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the -most popular WebSocket implementation in node.js. - -If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as -expected, then uninitialized server memory would be disclosed to the remote peer. - -These were the vulnerable methods: - -```js -socket.send(number) -socket.ping(number) -socket.pong(number) -``` - -Here's a vulnerable socket server with some echo functionality: - -```js -server.on('connection', function (socket) { - socket.on('message', function (message) { - message = JSON.parse(message) - if (message.type === 'echo') { - socket.send(message.data) // send back the user's message - } - }) -}) -``` - -`socket.send(number)` called on the server, will disclose server memory. - -Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue -was fixed, with a more detailed explanation. Props to -[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the -[Node Security Project disclosure](https://nodesecurity.io/advisories/67). - - -### What's the solution? - -It's important that node.js offers a fast way to get memory otherwise performance-critical -applications would needlessly get a lot slower. - -But we need a better way to *signal our intent* as programmers. **When we want -uninitialized memory, we should request it explicitly.** - -Sensitive functionality should not be packed into a developer-friendly API that loosely -accepts many different types. This type of API encourages the lazy practice of passing -variables in without checking the type very carefully. - -#### A new API: `Buffer.allocUnsafe(number)` - -The functionality of creating buffers with uninitialized memory should be part of another -API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that -frequently gets user input of all sorts of different types passed into it. - -```js -var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### How do we fix node.js core? - -We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as -`semver-major`) which defends against one case: - -```js -var str = 16 -new Buffer(str, 'utf8') -``` - -In this situation, it's implied that the programmer intended the first argument to be a -string, since they passed an encoding as a second argument. Today, node.js will allocate -uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not -what the programmer intended. - -But this is only a partial solution, since if the programmer does `new Buffer(variable)` -(without an `encoding` parameter) there's no way to know what they intended. If `variable` -is sometimes a number, then uninitialized memory will sometimes be returned. - -### What's the real long-term fix? - -We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when -we need uninitialized memory. But that would break 1000s of packages. - -~~We believe the best solution is to:~~ - -~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ - -~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ - -#### Update - -We now support adding three new APIs: - -- `Buffer.from(value)` - convert from any type to a buffer -- `Buffer.alloc(size)` - create a zero-filled buffer -- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size - -This solves the core problem that affected `ws` and `bittorrent-dht` which is -`Buffer(variable)` getting tricked into taking a number argument. - -This way, existing code continues working and the impact on the npm ecosystem will be -minimal. Over time, npm maintainers can migrate performance-critical code to use -`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. - - -### Conclusion - -We think there's a serious design issue with the `Buffer` API as it exists today. It -promotes insecure software by putting high-risk functionality into a convenient API -with friendly "developer ergonomics". - -This wasn't merely a theoretical exercise because we found the issue in some of the -most popular npm packages. - -Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of -`buffer`. - -```js -var Buffer = require('safe-buffer').Buffer -``` - -Eventually, we hope that node.js core can switch to this new, safer behavior. We believe -the impact on the ecosystem would be minimal since it's not a breaking change. -Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while -older, insecure packages would magically become safe from this attack vector. - - -## links - -- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) -- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) -- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) - - -## credit - -The original issues in `bittorrent-dht` -([disclosure](https://nodesecurity.io/advisories/68)) and -`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by -[Mathias Buus](https://github.com/mafintosh) and -[Feross Aboukhadijeh](http://feross.org/). - -Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues -and for his work running the [Node Security Project](https://nodesecurity.io/). - -Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and -auditing the code. - - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts b/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -declare module "safe-buffer" { - export class Buffer { - length: number - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor (str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor (size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor (arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor (buffer: Buffer); - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; - } -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/index.js b/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/index.js deleted file mode 100644 index 22438da..0000000 --- a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -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 { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -// Copy static methods from Buffer -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) -} diff --git a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/package.json b/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/package.json deleted file mode 100644 index 623fbc3..0000000 --- a/reverse_engineering/node_modules/readable-stream/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "safe-buffer", - "description": "Safer Node.js Buffer API", - "version": "5.1.2", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "devDependencies": { - "standard": "*", - "tape": "^4.0.0" - }, - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test/*.js" - } -} diff --git a/reverse_engineering/node_modules/readable-stream/package.json b/reverse_engineering/node_modules/readable-stream/package.json deleted file mode 100644 index 2afa6fb..0000000 --- a/reverse_engineering/node_modules/readable-stream/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "readable-stream", - "version": "2.3.7", - "description": "Streams3, a user-land copy of the stream library from Node.js", - "main": "readable.js", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - }, - "devDependencies": { - "assert": "^1.4.0", - "babel-polyfill": "^6.9.1", - "buffer": "^4.9.0", - "lolex": "^2.3.2", - "nyc": "^6.4.0", - "tap": "^0.7.0", - "tape": "^4.8.0" - }, - "scripts": { - "test": "tap test/parallel/*.js test/ours/*.js && node test/verify-dependencies.js", - "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", - "cover": "nyc npm test", - "report": "nyc report --reporter=lcov" - }, - "repository": { - "type": "git", - "url": "git://github.com/nodejs/readable-stream" - }, - "keywords": [ - "readable", - "stream", - "pipe" - ], - "browser": { - "util": false, - "./readable.js": "./readable-browser.js", - "./writable.js": "./writable-browser.js", - "./duplex.js": "./duplex-browser.js", - "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" - }, - "nyc": { - "include": [ - "lib/**.js" - ] - }, - "license": "MIT" -} diff --git a/reverse_engineering/node_modules/readable-stream/passthrough.js b/reverse_engineering/node_modules/readable-stream/passthrough.js deleted file mode 100644 index ffd791d..0000000 --- a/reverse_engineering/node_modules/readable-stream/passthrough.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./readable').PassThrough diff --git a/reverse_engineering/node_modules/readable-stream/readable-browser.js b/reverse_engineering/node_modules/readable-stream/readable-browser.js deleted file mode 100644 index e503725..0000000 --- a/reverse_engineering/node_modules/readable-stream/readable-browser.js +++ /dev/null @@ -1,7 +0,0 @@ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/reverse_engineering/node_modules/readable-stream/readable.js b/reverse_engineering/node_modules/readable-stream/readable.js deleted file mode 100644 index ec89ec5..0000000 --- a/reverse_engineering/node_modules/readable-stream/readable.js +++ /dev/null @@ -1,19 +0,0 @@ -var Stream = require('stream'); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = require('./lib/_stream_readable.js'); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = require('./lib/_stream_writable.js'); - exports.Duplex = require('./lib/_stream_duplex.js'); - exports.Transform = require('./lib/_stream_transform.js'); - exports.PassThrough = require('./lib/_stream_passthrough.js'); -} diff --git a/reverse_engineering/node_modules/readable-stream/transform.js b/reverse_engineering/node_modules/readable-stream/transform.js deleted file mode 100644 index b1baba2..0000000 --- a/reverse_engineering/node_modules/readable-stream/transform.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./readable').Transform diff --git a/reverse_engineering/node_modules/readable-stream/writable-browser.js b/reverse_engineering/node_modules/readable-stream/writable-browser.js deleted file mode 100644 index ebdde6a..0000000 --- a/reverse_engineering/node_modules/readable-stream/writable-browser.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/_stream_writable.js'); diff --git a/reverse_engineering/node_modules/readable-stream/writable.js b/reverse_engineering/node_modules/readable-stream/writable.js deleted file mode 100644 index 3211a6f..0000000 --- a/reverse_engineering/node_modules/readable-stream/writable.js +++ /dev/null @@ -1,8 +0,0 @@ -var Stream = require("stream") -var Writable = require("./lib/_stream_writable.js") - -if (process.env.READABLE_STREAM === 'disable') { - module.exports = Stream && Stream.Writable || Writable -} else { - module.exports = Writable -} diff --git a/reverse_engineering/node_modules/require-at/README.md b/reverse_engineering/node_modules/require-at/README.md deleted file mode 100644 index 732d669..0000000 --- a/reverse_engineering/node_modules/require-at/README.md +++ /dev/null @@ -1,85 +0,0 @@ -[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] -[![Dependency Status][daviddm-image]][daviddm-url] [![devDependency Status][daviddm-dev-image]][daviddm-dev-url] - -# require-at - -Allow you to call `require` or `require.resolve` pretending that you are at another directory. - -## Purpose - -Given the directory structure below with two NodeJS apps: - - app1 - |-+ foo - | +-- index.js - | +--+ node_modules - | +--+ x - | + ... - app2 - |-+ bar - | +-- index.js - | +--+ node_modules - | +--+ y - | + ... - -When you call `require("x")` in `/app1/foo/index.js`, NodeJS will search and find module `x` there. - -Now from the same file, if you want to resolve the module `y` under the directory `/app2/bar`, you have to use an absolute or relative path directly pointing to `y`, and you may have to do some searching, probably re-implementing Node's module searching algorithm if you don't know exactly where `y` could be. - -However, in the file `/app2/bar/index.js`, it can just do `require("y")` and Node would automatically find the module for it, because that file is at the location where `y` is under. - -What if from the file `/app1/foo/index.js`, you can call `require` as if you were at the directory `/app2/bar`, then you would be able to utilize Node's module searching automatically. - -To achieve this, most other implementations choose to re-implement Node's module searching algorithm. - -This module's approach is to tap into Node's `module` and let it do the work. - -## Install - - $ npm install require-at --save - -## Usage - -A single function is exported. - -##### `requireAt(dir, [request])` - -- If you call it with just `dir`, then it returns a `require` function that's been binded to the directory `dir`. You can use it to load any module as if you are at `dir`. - - You can also call `require.resolve` with the same effect. -- If you call it with `dir` and a `request`, then it will load and return the module `request` as if at `dir`. - -##### Example - -```js -const requireAt = require("require-at"); - -// get back a require binded to /another/dir - -const requireAtAnother = requireAt("/another/dir/"); -const modXPath = requireAtAnother.resolve("modX"); -const modX = requireAtAnother("modX"); - -// load modY at /another/yet/dir directly - -const modY = requireAt("/another/yet/dir", "modY"); -``` - -## License - -Apache-2.0 © [Joel Chen](https://github.com/jchip) - -[travis-image]: https://travis-ci.org/jchip/require-at.svg?branch=master - -[travis-url]: https://travis-ci.org/jchip/require-at - -[npm-image]: https://badge.fury.io/js/require-at.svg - -[npm-url]: https://npmjs.org/package/require-at - -[daviddm-image]: https://david-dm.org/jchip/require-at/status.svg - -[daviddm-url]: https://david-dm.org/jchip/require-at - -[daviddm-dev-image]: https://david-dm.org/jchip/require-at/dev-status.svg - -[daviddm-dev-url]: https://david-dm.org/jchip/require-at?type=dev diff --git a/reverse_engineering/node_modules/require-at/create-require.js b/reverse_engineering/node_modules/require-at/create-require.js deleted file mode 100644 index f25f36a..0000000 --- a/reverse_engineering/node_modules/require-at/create-require.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; - -const Module = require("module"); -// use eval to avoid tripping bundlers -const xrequire = eval("require"); - -const createRequireFromPath = - Module.createRequire || - Module.createRequireFromPath || - ((filename, dir) => { - // https://github.com/nodejs/node/blob/1ae0511b942c01c6e0adff98643d350a395bf101/lib/internal/modules/cjs/loader.js#L748 - // https://github.com/nodejs/node/blob/1ae0511b942c01c6e0adff98643d350a395bf101/lib/internal/modules/cjs/helpers.js#L16 - const m = new Module(filename); - - m.filename = filename; - m.paths = Module._nodeModulePaths(dir); - - // don't name this require to avoid tripping bundlers - function _require(request) { - // can't use m.require because there's an internal requireDepth thing - // in the native Module implementation - return xrequire(resolve(request)); - } - - function resolve(request, options) { - return Module._resolveFilename(request, m, false, options); - } - - _require.resolve = resolve; - - function paths(request) { - return Module._resolveLookupPaths(request, m, true); - } - - resolve.paths = paths; - _require.main = process.mainModule; - _require.extensions = Module._extensions; - _require.cache = Module._cache; - - return _require; - }); - -module.exports = createRequireFromPath; diff --git a/reverse_engineering/node_modules/require-at/package.json b/reverse_engineering/node_modules/require-at/package.json deleted file mode 100644 index f91b02c..0000000 --- a/reverse_engineering/node_modules/require-at/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "require-at", - "version": "1.0.6", - "main": "require-at.js", - "description": "Call require pretending your are at another directory", - "scripts": { - "test": "mocha test/spec", - "coverage": "istanbul cover -- _mocha test/spec && istanbul check-coverage" - }, - "keywords": [], - "author": "Joel Chen", - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/jchip/require-at" - }, - "files": [ - "create-require.js", - "require-at.js" - ], - "dependencies": {}, - "devDependencies": { - "chai": "^3.5.0", - "istanbul": "^0.4.5", - "mocha": "^3.2.0" - }, - "engines": { - "node": ">=4" - } -} diff --git a/reverse_engineering/node_modules/require-at/require-at.js b/reverse_engineering/node_modules/require-at/require-at.js deleted file mode 100644 index 66335eb..0000000 --- a/reverse_engineering/node_modules/require-at/require-at.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; - -const Path = require("path"); -const Fs = require("fs"); - -const createRequireFromPath = require("./create-require"); - -const cache = new Map(); - -function requireAt(dir, request) { - const makeIt = (xdir, checked) => { - let xRequire = requireAt.cache && requireAt.cache.get(xdir); - - if (!xRequire) { - let stat; - try { - stat = Fs.statSync(xdir); - } catch (e) { - throw new Error(`require-at: stat '${xdir}' failed: ${e.message}`); - } - - if (!stat || !stat.isDirectory()) { - if (checked) throw new Error(`require-at: not a directory: '${dir}'`); - return makeIt(Path.dirname(xdir), true); - } - - xRequire = createRequireFromPath(Path.join(xdir, "._require-at_"), xdir); - - requireAt.cache && requireAt.cache.set(xdir, xRequire); - } - - return request ? xRequire(request) : xRequire; - }; - - return makeIt(Path.resolve(dir), false); -} - -requireAt.cache = cache; - -module.exports = requireAt; diff --git a/reverse_engineering/node_modules/require-directory/.jshintrc b/reverse_engineering/node_modules/require-directory/.jshintrc deleted file mode 100644 index e14e4dc..0000000 --- a/reverse_engineering/node_modules/require-directory/.jshintrc +++ /dev/null @@ -1,67 +0,0 @@ -{ - "maxerr" : 50, - "bitwise" : true, - "camelcase" : true, - "curly" : true, - "eqeqeq" : true, - "forin" : true, - "immed" : true, - "indent" : 2, - "latedef" : true, - "newcap" : true, - "noarg" : true, - "noempty" : true, - "nonew" : true, - "plusplus" : true, - "quotmark" : true, - "undef" : true, - "unused" : true, - "strict" : true, - "trailing" : true, - "maxparams" : false, - "maxdepth" : false, - "maxstatements" : false, - "maxcomplexity" : false, - "maxlen" : false, - "asi" : false, - "boss" : false, - "debug" : false, - "eqnull" : true, - "es5" : false, - "esnext" : false, - "moz" : false, - "evil" : false, - "expr" : true, - "funcscope" : true, - "globalstrict" : true, - "iterator" : true, - "lastsemic" : false, - "laxbreak" : false, - "laxcomma" : false, - "loopfunc" : false, - "multistr" : false, - "proto" : false, - "scripturl" : false, - "smarttabs" : false, - "shadow" : false, - "sub" : false, - "supernew" : false, - "validthis" : false, - "browser" : true, - "couch" : false, - "devel" : true, - "dojo" : false, - "jquery" : false, - "mootools" : false, - "node" : true, - "nonstandard" : false, - "prototypejs" : false, - "rhino" : false, - "worker" : false, - "wsh" : false, - "yui" : false, - "nomen" : true, - "onevar" : true, - "passfail" : false, - "white" : true -} diff --git a/reverse_engineering/node_modules/require-directory/.npmignore b/reverse_engineering/node_modules/require-directory/.npmignore deleted file mode 100644 index 47cf365..0000000 --- a/reverse_engineering/node_modules/require-directory/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test/** diff --git a/reverse_engineering/node_modules/require-directory/.travis.yml b/reverse_engineering/node_modules/require-directory/.travis.yml deleted file mode 100644 index 20fd86b..0000000 --- a/reverse_engineering/node_modules/require-directory/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - 0.10 diff --git a/reverse_engineering/node_modules/require-directory/LICENSE b/reverse_engineering/node_modules/require-directory/LICENSE deleted file mode 100644 index a70f253..0000000 --- a/reverse_engineering/node_modules/require-directory/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2011 Troy Goode - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/require-directory/README.markdown b/reverse_engineering/node_modules/require-directory/README.markdown deleted file mode 100644 index 926a063..0000000 --- a/reverse_engineering/node_modules/require-directory/README.markdown +++ /dev/null @@ -1,184 +0,0 @@ -# require-directory - -Recursively iterates over specified directory, `require()`'ing each file, and returning a nested hash structure containing those modules. - -**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)** - -[![NPM](https://nodei.co/npm/require-directory.png?downloads=true&stars=true)](https://nodei.co/npm/require-directory/) - -[![build status](https://secure.travis-ci.org/troygoode/node-require-directory.png)](http://travis-ci.org/troygoode/node-require-directory) - -## How To Use - -### Installation (via [npm](https://npmjs.org/package/require-directory)) - -```bash -$ npm install require-directory -``` - -### Usage - -A common pattern in node.js is to include an index file which creates a hash of the files in its current directory. Given a directory structure like so: - -* app.js -* routes/ - * index.js - * home.js - * auth/ - * login.js - * logout.js - * register.js - -`routes/index.js` uses `require-directory` to build the hash (rather than doing so manually) like so: - -```javascript -var requireDirectory = require('require-directory'); -module.exports = requireDirectory(module); -``` - -`app.js` references `routes/index.js` like any other module, but it now has a hash/tree of the exports from the `./routes/` directory: - -```javascript -var routes = require('./routes'); - -// snip - -app.get('/', routes.home); -app.get('/register', routes.auth.register); -app.get('/login', routes.auth.login); -app.get('/logout', routes.auth.logout); -``` - -The `routes` variable above is the equivalent of this: - -```javascript -var routes = { - home: require('routes/home.js'), - auth: { - login: require('routes/auth/login.js'), - logout: require('routes/auth/logout.js'), - register: require('routes/auth/register.js') - } -}; -``` - -*Note that `routes.index` will be `undefined` as you would hope.* - -### Specifying Another Directory - -You can specify which directory you want to build a tree of (if it isn't the current directory for whatever reason) by passing it as the second parameter. Not specifying the path (`requireDirectory(module)`) is the equivelant of `requireDirectory(module, __dirname)`: - -```javascript -var requireDirectory = require('require-directory'); -module.exports = requireDirectory(module, './some/subdirectory'); -``` - -For example, in the [example in the Usage section](#usage) we could have avoided creating `routes/index.js` and instead changed the first lines of `app.js` to: - -```javascript -var requireDirectory = require('require-directory'); -var routes = requireDirectory(module, './routes'); -``` - -## Options - -You can pass an options hash to `require-directory` as the 2nd parameter (or 3rd if you're passing the path to another directory as the 2nd parameter already). Here are the available options: - -### Whitelisting - -Whitelisting (either via RegExp or function) allows you to specify that only certain files be loaded. - -```javascript -var requireDirectory = require('require-directory'), - whitelist = /onlyinclude.js$/, - hash = requireDirectory(module, {include: whitelist}); -``` - -```javascript -var requireDirectory = require('require-directory'), - check = function(path){ - if(/onlyinclude.js$/.test(path)){ - return true; // don't include - }else{ - return false; // go ahead and include - } - }, - hash = requireDirectory(module, {include: check}); -``` - -### Blacklisting - -Blacklisting (either via RegExp or function) allows you to specify that all but certain files should be loaded. - -```javascript -var requireDirectory = require('require-directory'), - blacklist = /dontinclude\.js$/, - hash = requireDirectory(module, {exclude: blacklist}); -``` - -```javascript -var requireDirectory = require('require-directory'), - check = function(path){ - if(/dontinclude\.js$/.test(path)){ - return false; // don't include - }else{ - return true; // go ahead and include - } - }, - hash = requireDirectory(module, {exclude: check}); -``` - -### Visiting Objects As They're Loaded - -`require-directory` takes a function as the `visit` option that will be called for each module that is added to module.exports. - -```javascript -var requireDirectory = require('require-directory'), - visitor = function(obj) { - console.log(obj); // will be called for every module that is loaded - }, - hash = requireDirectory(module, {visit: visitor}); -``` - -The visitor can also transform the objects by returning a value: - -```javascript -var requireDirectory = require('require-directory'), - visitor = function(obj) { - return obj(new Date()); - }, - hash = requireDirectory(module, {visit: visitor}); -``` - -### Renaming Keys - -```javascript -var requireDirectory = require('require-directory'), - renamer = function(name) { - return name.toUpperCase(); - }, - hash = requireDirectory(module, {rename: renamer}); -``` - -### No Recursion - -```javascript -var requireDirectory = require('require-directory'), - hash = requireDirectory(module, {recurse: false}); -``` - -## Run Unit Tests - -```bash -$ npm run lint -$ npm test -``` - -## License - -[MIT License](http://www.opensource.org/licenses/mit-license.php) - -## Author - -[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) - diff --git a/reverse_engineering/node_modules/require-directory/index.js b/reverse_engineering/node_modules/require-directory/index.js deleted file mode 100644 index cd37da7..0000000 --- a/reverse_engineering/node_modules/require-directory/index.js +++ /dev/null @@ -1,86 +0,0 @@ -'use strict'; - -var fs = require('fs'), - join = require('path').join, - resolve = require('path').resolve, - dirname = require('path').dirname, - defaultOptions = { - extensions: ['js', 'json', 'coffee'], - recurse: true, - rename: function (name) { - return name; - }, - visit: function (obj) { - return obj; - } - }; - -function checkFileInclusion(path, filename, options) { - return ( - // verify file has valid extension - (new RegExp('\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) && - - // if options.include is a RegExp, evaluate it and make sure the path passes - !(options.include && options.include instanceof RegExp && !options.include.test(path)) && - - // if options.include is a function, evaluate it and make sure the path passes - !(options.include && typeof options.include === 'function' && !options.include(path, filename)) && - - // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass - !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) && - - // if options.exclude is a function, evaluate it and make sure the path doesn't pass - !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename)) - ); -} - -function requireDirectory(m, path, options) { - var retval = {}; - - // path is optional - if (path && !options && typeof path !== 'string') { - options = path; - path = null; - } - - // default options - options = options || {}; - for (var prop in defaultOptions) { - if (typeof options[prop] === 'undefined') { - options[prop] = defaultOptions[prop]; - } - } - - // if no path was passed in, assume the equivelant of __dirname from caller - // otherwise, resolve path relative to the equivalent of __dirname - path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path); - - // get the path of each file in specified directory, append to current tree node, recurse - fs.readdirSync(path).forEach(function (filename) { - var joined = join(path, filename), - files, - key, - obj; - - if (fs.statSync(joined).isDirectory() && options.recurse) { - // this node is a directory; recurse - files = requireDirectory(m, joined, options); - // exclude empty directories - if (Object.keys(files).length) { - retval[options.rename(filename, joined, filename)] = files; - } - } else { - if (joined !== m.filename && checkFileInclusion(joined, filename, options)) { - // hash node key shouldn't include file extension - key = filename.substring(0, filename.lastIndexOf('.')); - obj = m.require(joined); - retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj; - } - } - }); - - return retval; -} - -module.exports = requireDirectory; -module.exports.defaults = defaultOptions; diff --git a/reverse_engineering/node_modules/require-directory/package.json b/reverse_engineering/node_modules/require-directory/package.json deleted file mode 100644 index 25ece4b..0000000 --- a/reverse_engineering/node_modules/require-directory/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "author": "Troy Goode (http://github.com/troygoode/)", - "name": "require-directory", - "version": "2.1.1", - "description": "Recursively iterates over specified directory, require()'ing each file, and returning a nested hash structure containing those modules.", - "keywords": [ - "require", - "directory", - "library", - "recursive" - ], - "homepage": "https://github.com/troygoode/node-require-directory/", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/troygoode/node-require-directory.git" - }, - "contributors": [ - { - "name": "Troy Goode", - "email": "troygoode@gmail.com", - "web": "http://github.com/troygoode/" - } - ], - "license": "MIT", - "bugs": { - "url": "http://github.com/troygoode/node-require-directory/issues/" - }, - "engines": { - "node": ">=0.10.0" - }, - "devDependencies": { - "jshint": "^2.6.0", - "mocha": "^2.1.0" - }, - "scripts": { - "test": "mocha", - "lint": "jshint index.js test/test.js" - } -} diff --git a/reverse_engineering/node_modules/require-main-filename/CHANGELOG.md b/reverse_engineering/node_modules/require-main-filename/CHANGELOG.md deleted file mode 100644 index 717d59e..0000000 --- a/reverse_engineering/node_modules/require-main-filename/CHANGELOG.md +++ /dev/null @@ -1,26 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -# [2.0.0](https://github.com/yargs/require-main-filename/compare/v1.0.2...v2.0.0) (2019-01-28) - - -### Chores - -* drop support for Node 0.10 ([#11](https://github.com/yargs/require-main-filename/issues/11)) ([87f4e13](https://github.com/yargs/require-main-filename/commit/87f4e13)) - - -### BREAKING CHANGES - -* drop support for Node 0.10/0.12 - - - - -## [1.0.2](https://github.com/yargs/require-main-filename/compare/v1.0.1...v1.0.2) (2017-06-16) - - -### Bug Fixes - -* add files to package.json ([#4](https://github.com/yargs/require-main-filename/issues/4)) ([fa29988](https://github.com/yargs/require-main-filename/commit/fa29988)) diff --git a/reverse_engineering/node_modules/require-main-filename/LICENSE.txt b/reverse_engineering/node_modules/require-main-filename/LICENSE.txt deleted file mode 100644 index 836440b..0000000 --- a/reverse_engineering/node_modules/require-main-filename/LICENSE.txt +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) 2016, Contributors - -Permission to use, copy, modify, and/or distribute this software -for any purpose with or without fee is hereby granted, provided -that the above copyright notice and this permission notice -appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE -LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/require-main-filename/README.md b/reverse_engineering/node_modules/require-main-filename/README.md deleted file mode 100644 index 820d9f5..0000000 --- a/reverse_engineering/node_modules/require-main-filename/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# require-main-filename - -[![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) -[![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) -[![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) - -`require.main.filename` is great for figuring out the entry -point for the current application. This can be combined with a module like -[pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load -top-level configuration. - -Unfortunately, `require.main.filename` sometimes fails when an application is -executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). - -`require-main-filename` is a shim that addresses this problem. - -## Usage - -```js -var main = require('require-main-filename')() -// use main as an alternative to require.main.filename. -``` - -## License - -ISC diff --git a/reverse_engineering/node_modules/require-main-filename/index.js b/reverse_engineering/node_modules/require-main-filename/index.js deleted file mode 100644 index dca7f0c..0000000 --- a/reverse_engineering/node_modules/require-main-filename/index.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = function (_require) { - _require = _require || require - var main = _require.main - if (main && isIISNode(main)) return handleIISNode(main) - else return main ? main.filename : process.cwd() -} - -function isIISNode (main) { - return /\\iisnode\\/.test(main.filename) -} - -function handleIISNode (main) { - if (!main.children.length) { - return main.filename - } else { - return main.children[0].filename - } -} diff --git a/reverse_engineering/node_modules/require-main-filename/package.json b/reverse_engineering/node_modules/require-main-filename/package.json deleted file mode 100644 index a549822..0000000 --- a/reverse_engineering/node_modules/require-main-filename/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "require-main-filename", - "version": "2.0.0", - "description": "shim for require.main.filename() that works in as many environments as possible", - "main": "index.js", - "scripts": { - "pretest": "standard", - "test": "tap --coverage test.js", - "release": "standard-version" - }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/yargs/require-main-filename.git" - }, - "keywords": [ - "require", - "shim", - "iisnode" - ], - "files": [ - "index.js" - ], - "author": "Ben Coe ", - "license": "ISC", - "bugs": { - "url": "https://github.com/yargs/require-main-filename/issues" - }, - "homepage": "https://github.com/yargs/require-main-filename#readme", - "devDependencies": { - "chai": "^4.0.0", - "standard": "^10.0.3", - "standard-version": "^4.0.0", - "tap": "^11.0.0" - } -} diff --git a/reverse_engineering/node_modules/reservoir/.npmignore b/reverse_engineering/node_modules/reservoir/.npmignore deleted file mode 100644 index 962e3b5..0000000 --- a/reverse_engineering/node_modules/reservoir/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -examples/pos diff --git a/reverse_engineering/node_modules/reservoir/README.md b/reverse_engineering/node_modules/reservoir/README.md deleted file mode 100644 index 7fd9d68..0000000 --- a/reverse_engineering/node_modules/reservoir/README.md +++ /dev/null @@ -1,114 +0,0 @@ -# Reservoir -A simple JavaScript library for quickly generating a random subset of arrays, iterators, or streams using [reservoir sampling](http://en.wikipedia.org/wiki/Reservoir_sampling). - -## Installation - -### Node.js - -For *Node.js*, use `npm`: - -````console -npm install reservoir -```` - -..then `require` Reservoir: - -````javascript -var Reservoir = require('reservoir'); -```` - -### In the browser, traditional - -For the *browser*, add the following to your pages: - -````html - -```` - -### In the browser, using AMD (require.js) - -...Or using AMD in the browser: - -````javascript -require(["reservoir"], function(Reservoir) { - // ... -}); -```` - -## Usage - -A reservoir is just an array with one very special function added - `pushSome`. - -### Basic - -To create an empty reservoir that will contain a *maximum* of 3 randomly-chosen items: - -````javascript -var myReservoir = Reservoir(3); -```` - -Now, using that new reservoir we begin to add items into it: - -````javascript -var myData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - -myData.forEach(function(e) { - myReservoir.pushSome(e); -}); -```` - -At this point, `myReservoir` will contain example 3 randomly-chosen values from the array `myData`: - -````javascript -myReservoir => [2, 4, 7] // This can be any random subset of myData -```` - -As we can see, one important property of the Reservoir is that the order of the input is preserved. - -### Intermediate - -Since, `Reservoir.pushSome` operates much like the real `Array.push` we can pass `pushSome` more than one parameter and each one will be pushed in order. That means we can make the previous example more succinct by using `Function.apply`: - -````javascript -myReservoir.pushSome.apply(myReservoir, myData); -```` - -Since the object returned from Reservoir() is just an array *decorated* with a `pushSome` function, all normal array functions are available. Particularly of value are the iterator functions: `forEach`, `filter`, `map`, `every`, `some`, `reduce`, and `reduceRight`. - -### Advanced - -TODO: Advanced usage (ie. see `Some`). - -## API - -### `Reservoir( reservoirSize = 1 [, randomNumberGenerator = Math.random] )` - -#### Parameters - -`reservoirSize` is the maximum size of the reservoir. This is the number of elements to be randomly chosen from the input provided to it using `pushSome`. - -`randomNumberGenerator` is an optional random number generating function to use in place of the default `Math.random`. - -#### Returns - -An empty Reservoir (an Array with the function `pushSome` added to it). - -### `reservoir.pushSome( datum[, datum...])` - -#### Parameters - -`datum` one or more elements to consider for inclusion into the reservoir. - -#### Returns - -The current length of the reservoir. - -## License - -> Copyright (C) 2012 Jon-Carlos Rivera -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/reservoir/examples/lib/readlines.js b/reverse_engineering/node_modules/reservoir/examples/lib/readlines.js deleted file mode 100644 index b56a14a..0000000 --- a/reverse_engineering/node_modules/reservoir/examples/lib/readlines.js +++ /dev/null @@ -1,51 +0,0 @@ -// Modified from: -// http://stackoverflow.com/a/6833016 - -function getnextLineOffset(string, startAt) { - var startAt = startAt || 0; - var index = string.indexOf('\r', startAt); - var newlineSize; - - if(index >= 0) { - if(string.charAt(index + 1) === "\n") - newlineSize = 2; - else - newlineSize = 1; - } else { - index = string.indexOf('\n', startAt); - newlineSize = 1; - } - - return { - last : startAt, - index : index, - next : index + newlineSize, - }; -} - -function readLines(input, func, done) { - var remaining = ''; - var lineNumber = 0; - - input.on('data', function(data) { - remaining += data; - var lineInfo = getnextLineOffset(remaining); - - while (lineInfo.index > -1) { - var line = remaining.substring(lineInfo.last, lineInfo.index); - func(line, ++lineNumber); - lineInfo = getnextLineOffset(remaining, lineInfo.next); - } - - remaining = remaining.substring(lineInfo.last); - }); - - input.on('end', function() { - if (remaining.length > 0) { - func(remaining); - } - done(); - }); -} - -module.exports = readLines; \ No newline at end of file diff --git a/reverse_engineering/node_modules/reservoir/examples/partsofspeech.README b/reverse_engineering/node_modules/reservoir/examples/partsofspeech.README deleted file mode 100644 index 741e076..0000000 --- a/reverse_engineering/node_modules/reservoir/examples/partsofspeech.README +++ /dev/null @@ -1,10 +0,0 @@ -To keep the size of this library small, the data file that the -script partsofspeech.js requires isn't included. - -You can get the "Part Of Speech Database" from: - -http://wordlist.sourceforge.net/ - -Unpack the data into this directory so that the 'pos' directory -is a direct subdirectory of this one. The script tries to open the -file `./pos/part-of-speech.txt`. \ No newline at end of file diff --git a/reverse_engineering/node_modules/reservoir/examples/partsofspeech.js b/reverse_engineering/node_modules/reservoir/examples/partsofspeech.js deleted file mode 100644 index 21934c5..0000000 --- a/reverse_engineering/node_modules/reservoir/examples/partsofspeech.js +++ /dev/null @@ -1,105 +0,0 @@ -var Reservoir = require("../"), - fs = require('fs'), - readLines = require('./lib/readlines.js'); - -var numberOfWords = 30, - maxWordLength = 37, - maxPOSLength = 35, - maxNumberLength = 8; - -var lineReservoir = Reservoir(numberOfWords); - -var partsOfSpeech = { - "N" : "Noun", - "p" : "Plural", - "h" : "Noun Phrase", - "V" : "Verb (usu participle)", - "t" : "Verb (transitive)", - "i" : "Verb (intransitive)", - "A" : "Adjective", - "v" : "Adverb", - "C" : "Conjunction", - "P" : "Preposition", - "!" : "Interjection", - "r" : "Pronoun", - "D" : "Definite Article", - "I" : "Indefinite Article", - "o" : "Nominative" -}; - -function makeWordObject(lineData) { - var a = lineData[0].split("\t"); // split into [word, part_of_speech]; - var b = a[1].split("|"); // split part of speech into old and new - var c = b[b.length-1].split(''); // split into letters - var word = { - 'lineNumber' : lineData[1], - 'word': a[0] - }; - - word['parts of speech'] = c.map(function(e){ return partsOfSpeech[e]; }); - - return word; -} - -function formatAndOutput(e, i) { - var lineNumber = e.lineNumber; - var partsOfSpeech = e["parts of speech"].join(', '); - - lineNumber < 10 - ? lineNumber = " " + lineNumber - : lineNumber = " " + lineNumber; - - if(e.word.length > maxWordLength - 1) - e.word = e.word.substr(0, maxWordLength - 4) + "..."; - - if(partsOfSpeech.length > maxPOSLength - 1) - partsOfSpeech = partsOfSpeech.substr(0, maxPOSLength - 4) + "..."; - - var lineNumberPadding = new Array(maxNumberLength - lineNumber.length).join(" "); - var wordPadding = new Array(maxWordLength - e.word.length + 1).join(" "); - - console.log(lineNumberPadding + lineNumber + " " + e.word + wordPadding + partsOfSpeech); -} - -function consoleHeading() { - console.log("\n Line Word Part(s) of Speech"); - console.log("--------------------------------------------------------------------------------"); -} - -openFile('pos/part-of-speech.txt'); - -function openFile(filename) { - var posFile = fs.createReadStream(filename); - - posFile.on('error', function(err) { - var slash = filename.indexOf('/'); - // Try to read the file from the local directory if it wasn't found - if(slash > 0) { - process.nextTick(function() { - openFile(filename.substr(slash + 1)); - }); - } else { - console.log("\nAn error occured trying to open `parts-of-speech.txt`.\n\nSee `partsofspeech.README` for information about aquiring this file."); - } - }); - - posFile.on("open", function(fd){ - console.log("\nSelecting " + numberOfWords + " words at random from a list of 295,172 words.."); - - var startTime = Date.now(); - readLines( - posFile, - function(line, lineNumber) { - lineReservoir.pushSome([line, lineNumber]); - }, - function(){ - var timeTaken = Date.now() - startTime; - var wordObjects = lineReservoir.map(makeWordObject); - - consoleHeading(); - wordObjects.forEach(formatAndOutput); - console.log("\nFinished in " + timeTaken + "ms."); - }); - }); -} - diff --git a/reverse_engineering/node_modules/reservoir/examples/probabilities.js b/reverse_engineering/node_modules/reservoir/examples/probabilities.js deleted file mode 100644 index 4d405bb..0000000 --- a/reverse_engineering/node_modules/reservoir/examples/probabilities.js +++ /dev/null @@ -1,58 +0,0 @@ -var Reservoir = require("../"); - -var source = []; -var counts = []; - -var totalSetSize = 100; -var subSetSize = 5; -var totalRuns = 10000; - -while(totalSetSize--) { - source.push(totalSetSize); -} - -totalSetSize = 100; - -var run = totalRuns; - -while(run--) { - var res = Reservoir(subSetSize); - res.pushSome.apply(res, source); - res.forEach(function(e, i) { - counts[e] = ++counts[e] || 1; - }); -} - -// mean: new_mean = old_mean + (value - old_mean) / samples -// sumofsquares: new_sum = old_sum + (value - old_mean) * (value - new_mean) -// variance = sumofsquares / number_of_samples -// standard deviation = sqrt( variance ) -var runningStats = function(p, c, i) { - var old_mean = p.mean; - var diff = c - old_mean; - p.samples = i + 1; // + 1 since arrays are 0-based - p.mean = old_mean + diff / p.samples; - p.sumofsq = p.sumofsq + diff * (c - p.mean); - p.samples = i + 1; - return p; -}; - -var prob = counts.map(function(e){ return e / (subSetSize * totalRuns); }); -var stats = prob.reduce(runningStats, {mean: 0, sumofsq: 0, samples: 0}); -stats.variance = stats.sumofsq / stats.samples; -stats.stdDev = Math.sqrt(stats.variance); - -var PDF = counts.sort(function(a, b) { return a - b; }); -PDF = PDF.map(function(e){ return e / (subSetSize * totalRuns); }); - -var CDF = PDF.map(function(e){ return (this[0] += e); }, [0]); - -console.log("PDF:") -console.log(PDF.map(function(e){ return e.toFixed(5); }).join(", ").replace(/((\d+.\d+,\s+){10})/g, "$1\n")); - -console.log("\nCDF:"); -console.log(CDF.map(function(e){ return e.toFixed(5); }).join(", ").replace(/((\d+.\d+,\s+){10})/g, "$1\n")); - -console.log("\nMean: ", stats.mean); -console.log("Variance: ", stats.variance); -console.log("StdDev: ", stats.stdDev); diff --git a/reverse_engineering/node_modules/reservoir/package.json b/reverse_engineering/node_modules/reservoir/package.json deleted file mode 100644 index 43c6f3b..0000000 --- a/reverse_engineering/node_modules/reservoir/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "reservoir", - "version": "0.1.2", - "description": "Fast random sampling using reservoir sampling", - "main": "reservoir.js", - "directories": { - "test": "test" - }, - "repository": { - "type": "git", - "url": "git://github.com/imbcmdth/reservoir.git" - }, - "keywords": [ - "reservoir", - "sampling", - "iterator" - ], - "dependencies": {}, - "devDependencies": { - "vows": ">=0.6.3" - }, - "author": { - "name": "Jon-Carlos Rivera", - "email": "jon.carlos.rivera@gmail.com", - "url": "http://jon-carlos.com" - }, - "scripts": { - "test": "vows test/*.js" - }, - "license": "MIT", - "engine": { - "node": ">=0.6.0" - } -} diff --git a/reverse_engineering/node_modules/reservoir/reservoir.js b/reverse_engineering/node_modules/reservoir/reservoir.js deleted file mode 100644 index c0270b4..0000000 --- a/reverse_engineering/node_modules/reservoir/reservoir.js +++ /dev/null @@ -1,233 +0,0 @@ -(function (root, factory) { - "use strict"; - - if (typeof exports === 'object') { - module.exports = factory(); - } else if (typeof define === 'function' && define.amd) { - define(factory); - } else { - root.Reservoir = factory(); - } - }(this, function () { - "use strict"; - - // We use the same constant specified in [Vitt85] - var switchToAlgorithmZConstant = 22; - - // `debug` was used to test for correctness of the more complicated - // algorithms, X and Z, by comparing their results to baseline R - var debug = "none"; - - function _Reservoir(reservoirSize, randomNumberGen) { - var rng = randomNumberGen || Math.random; - - // `reservoirSize` must be a number between 1 and 2^32 - var reservoirSize = - Math.max(1, (Math.floor(reservoirSize) >> 0) || 1); - - // `totalItemCount` contains the total number of items - // processed by `pushSome` against the reservoir - var totalItemCount = 0; - - // `numToSkip` is the total number of elements to skip over - // before accepting one into the reservoir. - var numToSkip = -1; - - // `currentAlgorithm` starts with algorithmX and switches to - // algorithmZ after `switchThreshold` items is reached - var currentAlgorithm = algorithmX; - - // `switchThreshold` is the `totalItemCount` at which to switch - // over from algorithm X to Z - var switchThreshold = - switchToAlgorithmZConstant * reservoirSize; - - if(debug === "R") { - currentAlgorithm = algorithmR; - } else if(debug === "X") { - switchThreshold = Infinity; - } else if(debug === "Z") { - currentAlgorithm = algorithmZ; - } - - // `algorithmXCount` is the number of items processed by algorithmX - // ie. the `totalItemCount` minus `reservoirSize` - var algorithmXCount = 0; - - // `W` is used in algorithmZ - var W = Math.exp(-Math.log(rng()) / reservoirSize); - - // `evictNext` is used only by algorithmR - var evictNext = null; - - // `targetArray` is the array to be returned by Reservoir() - var targetArray = []; - - targetArray.pushSome = function() { - this.length = Math.min(this.length, reservoirSize); - - for(var i = 0; i < arguments.length; i++) { - addSample.call(this, arguments[i]); - } - - return this.length; - }; - - // `addSample` adds a single item at a time by using `numToSkip` - // to determine whether to include it in the reservoir - var addSample = function(sample) { - // Prefill the reservoir if it isn't full - if(totalItemCount < reservoirSize) { - this.push(sample); - } else { - if(numToSkip < 0) { - numToSkip = currentAlgorithm(); - } - if(numToSkip === 0) { - replaceRandomSample(sample, this); - } - numToSkip--; - } - totalItemCount++; - return this; - }; - - // `replaceRandomSample` selects a single value from `reservoir` - // for eviction and replaces it with `sample` - function replaceRandomSample(sample, reservoir) { - // Typically, the new sample replaces the "evicted" sample - // but below we remove the evicted sample and push the - // new value to ensure that reservoir is sorted in the - // same order as the input data (ie. iterator or array). - var randomIndex; - if(evictNext !== null) { - randomIndex = evictNext; - evictNext = null; - } else { - randomIndex = Math.floor(rng() * reservoirSize); - } - reservoir.splice(randomIndex, 1); - reservoir.push(sample); - } - - // From [Vitt85], "Algorithm R" - // Selects random elements from an unknown-length input. - // Has a time-complexity of: - // O(N) - // Number of random numbers required: - // N - n - // Where: - // n = the size of the reservoir - // N = the size of the input - function algorithmR() { - var localItemCount = totalItemCount + 1, - randomValue = Math.floor(rng() * localItemCount), - toSkip = 0; - - while (randomValue >= reservoirSize) { - toSkip++; - localItemCount++; - randomValue = Math.floor(rng() * localItemCount); - } - evictNext = randomValue; - return toSkip; - } - - // From [Vitt85], "Algorithm X" - // Selects random elements from an unknown-length input. - // Has a time-complexity of: - // O(N) - // Number of random numbers required: - // 2 * n * ln( N / n ) - // Where: - // n = the size of the reservoir - // N = the size of the input - function algorithmX() { - var localItemCount = totalItemCount, - randomValue = rng(), - toSkip = 0, - quotient; - - if (totalItemCount <= switchThreshold) { - localItemCount++; - algorithmXCount++; - quotient = algorithmXCount / localItemCount; - - while (quotient > randomValue) { - toSkip++; - localItemCount++; - algorithmXCount++; - quotient = (quotient * algorithmXCount) / localItemCount; - } - return toSkip; - } else { - currentAlgorithm = algorithmZ; - return currentAlgorithm(); - } - } - - // From [Vitt85], "Algorithm Z" - // Selects random elements from an unknown-length input. - // Has a time-complexity of: - // O(n(1 + log (N / n))) - // Number of random numbers required: - // 2 * n * ln( N / n ) - // Where: - // n = the size of the reservoir - // N = the size of the input - function algorithmZ() { - var term = totalItemCount - reservoirSize + 1, - denom, - numer, - numer_lim; - - while(true) { - var randomValue = rng(); - var x = totalItemCount * (W - 1); - var toSkip = Math.floor(x); - - var subterm = ((totalItemCount + 1) / term); - subterm *= subterm; - var termSkip = term + toSkip; - var lhs = Math.exp(Math.log(((randomValue * subterm) * termSkip)/ (totalItemCount + x)) / reservoirSize); - var rhs = (((totalItemCount + x) / termSkip) * term) / totalItemCount; - - if(lhs <= rhs) { - W = rhs / lhs; - break; - } - - var y = (((randomValue * (totalItemCount + 1)) / term) * (totalItemCount + toSkip + 1)) / (totalItemCount + x); - - if(reservoirSize < toSkip) { - denom = totalItemCount; - numer_lim = term + toSkip; - } else { - denom = totalItemCount - reservoirSize + toSkip; - numer_lim = totalItemCount + 1; - } - - for(numer = totalItemCount + toSkip; numer >= numer_lim; numer--) { - y = (y * numer) / denom; - denom--; - } - - W = Math.exp(-Math.log(rng()) / reservoirSize); - - if(Math.exp(Math.log(y) / reservoirSize) <= (totalItemCount + x) / totalItemCount) { - break; - } - } - return toSkip; - } - return targetArray; - } - - return _Reservoir; - - // REFERENCES - // [Vitt85] Vitter, Jeffery S. "Random Sampling with a Reservoir." ACM - // Transactions on Mathematical Software, Vol. 11, No. 1, March - // 1985, pp. 37-57. Retrieved from - // http://www.cs.umd.edu/~samir/498/vitter.pdf -})); \ No newline at end of file diff --git a/reverse_engineering/node_modules/reservoir/test/reservoir-test.js b/reverse_engineering/node_modules/reservoir/test/reservoir-test.js deleted file mode 100644 index 8e30969..0000000 --- a/reverse_engineering/node_modules/reservoir/test/reservoir-test.js +++ /dev/null @@ -1,59 +0,0 @@ -var vows = require('vows'), - assert = require('assert'), - Reservoir = require('../'); - -var testElements = []; -for(var i = 0; i < 100; i++) testElements[i] = Math.pow(i, 2); - -vows.describe('Reservoir').addBatch({ - 'A new Reservoir': { - topic: Reservoir(3), - - 'is an array' : function (reservoir) { - assert.isArray(reservoir); - }, - 'is empty': function (reservoir) { - assert.lengthOf(reservoir, 0); - }, - 'has pushSome': function (reservoir) { - assert.isFunction(reservoir.pushSome); - } - }, - 'A partially-filled Reservoir': { - topic: function() { - var res = Reservoir(3); - res.pushSome("test1"); - res.pushSome("test2"); - return res; - }, - 'is an array' : function (reservoir) { - assert.isArray(reservoir); - }, - 'is partially-filled': function (reservoir) { - assert.lengthOf(reservoir, 2); - }, - 'has exactly the pushSomed items in the order they were inserted': function (reservoir) { - assert.equal(reservoir[0], "test1"); - assert.equal(reservoir[1], "test2"); - } - }, - 'A fully-filled Reservoir': { - topic: function() { - var res = Reservoir(3); - res.pushSome.apply(res, testElements); - return res; - }, - 'is an array' : function (reservoir) { - assert.isArray(reservoir); - }, - 'is fully-filled': function (reservoir) { - assert.lengthOf(reservoir, 3); - }, - 'has elements in the same order as the original': function (reservoir) { - var prev = 0; - reservoir.every(function(e){ - return (e > prev && (prev = e)); - }); - } - } -}).export(module); diff --git a/reverse_engineering/node_modules/safe-buffer/LICENSE b/reverse_engineering/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/reverse_engineering/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/safe-buffer/README.md b/reverse_engineering/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/reverse_engineering/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg -[travis-url]: https://travis-ci.org/feross/safe-buffer -[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg -[npm-url]: https://npmjs.org/package/safe-buffer -[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg -[downloads-url]: https://npmjs.org/package/safe-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### Safer Node.js Buffer API - -**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, -`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** - -**Uses the built-in implementation when available.** - -## install - -``` -npm install safe-buffer -``` - -## usage - -The goal of this package is to provide a safe replacement for the node.js `Buffer`. - -It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to -the top of your node.js modules: - -```js -var Buffer = require('safe-buffer').Buffer - -// Existing buffer code will continue to work without issues: - -new Buffer('hey', 'utf8') -new Buffer([1, 2, 3], 'utf8') -new Buffer(obj) -new Buffer(16) // create an uninitialized buffer (potentially unsafe) - -// But you can use these new explicit APIs to make clear what you want: - -Buffer.from('hey', 'utf8') // convert from many types to a Buffer -Buffer.alloc(16) // create a zero-filled buffer (safe) -Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) -``` - -## api - -### Class Method: Buffer.from(array) - - -* `array` {Array} - -Allocates a new `Buffer` using an `array` of octets. - -```js -const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); - // creates a new Buffer containing ASCII bytes - // ['b','u','f','f','e','r'] -``` - -A `TypeError` will be thrown if `array` is not an `Array`. - -### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - - -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or - a `new ArrayBuffer()` -* `byteOffset` {Number} Default: `0` -* `length` {Number} Default: `arrayBuffer.length - byteOffset` - -When passed a reference to the `.buffer` property of a `TypedArray` instance, -the newly created `Buffer` will share the same allocated memory as the -TypedArray. - -```js -const arr = new Uint16Array(2); -arr[0] = 5000; -arr[1] = 4000; - -const buf = Buffer.from(arr.buffer); // shares the memory with arr; - -console.log(buf); - // Prints: - -// changing the TypedArray changes the Buffer also -arr[1] = 6000; - -console.log(buf); - // Prints: -``` - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const ab = new ArrayBuffer(10); -const buf = Buffer.from(ab, 0, 2); -console.log(buf.length); - // Prints: 2 -``` - -A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. - -### Class Method: Buffer.from(buffer) - - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = Buffer.from('buffer'); -const buf2 = Buffer.from(buf1); - -buf1[0] = 0x61; -console.log(buf1.toString()); - // 'auffer' -console.log(buf2.toString()); - // 'buffer' (copy is not changed) -``` - -A `TypeError` will be thrown if `buffer` is not a `Buffer`. - -### Class Method: Buffer.from(str[, encoding]) - - -* `str` {String} String to encode. -* `encoding` {String} Encoding to use, Default: `'utf8'` - -Creates a new `Buffer` containing the given JavaScript string `str`. If -provided, the `encoding` parameter identifies the character encoding. -If not provided, `encoding` defaults to `'utf8'`. - -```js -const buf1 = Buffer.from('this is a tést'); -console.log(buf1.toString()); - // prints: this is a tést -console.log(buf1.toString('ascii')); - // prints: this is a tC)st - -const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); -console.log(buf2.toString()); - // prints: this is a tést -``` - -A `TypeError` will be thrown if `str` is not a string. - -### Class Method: Buffer.alloc(size[, fill[, encoding]]) - - -* `size` {Number} -* `fill` {Value} Default: `undefined` -* `encoding` {String} Default: `utf8` - -Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the -`Buffer` will be *zero-filled*. - -```js -const buf = Buffer.alloc(5); -console.log(buf); - // -``` - -The `size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -If `fill` is specified, the allocated `Buffer` will be initialized by calling -`buf.fill(fill)`. See [`buf.fill()`][] for more information. - -```js -const buf = Buffer.alloc(5, 'a'); -console.log(buf); - // -``` - -If both `fill` and `encoding` are specified, the allocated `Buffer` will be -initialized by calling `buf.fill(fill, encoding)`. For example: - -```js -const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -console.log(buf); - // -``` - -Calling `Buffer.alloc(size)` can be significantly slower than the alternative -`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance -contents will *never contain sensitive data*. - -A `TypeError` will be thrown if `size` is not a number. - -### Class Method: Buffer.allocUnsafe(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must -be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit -architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is -thrown. A zero-length Buffer will be created if a `size` less than or equal to -0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -```js -const buf = Buffer.allocUnsafe(5); -console.log(buf); - // - // (octets will be different, every time) -buf.fill(0); -console.log(buf); - // -``` - -A `TypeError` will be thrown if `size` is not a number. - -Note that the `Buffer` module pre-allocates an internal `Buffer` instance of -size `Buffer.poolSize` that is used as a pool for the fast allocation of new -`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated -`new Buffer(size)` constructor) only when `size` is less than or equal to -`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default -value of `Buffer.poolSize` is `8192` but can be modified. - -Use of this pre-allocated internal memory pool is a key difference between -calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. -Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer -pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal -Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The -difference is subtle but can be important when an application requires the -additional performance that `Buffer.allocUnsafe(size)` provides. - -### Class Method: Buffer.allocUnsafeSlow(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The -`size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, -allocations under 4KB are, by default, sliced from a single pre-allocated -`Buffer`. This allows applications to avoid the garbage collection overhead of -creating many individually allocated Buffers. This approach improves both -performance and memory usage by eliminating the need to track and cleanup as -many `Persistent` objects. - -However, in the case where a developer may need to retain a small chunk of -memory from a pool for an indeterminate amount of time, it may be appropriate -to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then -copy out the relevant bits. - -```js -// need to keep around a few small chunks of memory -const store = []; - -socket.on('readable', () => { - const data = socket.read(); - // allocate for retained data - const sb = Buffer.allocUnsafeSlow(10); - // copy the data into the new allocation - data.copy(sb, 0, 0, 10); - store.push(sb); -}); -``` - -Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* -a developer has observed undue memory retention in their applications. - -A `TypeError` will be thrown if `size` is not a number. - -### All the Rest - -The rest of the `Buffer` API is exactly the same as in node.js. -[See the docs](https://nodejs.org/api/buffer.html). - - -## Related links - -- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) -- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) - -## Why is `Buffer` unsafe? - -Today, the node.js `Buffer` constructor is overloaded to handle many different argument -types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), -`ArrayBuffer`, and also `Number`. - -The API is optimized for convenience: you can throw any type at it, and it will try to do -what you want. - -Because the Buffer constructor is so powerful, you often see code like this: - -```js -// Convert UTF-8 strings to hex -function toHex (str) { - return new Buffer(str).toString('hex') -} -``` - -***But what happens if `toHex` is called with a `Number` argument?*** - -### Remote Memory Disclosure - -If an attacker can make your program call the `Buffer` constructor with a `Number` -argument, then they can make it allocate uninitialized memory from the node.js process. -This could potentially disclose TLS private keys, user data, or database passwords. - -When the `Buffer` constructor is passed a `Number` argument, it returns an -**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like -this, you **MUST** overwrite the contents before returning it to the user. - -From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): - -> `new Buffer(size)` -> -> - `size` Number -> -> The underlying memory for `Buffer` instances created in this way is not initialized. -> **The contents of a newly created `Buffer` are unknown and could contain sensitive -> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. - -(Emphasis our own.) - -Whenever the programmer intended to create an uninitialized `Buffer` you often see code -like this: - -```js -var buf = new Buffer(16) - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### Would this ever be a problem in real code? - -Yes. It's surprisingly common to forget to check the type of your variables in a -dynamically-typed language like JavaScript. - -Usually the consequences of assuming the wrong type is that your program crashes with an -uncaught exception. But the failure mode for forgetting to check the type of arguments to -the `Buffer` constructor is more catastrophic. - -Here's an example of a vulnerable service that takes a JSON payload and converts it to -hex: - -```js -// Take a JSON payload {str: "some string"} and convert it to hex -var server = http.createServer(function (req, res) { - var data = '' - req.setEncoding('utf8') - req.on('data', function (chunk) { - data += chunk - }) - req.on('end', function () { - var body = JSON.parse(data) - res.end(new Buffer(body.str).toString('hex')) - }) -}) - -server.listen(8080) -``` - -In this example, an http client just has to send: - -```json -{ - "str": 1000 -} -``` - -and it will get back 1,000 bytes of uninitialized memory from the server. - -This is a very serious bug. It's similar in severity to the -[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process -memory by remote attackers. - - -### Which real-world packages were vulnerable? - -#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) - -[Mathias Buus](https://github.com/mafintosh) and I -([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, -[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow -anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get -them to reveal 20 bytes at a time of uninitialized memory from the node.js process. - -Here's -[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) -that fixed it. We released a new fixed version, created a -[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all -vulnerable versions on npm so users will get a warning to upgrade to a newer version. - -#### [`ws`](https://www.npmjs.com/package/ws) - -That got us wondering if there were other vulnerable packages. Sure enough, within a short -period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the -most popular WebSocket implementation in node.js. - -If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as -expected, then uninitialized server memory would be disclosed to the remote peer. - -These were the vulnerable methods: - -```js -socket.send(number) -socket.ping(number) -socket.pong(number) -``` - -Here's a vulnerable socket server with some echo functionality: - -```js -server.on('connection', function (socket) { - socket.on('message', function (message) { - message = JSON.parse(message) - if (message.type === 'echo') { - socket.send(message.data) // send back the user's message - } - }) -}) -``` - -`socket.send(number)` called on the server, will disclose server memory. - -Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue -was fixed, with a more detailed explanation. Props to -[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the -[Node Security Project disclosure](https://nodesecurity.io/advisories/67). - - -### What's the solution? - -It's important that node.js offers a fast way to get memory otherwise performance-critical -applications would needlessly get a lot slower. - -But we need a better way to *signal our intent* as programmers. **When we want -uninitialized memory, we should request it explicitly.** - -Sensitive functionality should not be packed into a developer-friendly API that loosely -accepts many different types. This type of API encourages the lazy practice of passing -variables in without checking the type very carefully. - -#### A new API: `Buffer.allocUnsafe(number)` - -The functionality of creating buffers with uninitialized memory should be part of another -API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that -frequently gets user input of all sorts of different types passed into it. - -```js -var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### How do we fix node.js core? - -We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as -`semver-major`) which defends against one case: - -```js -var str = 16 -new Buffer(str, 'utf8') -``` - -In this situation, it's implied that the programmer intended the first argument to be a -string, since they passed an encoding as a second argument. Today, node.js will allocate -uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not -what the programmer intended. - -But this is only a partial solution, since if the programmer does `new Buffer(variable)` -(without an `encoding` parameter) there's no way to know what they intended. If `variable` -is sometimes a number, then uninitialized memory will sometimes be returned. - -### What's the real long-term fix? - -We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when -we need uninitialized memory. But that would break 1000s of packages. - -~~We believe the best solution is to:~~ - -~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ - -~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ - -#### Update - -We now support adding three new APIs: - -- `Buffer.from(value)` - convert from any type to a buffer -- `Buffer.alloc(size)` - create a zero-filled buffer -- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size - -This solves the core problem that affected `ws` and `bittorrent-dht` which is -`Buffer(variable)` getting tricked into taking a number argument. - -This way, existing code continues working and the impact on the npm ecosystem will be -minimal. Over time, npm maintainers can migrate performance-critical code to use -`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. - - -### Conclusion - -We think there's a serious design issue with the `Buffer` API as it exists today. It -promotes insecure software by putting high-risk functionality into a convenient API -with friendly "developer ergonomics". - -This wasn't merely a theoretical exercise because we found the issue in some of the -most popular npm packages. - -Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of -`buffer`. - -```js -var Buffer = require('safe-buffer').Buffer -``` - -Eventually, we hope that node.js core can switch to this new, safer behavior. We believe -the impact on the ecosystem would be minimal since it's not a breaking change. -Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while -older, insecure packages would magically become safe from this attack vector. - - -## links - -- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) -- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) -- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) - - -## credit - -The original issues in `bittorrent-dht` -([disclosure](https://nodesecurity.io/advisories/68)) and -`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by -[Mathias Buus](https://github.com/mafintosh) and -[Feross Aboukhadijeh](http://feross.org/). - -Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues -and for his work running the [Node Security Project](https://nodesecurity.io/). - -Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and -auditing the code. - - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/reverse_engineering/node_modules/safe-buffer/index.d.ts b/reverse_engineering/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/reverse_engineering/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -declare module "safe-buffer" { - export class Buffer { - length: number - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor (str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor (size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor (arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor (buffer: Buffer); - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; - } -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/safe-buffer/index.js b/reverse_engineering/node_modules/safe-buffer/index.js deleted file mode 100644 index f8d3ec9..0000000 --- a/reverse_engineering/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,65 +0,0 @@ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -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 { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -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) -} diff --git a/reverse_engineering/node_modules/safe-buffer/package.json b/reverse_engineering/node_modules/safe-buffer/package.json deleted file mode 100644 index f2869e2..0000000 --- a/reverse_engineering/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "safe-buffer", - "description": "Safer Node.js Buffer API", - "version": "5.2.1", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "https://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "devDependencies": { - "standard": "*", - "tape": "^5.0.0" - }, - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test/*.js" - }, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] -} diff --git a/reverse_engineering/node_modules/safer-buffer/LICENSE b/reverse_engineering/node_modules/safer-buffer/LICENSE deleted file mode 100644 index 4fe9e6f..0000000 --- a/reverse_engineering/node_modules/safer-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Nikita Skovoroda - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/safer-buffer/Porting-Buffer.md b/reverse_engineering/node_modules/safer-buffer/Porting-Buffer.md deleted file mode 100644 index 68d86ba..0000000 --- a/reverse_engineering/node_modules/safer-buffer/Porting-Buffer.md +++ /dev/null @@ -1,268 +0,0 @@ -# Porting to the Buffer.from/Buffer.alloc API - - -## Overview - -- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) -- [Variant 2: Use a polyfill](#variant-2) -- [Variant 3: manual detection, with safeguards](#variant-3) - -### Finding problematic bits of code using grep - -Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. - -It will find all the potentially unsafe places in your own code (with some considerably unlikely -exceptions). - -### Finding problematic bits of code using Node.js 8 - -If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: - -- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. -- `--trace-deprecation` does the same thing, but only for deprecation warnings. -- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. - -You can set these flags using an environment variable: - -```console -$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' -$ cat example.js -'use strict'; -const foo = new Buffer('foo'); -$ node example.js -(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. - at showFlaggedDeprecation (buffer.js:127:13) - at new Buffer (buffer.js:148:3) - at Object. (/path/to/example.js:2:13) - [... more stack trace lines ...] -``` - -### Finding problematic bits of code using linters - -Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. - -There is a drawback, though, that it doesn't always -[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is -overriden e.g. with a polyfill, so recommended is a combination of this and some other method -described above. - - -## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. - -This is the recommended solution nowadays that would imply only minimal overhead. - -The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. - -What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: - -- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. -- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). -- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. - -Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than -`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. - -Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -is recommended to avoid accidential unsafe Buffer API usage. - -There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) -for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. -Note that it currently only works with cases where the arguments are literals or where the -constructor is invoked with two arguments. - -_If you currently support those older Node.js versions and dropping them would be a semver-major change -for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) -or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive -the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and -your users will not observe a runtime deprecation warning when running your code on Node.js 10._ - - -## Variant 2: Use a polyfill - -Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older -Node.js versions. - -You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill -`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. - -Make sure that you do not use old `new Buffer` API — in any files where the line above is added, -using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. - -Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or -[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — -those are great, the only downsides being 4 deps in the tree and slightly more code changes to -migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only -`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. - -_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also -provides a polyfill, but takes a different approach which has -[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you -to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as -it is problematic, can cause issues in your code, and will start emitting runtime deprecation -warnings starting with Node.js 10._ - -Note that in either case, it is important that you also remove all calls to the old Buffer -API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides -a polyfill for the new API. I have seen people doing that mistake. - -Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -is recommended. - -_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ - - -## Variant 3 — manual detection, with safeguards - -This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own -wrapper around them. - -### Buffer(0) - -This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which -returns the same result all the way down to Node.js 0.8.x. - -### Buffer(notNumber) - -Before: - -```js -var buf = new Buffer(notNumber, encoding); -``` - -After: - -```js -var buf; -if (Buffer.from && Buffer.from !== Uint8Array.from) { - buf = Buffer.from(notNumber, encoding); -} else { - if (typeof notNumber === 'number') - throw new Error('The "size" argument must be of type number.'); - buf = new Buffer(notNumber, encoding); -} -``` - -`encoding` is optional. - -Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not -hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the -Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous -security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create -problems ranging from DoS to leaking sensitive information to the attacker from the process memory. - -When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can -be omitted. - -Also note that using TypeScript does not fix this problem for you — when libs written in -`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as -all type checks are translation-time only and are not present in the actual JS code which TS -compiles to. - -### Buffer(number) - -For Node.js 0.10.x (and below) support: - -```js -var buf; -if (Buffer.alloc) { - buf = Buffer.alloc(number); -} else { - buf = new Buffer(number); - buf.fill(0); -} -``` - -Otherwise (Node.js ≥ 0.12.x): - -```js -const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); -``` - -## Regarding Buffer.allocUnsafe - -Be extra cautious when using `Buffer.allocUnsafe`: - * Don't use it if you don't have a good reason to - * e.g. you probably won't ever see a performance difference for small buffers, in fact, those - might be even faster with `Buffer.alloc()`, - * if your code is not in the hot code path — you also probably won't notice a difference, - * keep in mind that zero-filling minimizes the potential risks. - * If you use it, make sure that you never return the buffer in a partially-filled state, - * if you are writing to it sequentially — always truncate it to the actuall written length - -Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, -ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) -leaking to the remote attacker. - -_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js -version (and lacking type checks also adds DoS to the list of potential problems)._ - - -## FAQ - - -### What is wrong with the `Buffer` constructor? - -The `Buffer` constructor could be used to create a buffer in many different ways: - -- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained - *arbitrary memory* for performance reasons, which could include anything ranging from - program source code to passwords and encryption keys. -- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of - the string `'abc'`. A second argument could specify another encoding: For example, - `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original - sequence of bytes that it represents. -- There are several other combinations of arguments. - -This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell -what exactly the contents of the generated buffer are* without knowing the type of `foo`. - -Sometimes, the value of `foo` comes from an external source. For example, this function -could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: - -``` -function stringToBase64(req, res) { - // The request body should have the format of `{ string: 'foobar' }` - const rawBytes = new Buffer(req.body.string) - const encoded = rawBytes.toString('base64') - res.end({ encoded: encoded }) -} -``` - -Note that this code does *not* validate the type of `req.body.string`: - -- `req.body.string` is expected to be a string. If this is the case, all goes well. -- `req.body.string` is controlled by the client that sends the request. -- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: - - Before Node.js 8, the content would be uninitialized - - After Node.js 8, the content would be `50` bytes with the value `0` - -Because of the missing type check, an attacker could intentionally send a number -as part of the request. Using this, they can either: - -- Read uninitialized memory. This **will** leak passwords, encryption keys and other - kinds of sensitive information. (Information leak) -- Force the program to allocate a large amount of memory. For example, when specifying - `500000000` as the input value, each request will allocate 500MB of memory. - This can be used to either exhaust the memory available of a program completely - and make it crash, or slow it down significantly. (Denial of Service) - -Both of these scenarios are considered serious security issues in a real-world -web server context. - -when using `Buffer.from(req.body.string)` instead, passing a number will always -throw an exception instead, giving a controlled behaviour that can always be -handled by the program. - - -### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? - -Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still -widely used. This includes new code, and overall usage of such code has actually been -*increasing*. diff --git a/reverse_engineering/node_modules/safer-buffer/Readme.md b/reverse_engineering/node_modules/safer-buffer/Readme.md deleted file mode 100644 index 14b0822..0000000 --- a/reverse_engineering/node_modules/safer-buffer/Readme.md +++ /dev/null @@ -1,156 +0,0 @@ -# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] - -[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master -[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer -[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg -[npm-url]: https://npmjs.org/package/safer-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com -[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg -[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md - -Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. - -## How to use? - -First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. - -Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use -`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new -Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ - -Also, see the -[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. - -## Do I need it? - -Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that -is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` -though. - -See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) -for a better description. - -## Why not [safe-buffer](https://npmjs.com/safe-buffer)? - -_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and -itself contains footguns._ - -`safe-buffer` could be used safely to get the new API while still keeping support for older -Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API -I found out that `safe-buffer` is itself causing problems in some cases. - -For example, consider the following snippet: - -```console -$ cat example.unsafe.js -console.log(Buffer(20)) -$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js - -$ standard example.unsafe.js -standard: Use JavaScript Standard Style (https://standardjs.com) - /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. -``` - -This is allocates and writes to console an uninitialized chunk of memory. -[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people -to avoid using unsafe API. - -Let's now throw in `safe-buffer`! - -```console -$ cat example.safe-buffer.js -const Buffer = require('safe-buffer').Buffer -console.log(Buffer(20)) -$ standard example.safe-buffer.js -$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js - -``` - -See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior -remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out -chunks of uninitialized memory. -_And this code will still emit runtime warnings on Node.js 10.x and above._ - -That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or -emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some -discussion, it was decided to move my approach into a separate package, and _this is that separate -package_. - -This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, -«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. - -Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request -can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go -unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even -pass CI. _I also observed that being done in popular packages._ - -Some examples: - * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) - (a module with 548 759 downloads/month), - * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) - (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), - * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) - (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), - * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) - (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), - * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) - (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). - * And there are a lot more over the ecosystem. - -I filed a PR at -[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to -partially fix that (for cases when that lint rule is used), but it is a semver-major change for -linter rules and presets, so it would take significant time for that to reach actual setups. -_It also hasn't been released yet (2018-03-20)._ - -Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. -It still supports it with an explicit concern barier, by placing it under -`require('safer-buffer/dangereous')`. - -## But isn't throwing bad? - -Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like -unguarded `new Buffer()` calls that end up receiving user input can do. - -This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so -it is really simple to keep track of things and make sure that you don't mix old API usage with that. -Also, CI should hint anything that you might have missed. - -New commits, if tested, won't land new usage of unsafe Buffer API this way. -_Node.js 10.x also deals with that by printing a runtime depecation warning._ - -### Would it affect third-party modules? - -No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. -Don't do that. - -### But I don't want throwing… - -That is also fine! - -Also, it could be better in some cases when you don't comprehensive enough test coverage. - -In that case — just don't override `Buffer` and use -`var SaferBuffer = require('safer-buffer').Buffer` instead. - -That way, everything using `Buffer` natively would still work, but there would be two drawbacks: - -* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and - `SaferBuffer.alloc` instead. -* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. - -Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly -recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. - -## «Without footguns»? - -Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property -on older versions and duping things from there. You shouldn't do that in your code, probabably. - -The intention is to remove the most significant footguns that affect lots of packages in the -ecosystem, and to do it in the proper way. - -Also, this package doesn't protect against security issues affecting some Node.js versions, so for -usage in your own production code, it is still recommended to update to a Node.js version -[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/reverse_engineering/node_modules/safer-buffer/dangerous.js b/reverse_engineering/node_modules/safer-buffer/dangerous.js deleted file mode 100644 index ca41fdc..0000000 --- a/reverse_engineering/node_modules/safer-buffer/dangerous.js +++ /dev/null @@ -1,58 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var buffer = require('buffer') -var Buffer = buffer.Buffer -var safer = require('./safer.js') -var Safer = safer.Buffer - -var dangerous = {} - -var key - -for (key in safer) { - if (!safer.hasOwnProperty(key)) continue - dangerous[key] = safer[key] -} - -var Dangereous = dangerous.Buffer = {} - -// Copy Safer API -for (key in Safer) { - if (!Safer.hasOwnProperty(key)) continue - Dangereous[key] = Safer[key] -} - -// Copy those missing unsafe methods, if they are present -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (Dangereous.hasOwnProperty(key)) continue - Dangereous[key] = Buffer[key] -} - -if (!Dangereous.allocUnsafe) { - Dangereous.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - return Buffer(size) - } -} - -if (!Dangereous.allocUnsafeSlow) { - Dangereous.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - return buffer.SlowBuffer(size) - } -} - -module.exports = dangerous diff --git a/reverse_engineering/node_modules/safer-buffer/package.json b/reverse_engineering/node_modules/safer-buffer/package.json deleted file mode 100644 index d452b04..0000000 --- a/reverse_engineering/node_modules/safer-buffer/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "safer-buffer", - "version": "2.1.2", - "description": "Modern Buffer API polyfill without footguns", - "main": "safer.js", - "scripts": { - "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", - "test": "standard && tape tests.js" - }, - "author": { - "name": "Nikita Skovoroda", - "email": "chalkerx@gmail.com", - "url": "https://github.com/ChALkeR" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/ChALkeR/safer-buffer.git" - }, - "bugs": { - "url": "https://github.com/ChALkeR/safer-buffer/issues" - }, - "devDependencies": { - "standard": "^11.0.1", - "tape": "^4.9.0" - }, - "files": [ - "Porting-Buffer.md", - "Readme.md", - "tests.js", - "dangerous.js", - "safer.js" - ] -} diff --git a/reverse_engineering/node_modules/safer-buffer/safer.js b/reverse_engineering/node_modules/safer-buffer/safer.js deleted file mode 100644 index 37c7e1a..0000000 --- a/reverse_engineering/node_modules/safer-buffer/safer.js +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var buffer = require('buffer') -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer diff --git a/reverse_engineering/node_modules/safer-buffer/tests.js b/reverse_engineering/node_modules/safer-buffer/tests.js deleted file mode 100644 index 7ed2777..0000000 --- a/reverse_engineering/node_modules/safer-buffer/tests.js +++ /dev/null @@ -1,406 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var test = require('tape') - -var buffer = require('buffer') - -var index = require('./') -var safer = require('./safer') -var dangerous = require('./dangerous') - -/* Inheritance tests */ - -test('Default is Safer', function (t) { - t.equal(index, safer) - t.notEqual(safer, dangerous) - t.notEqual(index, dangerous) - t.end() -}) - -test('Is not a function', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(typeof impl, 'object') - t.equal(typeof impl.Buffer, 'object') - }); - [buffer].forEach(function (impl) { - t.equal(typeof impl, 'object') - t.equal(typeof impl.Buffer, 'function') - }) - t.end() -}) - -test('Constructor throws', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.throws(function () { impl.Buffer() }) - t.throws(function () { impl.Buffer(0) }) - t.throws(function () { impl.Buffer('a') }) - t.throws(function () { impl.Buffer('a', 'utf-8') }) - t.throws(function () { return new impl.Buffer() }) - t.throws(function () { return new impl.Buffer(0) }) - t.throws(function () { return new impl.Buffer('a') }) - t.throws(function () { return new impl.Buffer('a', 'utf-8') }) - }) - t.end() -}) - -test('Safe methods exist', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') - t.equal(typeof impl.Buffer.from, 'function', 'from') - }) - t.end() -}) - -test('Unsafe methods exist only in Dangerous', function (t) { - [index, safer].forEach(function (impl) { - t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') - t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') - }); - [dangerous].forEach(function (impl) { - t.equal(typeof impl.Buffer.allocUnsafe, 'function') - t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') - }) - t.end() -}) - -test('Generic methods/properties are defined and equal', function (t) { - ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], buffer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Built-in buffer static methods/properties are inherited', function (t) { - Object.keys(buffer).forEach(function (method) { - if (method === 'SlowBuffer' || method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], buffer[method], method) - t.notEqual(typeof impl[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Built-in Buffer static methods/properties are inherited', function (t) { - Object.keys(buffer.Buffer).forEach(function (method) { - if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], buffer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('.prototype property of Buffer is inherited', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') - t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') - }) - t.end() -}) - -test('All Safer methods are present in Dangerous', function (t) { - Object.keys(safer).forEach(function (method) { - if (method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], safer[method], method) - if (method !== 'kStringMaxLength') { - t.notEqual(typeof impl[method], 'undefined', method) - } - }) - }) - Object.keys(safer.Buffer).forEach(function (method) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], safer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Safe methods from Dangerous methods are present in Safer', function (t) { - Object.keys(dangerous).forEach(function (method) { - if (method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], dangerous[method], method) - if (method !== 'kStringMaxLength') { - t.notEqual(typeof impl[method], 'undefined', method) - } - }) - }) - Object.keys(dangerous.Buffer).forEach(function (method) { - if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], dangerous.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -/* Behaviour tests */ - -test('Methods return Buffers', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) - t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) - }) - t.end() -}) - -test('Constructor is buffer.Buffer', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) - t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) - t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) - t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) - }); - [0, 10, 100].forEach(function (arg) { - t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) - t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) - }) - t.end() -}) - -test('Invalid calls throw', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.throws(function () { impl.Buffer.from(0) }) - t.throws(function () { impl.Buffer.from(10) }) - t.throws(function () { impl.Buffer.from(10, 'utf-8') }) - t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) - t.throws(function () { impl.Buffer.from(-10) }) - t.throws(function () { impl.Buffer.from(1e90) }) - t.throws(function () { impl.Buffer.from(Infinity) }) - t.throws(function () { impl.Buffer.from(-Infinity) }) - t.throws(function () { impl.Buffer.from(NaN) }) - t.throws(function () { impl.Buffer.from(null) }) - t.throws(function () { impl.Buffer.from(undefined) }) - t.throws(function () { impl.Buffer.from() }) - t.throws(function () { impl.Buffer.from({}) }) - t.throws(function () { impl.Buffer.alloc('') }) - t.throws(function () { impl.Buffer.alloc('string') }) - t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) - t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) - t.throws(function () { impl.Buffer.alloc(-10) }) - t.throws(function () { impl.Buffer.alloc(1e90) }) - t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) - t.throws(function () { impl.Buffer.alloc(Infinity) }) - t.throws(function () { impl.Buffer.alloc(-Infinity) }) - t.throws(function () { impl.Buffer.alloc(null) }) - t.throws(function () { impl.Buffer.alloc(undefined) }) - t.throws(function () { impl.Buffer.alloc() }) - t.throws(function () { impl.Buffer.alloc([]) }) - t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) - t.throws(function () { impl.Buffer.alloc({}) }) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.throws(function () { dangerous.Buffer[method]('') }) - t.throws(function () { dangerous.Buffer[method]('string') }) - t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) - t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) - t.throws(function () { dangerous.Buffer[method](Infinity) }) - if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { - t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') - } else { - t.throws(function () { dangerous.Buffer[method](-10) }) - t.throws(function () { dangerous.Buffer[method](-1e90) }) - t.throws(function () { dangerous.Buffer[method](-Infinity) }) - } - t.throws(function () { dangerous.Buffer[method](null) }) - t.throws(function () { dangerous.Buffer[method](undefined) }) - t.throws(function () { dangerous.Buffer[method]() }) - t.throws(function () { dangerous.Buffer[method]([]) }) - t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) - t.throws(function () { dangerous.Buffer[method]({}) }) - }) - t.end() -}) - -test('Buffers have appropriate lengths', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.alloc(0).length, 0) - t.equal(impl.Buffer.alloc(10).length, 10) - t.equal(impl.Buffer.from('').length, 0) - t.equal(impl.Buffer.from('string').length, 6) - t.equal(impl.Buffer.from('string', 'utf-8').length, 6) - t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) - t.equal(impl.Buffer.from([0, 42, 3]).length, 3) - t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) - t.equal(impl.Buffer.from([]).length, 0) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.equal(dangerous.Buffer[method](0).length, 0) - t.equal(dangerous.Buffer[method](10).length, 10) - }) - t.end() -}) - -test('Buffers have appropriate lengths (2)', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true; - [ safer.Buffer.alloc, - dangerous.Buffer.allocUnsafe, - dangerous.Buffer.allocUnsafeSlow - ].forEach(function (method) { - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 1e5) - var buf = method(length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - } - }) - t.ok(ok) - t.end() -}) - -test('.alloc(size) is zero-filled and has correct length', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var buf = index.Buffer.alloc(length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - var j - for (j = 0; j < length; j++) { - if (buf[j] !== 0) ok = false - } - buf.fill(1) - for (j = 0; j < length; j++) { - if (buf[j] !== 1) ok = false - } - } - t.ok(ok) - t.end() -}) - -test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var buf = dangerous.Buffer[method](length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - buf.fill(0, 0, length) - var j - for (j = 0; j < length; j++) { - if (buf[j] !== 0) ok = false - } - buf.fill(1, 0, length) - for (j = 0; j < length; j++) { - if (buf[j] !== 1) ok = false - } - } - t.ok(ok, method) - }) - t.end() -}) - -test('.alloc(size, fill) is `fill`-filled', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var fill = Math.round(Math.random() * 255) - var buf = index.Buffer.alloc(length, fill) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - for (var j = 0; j < length; j++) { - if (buf[j] !== fill) ok = false - } - } - t.ok(ok) - t.end() -}) - -test('.alloc(size, fill) is `fill`-filled', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var fill = Math.round(Math.random() * 255) - var buf = index.Buffer.alloc(length, fill) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - for (var j = 0; j < length; j++) { - if (buf[j] !== fill) ok = false - } - } - t.ok(ok) - t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) - t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) - - var tmp = new buffer.Buffer(2) - tmp.fill('ok') - if (tmp[1] === tmp[0]) { - // Outdated Node.js - t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) - } else { - t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) - } - t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) - - t.end() -}) - -test('safer.Buffer.from returns results same as Buffer constructor', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) - t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) - t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) - t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) - t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) - t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) - t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) - }) - t.end() -}) - -test('safer.Buffer.from returns consistent results', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) - t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) - t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) - t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) - t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) - }) - t.end() -}) diff --git a/reverse_engineering/node_modules/saslprep/.editorconfig b/reverse_engineering/node_modules/saslprep/.editorconfig deleted file mode 100644 index d1d8a41..0000000 --- a/reverse_engineering/node_modules/saslprep/.editorconfig +++ /dev/null @@ -1,10 +0,0 @@ -# http://editorconfig.org -root = true - -[*] -indent_style = space -indent_size = 2 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true diff --git a/reverse_engineering/node_modules/saslprep/.gitattributes b/reverse_engineering/node_modules/saslprep/.gitattributes deleted file mode 100644 index 3ba4536..0000000 --- a/reverse_engineering/node_modules/saslprep/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.mem binary diff --git a/reverse_engineering/node_modules/saslprep/.travis.yml b/reverse_engineering/node_modules/saslprep/.travis.yml deleted file mode 100644 index 0bca826..0000000 --- a/reverse_engineering/node_modules/saslprep/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -sudo: false -language: node_js -node_js: - - "6" - - "8" - - "10" - - "12" - -before_install: -- npm install -g npm@6 diff --git a/reverse_engineering/node_modules/saslprep/CHANGELOG.md b/reverse_engineering/node_modules/saslprep/CHANGELOG.md deleted file mode 100644 index 7798078..0000000 --- a/reverse_engineering/node_modules/saslprep/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -# Change Log -All notable changes to the "saslprep" package will be documented in this file. - -## [1.0.3] - 2019-05-01 - -- Correctly get code points >U+FFFF ([#5](https://github.com/reklatsmasters/saslprep/pull/5)) -- Fix perfomance downgrades from [#5](https://github.com/reklatsmasters/saslprep/pull/5). - -## [1.0.2] - 2018-09-13 - -- Reduced initialization time ([#3](https://github.com/reklatsmasters/saslprep/issues/3)) - -## [1.0.1] - 2018-06-20 - -- Reduced stack overhead of range creation ([#2](https://github.com/reklatsmasters/saslprep/pull/2)) - -## [1.0.0] - 2017-06-21 - -- First release diff --git a/reverse_engineering/node_modules/saslprep/LICENSE b/reverse_engineering/node_modules/saslprep/LICENSE deleted file mode 100644 index 481c7a5..0000000 --- a/reverse_engineering/node_modules/saslprep/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 Dmitry Tsvettsikh - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/saslprep/code-points.mem b/reverse_engineering/node_modules/saslprep/code-points.mem deleted file mode 100644 index 4781b06..0000000 Binary files a/reverse_engineering/node_modules/saslprep/code-points.mem and /dev/null differ diff --git a/reverse_engineering/node_modules/saslprep/generate-code-points.js b/reverse_engineering/node_modules/saslprep/generate-code-points.js deleted file mode 100644 index c5162ca..0000000 --- a/reverse_engineering/node_modules/saslprep/generate-code-points.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -const bitfield = require('sparse-bitfield'); -const codePoints = require('./lib/code-points'); - -const unassigned_code_points = bitfield(); -const commonly_mapped_to_nothing = bitfield(); -const non_ascii_space_characters = bitfield(); -const prohibited_characters = bitfield(); -const bidirectional_r_al = bitfield(); -const bidirectional_l = bitfield(); - -/** - * Iterare over code points and - * convert it into an buffer. - * @param {bitfield} bits - * @param {Array} src - * @returns {Buffer} - */ -function traverse(bits, src) { - for (const code of src.keys()) { - bits.set(code, true); - } - - const buffer = bits.toBuffer(); - return Buffer.concat([createSize(buffer), buffer]); -} - -/** - * @param {Buffer} buffer - * @returns {Buffer} - */ -function createSize(buffer) { - const buf = Buffer.alloc(4); - buf.writeUInt32BE(buffer.length); - - return buf; -} - -const memory = []; - -memory.push( - traverse(unassigned_code_points, codePoints.unassigned_code_points), - traverse(commonly_mapped_to_nothing, codePoints.commonly_mapped_to_nothing), - traverse(non_ascii_space_characters, codePoints.non_ASCII_space_characters), - traverse(prohibited_characters, codePoints.prohibited_characters), - traverse(bidirectional_r_al, codePoints.bidirectional_r_al), - traverse(bidirectional_l, codePoints.bidirectional_l) -); - -process.stdout.write(Buffer.concat(memory)); diff --git a/reverse_engineering/node_modules/saslprep/index.js b/reverse_engineering/node_modules/saslprep/index.js deleted file mode 100644 index 21bb0fe..0000000 --- a/reverse_engineering/node_modules/saslprep/index.js +++ /dev/null @@ -1,157 +0,0 @@ -'use strict'; - -const { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -} = require('./lib/memory-code-points'); - -module.exports = saslprep; - -// 2.1. Mapping - -/** - * non-ASCII space characters [StringPrep, C.1.2] that can be - * mapped to SPACE (U+0020) - */ -const mapping2space = non_ASCII_space_characters; - -/** - * the "commonly mapped to nothing" characters [StringPrep, B.1] - * that can be mapped to nothing. - */ -const mapping2nothing = commonly_mapped_to_nothing; - -// utils -const getCodePoint = character => character.codePointAt(0); -const first = x => x[0]; -const last = x => x[x.length - 1]; - -/** - * Convert provided string into an array of Unicode Code Points. - * Based on https://stackoverflow.com/a/21409165/1556249 - * and https://www.npmjs.com/package/code-point-at. - * @param {string} input - * @returns {number[]} - */ -function toCodePoints(input) { - const codepoints = []; - const size = input.length; - - for (let i = 0; i < size; i += 1) { - const before = input.charCodeAt(i); - - if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { - const next = input.charCodeAt(i + 1); - - if (next >= 0xdc00 && next <= 0xdfff) { - codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); - i += 1; - continue; - } - } - - codepoints.push(before); - } - - return codepoints; -} - -/** - * SASLprep. - * @param {string} input - * @param {Object} opts - * @param {boolean} opts.allowUnassigned - * @returns {string} - */ -function saslprep(input, opts = {}) { - if (typeof input !== 'string') { - throw new TypeError('Expected string.'); - } - - if (input.length === 0) { - return ''; - } - - // 1. Map - const mapped_input = toCodePoints(input) - // 1.1 mapping to space - .map(character => (mapping2space.get(character) ? 0x20 : character)) - // 1.2 mapping to nothing - .filter(character => !mapping2nothing.get(character)); - - // 2. Normalize - const normalized_input = String.fromCodePoint - .apply(null, mapped_input) - .normalize('NFKC'); - - const normalized_map = toCodePoints(normalized_input); - - // 3. Prohibit - const hasProhibited = normalized_map.some(character => - prohibited_characters.get(character) - ); - - if (hasProhibited) { - throw new Error( - 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' - ); - } - - // Unassigned Code Points - if (opts.allowUnassigned !== true) { - const hasUnassigned = normalized_map.some(character => - unassigned_code_points.get(character) - ); - - if (hasUnassigned) { - throw new Error( - 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' - ); - } - } - - // 4. check bidi - - const hasBidiRAL = normalized_map.some(character => - bidirectional_r_al.get(character) - ); - - const hasBidiL = normalized_map.some(character => - bidirectional_l.get(character) - ); - - // 4.1 If a string contains any RandALCat character, the string MUST NOT - // contain any LCat character. - if (hasBidiRAL && hasBidiL) { - throw new Error( - 'String must not contain RandALCat and LCat at the same time,' + - ' see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - /** - * 4.2 If a string contains any RandALCat character, a RandALCat - * character MUST be the first character of the string, and a - * RandALCat character MUST be the last character of the string. - */ - - const isFirstBidiRAL = bidirectional_r_al.get( - getCodePoint(first(normalized_input)) - ); - const isLastBidiRAL = bidirectional_r_al.get( - getCodePoint(last(normalized_input)) - ); - - if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { - throw new Error( - 'Bidirectional RandALCat character must be the first and the last' + - ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - return normalized_input; -} diff --git a/reverse_engineering/node_modules/saslprep/lib/code-points.js b/reverse_engineering/node_modules/saslprep/lib/code-points.js deleted file mode 100644 index 222182c..0000000 --- a/reverse_engineering/node_modules/saslprep/lib/code-points.js +++ /dev/null @@ -1,996 +0,0 @@ -'use strict'; - -const { range } = require('./util'); - -/** - * A.1 Unassigned code points in Unicode 3.2 - * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 - */ -const unassigned_code_points = new Set([ - 0x0221, - ...range(0x0234, 0x024f), - ...range(0x02ae, 0x02af), - ...range(0x02ef, 0x02ff), - ...range(0x0350, 0x035f), - ...range(0x0370, 0x0373), - ...range(0x0376, 0x0379), - ...range(0x037b, 0x037d), - ...range(0x037f, 0x0383), - 0x038b, - 0x038d, - 0x03a2, - 0x03cf, - ...range(0x03f7, 0x03ff), - 0x0487, - 0x04cf, - ...range(0x04f6, 0x04f7), - ...range(0x04fa, 0x04ff), - ...range(0x0510, 0x0530), - ...range(0x0557, 0x0558), - 0x0560, - 0x0588, - ...range(0x058b, 0x0590), - 0x05a2, - 0x05ba, - ...range(0x05c5, 0x05cf), - ...range(0x05eb, 0x05ef), - ...range(0x05f5, 0x060b), - ...range(0x060d, 0x061a), - ...range(0x061c, 0x061e), - 0x0620, - ...range(0x063b, 0x063f), - ...range(0x0656, 0x065f), - ...range(0x06ee, 0x06ef), - 0x06ff, - 0x070e, - ...range(0x072d, 0x072f), - ...range(0x074b, 0x077f), - ...range(0x07b2, 0x0900), - 0x0904, - ...range(0x093a, 0x093b), - ...range(0x094e, 0x094f), - ...range(0x0955, 0x0957), - ...range(0x0971, 0x0980), - 0x0984, - ...range(0x098d, 0x098e), - ...range(0x0991, 0x0992), - 0x09a9, - 0x09b1, - ...range(0x09b3, 0x09b5), - ...range(0x09ba, 0x09bb), - 0x09bd, - ...range(0x09c5, 0x09c6), - ...range(0x09c9, 0x09ca), - ...range(0x09ce, 0x09d6), - ...range(0x09d8, 0x09db), - 0x09de, - ...range(0x09e4, 0x09e5), - ...range(0x09fb, 0x0a01), - ...range(0x0a03, 0x0a04), - ...range(0x0a0b, 0x0a0e), - ...range(0x0a11, 0x0a12), - 0x0a29, - 0x0a31, - 0x0a34, - 0x0a37, - ...range(0x0a3a, 0x0a3b), - 0x0a3d, - ...range(0x0a43, 0x0a46), - ...range(0x0a49, 0x0a4a), - ...range(0x0a4e, 0x0a58), - 0x0a5d, - ...range(0x0a5f, 0x0a65), - ...range(0x0a75, 0x0a80), - 0x0a84, - 0x0a8c, - 0x0a8e, - 0x0a92, - 0x0aa9, - 0x0ab1, - 0x0ab4, - ...range(0x0aba, 0x0abb), - 0x0ac6, - 0x0aca, - ...range(0x0ace, 0x0acf), - ...range(0x0ad1, 0x0adf), - ...range(0x0ae1, 0x0ae5), - ...range(0x0af0, 0x0b00), - 0x0b04, - ...range(0x0b0d, 0x0b0e), - ...range(0x0b11, 0x0b12), - 0x0b29, - 0x0b31, - ...range(0x0b34, 0x0b35), - ...range(0x0b3a, 0x0b3b), - ...range(0x0b44, 0x0b46), - ...range(0x0b49, 0x0b4a), - ...range(0x0b4e, 0x0b55), - ...range(0x0b58, 0x0b5b), - 0x0b5e, - ...range(0x0b62, 0x0b65), - ...range(0x0b71, 0x0b81), - 0x0b84, - ...range(0x0b8b, 0x0b8d), - 0x0b91, - ...range(0x0b96, 0x0b98), - 0x0b9b, - 0x0b9d, - ...range(0x0ba0, 0x0ba2), - ...range(0x0ba5, 0x0ba7), - ...range(0x0bab, 0x0bad), - 0x0bb6, - ...range(0x0bba, 0x0bbd), - ...range(0x0bc3, 0x0bc5), - 0x0bc9, - ...range(0x0bce, 0x0bd6), - ...range(0x0bd8, 0x0be6), - ...range(0x0bf3, 0x0c00), - 0x0c04, - 0x0c0d, - 0x0c11, - 0x0c29, - 0x0c34, - ...range(0x0c3a, 0x0c3d), - 0x0c45, - 0x0c49, - ...range(0x0c4e, 0x0c54), - ...range(0x0c57, 0x0c5f), - ...range(0x0c62, 0x0c65), - ...range(0x0c70, 0x0c81), - 0x0c84, - 0x0c8d, - 0x0c91, - 0x0ca9, - 0x0cb4, - ...range(0x0cba, 0x0cbd), - 0x0cc5, - 0x0cc9, - ...range(0x0cce, 0x0cd4), - ...range(0x0cd7, 0x0cdd), - 0x0cdf, - ...range(0x0ce2, 0x0ce5), - ...range(0x0cf0, 0x0d01), - 0x0d04, - 0x0d0d, - 0x0d11, - 0x0d29, - ...range(0x0d3a, 0x0d3d), - ...range(0x0d44, 0x0d45), - 0x0d49, - ...range(0x0d4e, 0x0d56), - ...range(0x0d58, 0x0d5f), - ...range(0x0d62, 0x0d65), - ...range(0x0d70, 0x0d81), - 0x0d84, - ...range(0x0d97, 0x0d99), - 0x0db2, - 0x0dbc, - ...range(0x0dbe, 0x0dbf), - ...range(0x0dc7, 0x0dc9), - ...range(0x0dcb, 0x0dce), - 0x0dd5, - 0x0dd7, - ...range(0x0de0, 0x0df1), - ...range(0x0df5, 0x0e00), - ...range(0x0e3b, 0x0e3e), - ...range(0x0e5c, 0x0e80), - 0x0e83, - ...range(0x0e85, 0x0e86), - 0x0e89, - ...range(0x0e8b, 0x0e8c), - ...range(0x0e8e, 0x0e93), - 0x0e98, - 0x0ea0, - 0x0ea4, - 0x0ea6, - ...range(0x0ea8, 0x0ea9), - 0x0eac, - 0x0eba, - ...range(0x0ebe, 0x0ebf), - 0x0ec5, - 0x0ec7, - ...range(0x0ece, 0x0ecf), - ...range(0x0eda, 0x0edb), - ...range(0x0ede, 0x0eff), - 0x0f48, - ...range(0x0f6b, 0x0f70), - ...range(0x0f8c, 0x0f8f), - 0x0f98, - 0x0fbd, - ...range(0x0fcd, 0x0fce), - ...range(0x0fd0, 0x0fff), - 0x1022, - 0x1028, - 0x102b, - ...range(0x1033, 0x1035), - ...range(0x103a, 0x103f), - ...range(0x105a, 0x109f), - ...range(0x10c6, 0x10cf), - ...range(0x10f9, 0x10fa), - ...range(0x10fc, 0x10ff), - ...range(0x115a, 0x115e), - ...range(0x11a3, 0x11a7), - ...range(0x11fa, 0x11ff), - 0x1207, - 0x1247, - 0x1249, - ...range(0x124e, 0x124f), - 0x1257, - 0x1259, - ...range(0x125e, 0x125f), - 0x1287, - 0x1289, - ...range(0x128e, 0x128f), - 0x12af, - 0x12b1, - ...range(0x12b6, 0x12b7), - 0x12bf, - 0x12c1, - ...range(0x12c6, 0x12c7), - 0x12cf, - 0x12d7, - 0x12ef, - 0x130f, - 0x1311, - ...range(0x1316, 0x1317), - 0x131f, - 0x1347, - ...range(0x135b, 0x1360), - ...range(0x137d, 0x139f), - ...range(0x13f5, 0x1400), - ...range(0x1677, 0x167f), - ...range(0x169d, 0x169f), - ...range(0x16f1, 0x16ff), - 0x170d, - ...range(0x1715, 0x171f), - ...range(0x1737, 0x173f), - ...range(0x1754, 0x175f), - 0x176d, - 0x1771, - ...range(0x1774, 0x177f), - ...range(0x17dd, 0x17df), - ...range(0x17ea, 0x17ff), - 0x180f, - ...range(0x181a, 0x181f), - ...range(0x1878, 0x187f), - ...range(0x18aa, 0x1dff), - ...range(0x1e9c, 0x1e9f), - ...range(0x1efa, 0x1eff), - ...range(0x1f16, 0x1f17), - ...range(0x1f1e, 0x1f1f), - ...range(0x1f46, 0x1f47), - ...range(0x1f4e, 0x1f4f), - 0x1f58, - 0x1f5a, - 0x1f5c, - 0x1f5e, - ...range(0x1f7e, 0x1f7f), - 0x1fb5, - 0x1fc5, - ...range(0x1fd4, 0x1fd5), - 0x1fdc, - ...range(0x1ff0, 0x1ff1), - 0x1ff5, - 0x1fff, - ...range(0x2053, 0x2056), - ...range(0x2058, 0x205e), - ...range(0x2064, 0x2069), - ...range(0x2072, 0x2073), - ...range(0x208f, 0x209f), - ...range(0x20b2, 0x20cf), - ...range(0x20eb, 0x20ff), - ...range(0x213b, 0x213c), - ...range(0x214c, 0x2152), - ...range(0x2184, 0x218f), - ...range(0x23cf, 0x23ff), - ...range(0x2427, 0x243f), - ...range(0x244b, 0x245f), - 0x24ff, - ...range(0x2614, 0x2615), - 0x2618, - ...range(0x267e, 0x267f), - ...range(0x268a, 0x2700), - 0x2705, - ...range(0x270a, 0x270b), - 0x2728, - 0x274c, - 0x274e, - ...range(0x2753, 0x2755), - 0x2757, - ...range(0x275f, 0x2760), - ...range(0x2795, 0x2797), - 0x27b0, - ...range(0x27bf, 0x27cf), - ...range(0x27ec, 0x27ef), - ...range(0x2b00, 0x2e7f), - 0x2e9a, - ...range(0x2ef4, 0x2eff), - ...range(0x2fd6, 0x2fef), - ...range(0x2ffc, 0x2fff), - 0x3040, - ...range(0x3097, 0x3098), - ...range(0x3100, 0x3104), - ...range(0x312d, 0x3130), - 0x318f, - ...range(0x31b8, 0x31ef), - ...range(0x321d, 0x321f), - ...range(0x3244, 0x3250), - ...range(0x327c, 0x327e), - ...range(0x32cc, 0x32cf), - 0x32ff, - ...range(0x3377, 0x337a), - ...range(0x33de, 0x33df), - 0x33ff, - ...range(0x4db6, 0x4dff), - ...range(0x9fa6, 0x9fff), - ...range(0xa48d, 0xa48f), - ...range(0xa4c7, 0xabff), - ...range(0xd7a4, 0xd7ff), - ...range(0xfa2e, 0xfa2f), - ...range(0xfa6b, 0xfaff), - ...range(0xfb07, 0xfb12), - ...range(0xfb18, 0xfb1c), - 0xfb37, - 0xfb3d, - 0xfb3f, - 0xfb42, - 0xfb45, - ...range(0xfbb2, 0xfbd2), - ...range(0xfd40, 0xfd4f), - ...range(0xfd90, 0xfd91), - ...range(0xfdc8, 0xfdcf), - ...range(0xfdfd, 0xfdff), - ...range(0xfe10, 0xfe1f), - ...range(0xfe24, 0xfe2f), - ...range(0xfe47, 0xfe48), - 0xfe53, - 0xfe67, - ...range(0xfe6c, 0xfe6f), - 0xfe75, - ...range(0xfefd, 0xfefe), - 0xff00, - ...range(0xffbf, 0xffc1), - ...range(0xffc8, 0xffc9), - ...range(0xffd0, 0xffd1), - ...range(0xffd8, 0xffd9), - ...range(0xffdd, 0xffdf), - 0xffe7, - ...range(0xffef, 0xfff8), - ...range(0x10000, 0x102ff), - 0x1031f, - ...range(0x10324, 0x1032f), - ...range(0x1034b, 0x103ff), - ...range(0x10426, 0x10427), - ...range(0x1044e, 0x1cfff), - ...range(0x1d0f6, 0x1d0ff), - ...range(0x1d127, 0x1d129), - ...range(0x1d1de, 0x1d3ff), - 0x1d455, - 0x1d49d, - ...range(0x1d4a0, 0x1d4a1), - ...range(0x1d4a3, 0x1d4a4), - ...range(0x1d4a7, 0x1d4a8), - 0x1d4ad, - 0x1d4ba, - 0x1d4bc, - 0x1d4c1, - 0x1d4c4, - 0x1d506, - ...range(0x1d50b, 0x1d50c), - 0x1d515, - 0x1d51d, - 0x1d53a, - 0x1d53f, - 0x1d545, - ...range(0x1d547, 0x1d549), - 0x1d551, - ...range(0x1d6a4, 0x1d6a7), - ...range(0x1d7ca, 0x1d7cd), - ...range(0x1d800, 0x1fffd), - ...range(0x2a6d7, 0x2f7ff), - ...range(0x2fa1e, 0x2fffd), - ...range(0x30000, 0x3fffd), - ...range(0x40000, 0x4fffd), - ...range(0x50000, 0x5fffd), - ...range(0x60000, 0x6fffd), - ...range(0x70000, 0x7fffd), - ...range(0x80000, 0x8fffd), - ...range(0x90000, 0x9fffd), - ...range(0xa0000, 0xafffd), - ...range(0xb0000, 0xbfffd), - ...range(0xc0000, 0xcfffd), - ...range(0xd0000, 0xdfffd), - 0xe0000, - ...range(0xe0002, 0xe001f), - ...range(0xe0080, 0xefffd), -]); - -/** - * B.1 Commonly mapped to nothing - * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 - */ -const commonly_mapped_to_nothing = new Set([ - 0x00ad, - 0x034f, - 0x1806, - 0x180b, - 0x180c, - 0x180d, - 0x200b, - 0x200c, - 0x200d, - 0x2060, - 0xfe00, - 0xfe01, - 0xfe02, - 0xfe03, - 0xfe04, - 0xfe05, - 0xfe06, - 0xfe07, - 0xfe08, - 0xfe09, - 0xfe0a, - 0xfe0b, - 0xfe0c, - 0xfe0d, - 0xfe0e, - 0xfe0f, - 0xfeff, -]); - -/** - * C.1.2 Non-ASCII space characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 - */ -const non_ASCII_space_characters = new Set([ - 0x00a0 /* NO-BREAK SPACE */, - 0x1680 /* OGHAM SPACE MARK */, - 0x2000 /* EN QUAD */, - 0x2001 /* EM QUAD */, - 0x2002 /* EN SPACE */, - 0x2003 /* EM SPACE */, - 0x2004 /* THREE-PER-EM SPACE */, - 0x2005 /* FOUR-PER-EM SPACE */, - 0x2006 /* SIX-PER-EM SPACE */, - 0x2007 /* FIGURE SPACE */, - 0x2008 /* PUNCTUATION SPACE */, - 0x2009 /* THIN SPACE */, - 0x200a /* HAIR SPACE */, - 0x200b /* ZERO WIDTH SPACE */, - 0x202f /* NARROW NO-BREAK SPACE */, - 0x205f /* MEDIUM MATHEMATICAL SPACE */, - 0x3000 /* IDEOGRAPHIC SPACE */, -]); - -/** - * 2.3. Prohibited Output - * @type {Set} - */ -const prohibited_characters = new Set([ - ...non_ASCII_space_characters, - - /** - * C.2.1 ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 - */ - ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, - 0x007f /* DELETE */, - - /** - * C.2.2 Non-ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 - */ - ...range(0x0080, 0x009f) /* [CONTROL CHARACTERS] */, - 0x06dd /* ARABIC END OF AYAH */, - 0x070f /* SYRIAC ABBREVIATION MARK */, - 0x180e /* MONGOLIAN VOWEL SEPARATOR */, - 0x200c /* ZERO WIDTH NON-JOINER */, - 0x200d /* ZERO WIDTH JOINER */, - 0x2028 /* LINE SEPARATOR */, - 0x2029 /* PARAGRAPH SEPARATOR */, - 0x2060 /* WORD JOINER */, - 0x2061 /* FUNCTION APPLICATION */, - 0x2062 /* INVISIBLE TIMES */, - 0x2063 /* INVISIBLE SEPARATOR */, - ...range(0x206a, 0x206f) /* [CONTROL CHARACTERS] */, - 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, - ...range(0xfff9, 0xfffc) /* [CONTROL CHARACTERS] */, - ...range(0x1d173, 0x1d17a) /* [MUSICAL CONTROL CHARACTERS] */, - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - ...range(0xe000, 0xf8ff) /* [PRIVATE USE, PLANE 0] */, - ...range(0xf0000, 0xffffd) /* [PRIVATE USE, PLANE 15] */, - ...range(0x100000, 0x10fffd) /* [PRIVATE USE, PLANE 16] */, - - /** - * C.4 Non-character code points - * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 - */ - ...range(0xfdd0, 0xfdef) /* [NONCHARACTER CODE POINTS] */, - ...range(0xfffe, 0xffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x1fffe, 0x1ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x2fffe, 0x2ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x3fffe, 0x3ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x4fffe, 0x4ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x5fffe, 0x5ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x6fffe, 0x6ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x7fffe, 0x7ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x8fffe, 0x8ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x9fffe, 0x9ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xafffe, 0xaffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xbfffe, 0xbffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xcfffe, 0xcffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xdfffe, 0xdffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xefffe, 0xeffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x10fffe, 0x10ffff) /* [NONCHARACTER CODE POINTS] */, - - /** - * C.5 Surrogate codes - * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 - */ - ...range(0xd800, 0xdfff), - - /** - * C.6 Inappropriate for plain text - * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 - */ - 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, - 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, - 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, - 0xfffc /* OBJECT REPLACEMENT CHARACTER */, - 0xfffd /* REPLACEMENT CHARACTER */, - - /** - * C.7 Inappropriate for canonical representation - * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 - */ - ...range(0x2ff0, 0x2ffb) /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, - - /** - * C.8 Change display properties or are deprecated - * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 - */ - 0x0340 /* COMBINING GRAVE TONE MARK */, - 0x0341 /* COMBINING ACUTE TONE MARK */, - 0x200e /* LEFT-TO-RIGHT MARK */, - 0x200f /* RIGHT-TO-LEFT MARK */, - 0x202a /* LEFT-TO-RIGHT EMBEDDING */, - 0x202b /* RIGHT-TO-LEFT EMBEDDING */, - 0x202c /* POP DIRECTIONAL FORMATTING */, - 0x202d /* LEFT-TO-RIGHT OVERRIDE */, - 0x202e /* RIGHT-TO-LEFT OVERRIDE */, - 0x206a /* INHIBIT SYMMETRIC SWAPPING */, - 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, - 0x206c /* INHIBIT ARABIC FORM SHAPING */, - 0x206d /* ACTIVATE ARABIC FORM SHAPING */, - 0x206e /* NATIONAL DIGIT SHAPES */, - 0x206f /* NOMINAL DIGIT SHAPES */, - - /** - * C.9 Tagging characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 - */ - 0xe0001 /* LANGUAGE TAG */, - ...range(0xe0020, 0xe007f) /* [TAGGING CHARACTERS] */, -]); - -/** - * D.1 Characters with bidirectional property "R" or "AL" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 - */ -const bidirectional_r_al = new Set([ - 0x05be, - 0x05c0, - 0x05c3, - ...range(0x05d0, 0x05ea), - ...range(0x05f0, 0x05f4), - 0x061b, - 0x061f, - ...range(0x0621, 0x063a), - ...range(0x0640, 0x064a), - ...range(0x066d, 0x066f), - ...range(0x0671, 0x06d5), - 0x06dd, - ...range(0x06e5, 0x06e6), - ...range(0x06fa, 0x06fe), - ...range(0x0700, 0x070d), - 0x0710, - ...range(0x0712, 0x072c), - ...range(0x0780, 0x07a5), - 0x07b1, - 0x200f, - 0xfb1d, - ...range(0xfb1f, 0xfb28), - ...range(0xfb2a, 0xfb36), - ...range(0xfb38, 0xfb3c), - 0xfb3e, - ...range(0xfb40, 0xfb41), - ...range(0xfb43, 0xfb44), - ...range(0xfb46, 0xfbb1), - ...range(0xfbd3, 0xfd3d), - ...range(0xfd50, 0xfd8f), - ...range(0xfd92, 0xfdc7), - ...range(0xfdf0, 0xfdfc), - ...range(0xfe70, 0xfe74), - ...range(0xfe76, 0xfefc), -]); - -/** - * D.2 Characters with bidirectional property "L" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 - */ -const bidirectional_l = new Set([ - ...range(0x0041, 0x005a), - ...range(0x0061, 0x007a), - 0x00aa, - 0x00b5, - 0x00ba, - ...range(0x00c0, 0x00d6), - ...range(0x00d8, 0x00f6), - ...range(0x00f8, 0x0220), - ...range(0x0222, 0x0233), - ...range(0x0250, 0x02ad), - ...range(0x02b0, 0x02b8), - ...range(0x02bb, 0x02c1), - ...range(0x02d0, 0x02d1), - ...range(0x02e0, 0x02e4), - 0x02ee, - 0x037a, - 0x0386, - ...range(0x0388, 0x038a), - 0x038c, - ...range(0x038e, 0x03a1), - ...range(0x03a3, 0x03ce), - ...range(0x03d0, 0x03f5), - ...range(0x0400, 0x0482), - ...range(0x048a, 0x04ce), - ...range(0x04d0, 0x04f5), - ...range(0x04f8, 0x04f9), - ...range(0x0500, 0x050f), - ...range(0x0531, 0x0556), - ...range(0x0559, 0x055f), - ...range(0x0561, 0x0587), - 0x0589, - 0x0903, - ...range(0x0905, 0x0939), - ...range(0x093d, 0x0940), - ...range(0x0949, 0x094c), - 0x0950, - ...range(0x0958, 0x0961), - ...range(0x0964, 0x0970), - ...range(0x0982, 0x0983), - ...range(0x0985, 0x098c), - ...range(0x098f, 0x0990), - ...range(0x0993, 0x09a8), - ...range(0x09aa, 0x09b0), - 0x09b2, - ...range(0x09b6, 0x09b9), - ...range(0x09be, 0x09c0), - ...range(0x09c7, 0x09c8), - ...range(0x09cb, 0x09cc), - 0x09d7, - ...range(0x09dc, 0x09dd), - ...range(0x09df, 0x09e1), - ...range(0x09e6, 0x09f1), - ...range(0x09f4, 0x09fa), - ...range(0x0a05, 0x0a0a), - ...range(0x0a0f, 0x0a10), - ...range(0x0a13, 0x0a28), - ...range(0x0a2a, 0x0a30), - ...range(0x0a32, 0x0a33), - ...range(0x0a35, 0x0a36), - ...range(0x0a38, 0x0a39), - ...range(0x0a3e, 0x0a40), - ...range(0x0a59, 0x0a5c), - 0x0a5e, - ...range(0x0a66, 0x0a6f), - ...range(0x0a72, 0x0a74), - 0x0a83, - ...range(0x0a85, 0x0a8b), - 0x0a8d, - ...range(0x0a8f, 0x0a91), - ...range(0x0a93, 0x0aa8), - ...range(0x0aaa, 0x0ab0), - ...range(0x0ab2, 0x0ab3), - ...range(0x0ab5, 0x0ab9), - ...range(0x0abd, 0x0ac0), - 0x0ac9, - ...range(0x0acb, 0x0acc), - 0x0ad0, - 0x0ae0, - ...range(0x0ae6, 0x0aef), - ...range(0x0b02, 0x0b03), - ...range(0x0b05, 0x0b0c), - ...range(0x0b0f, 0x0b10), - ...range(0x0b13, 0x0b28), - ...range(0x0b2a, 0x0b30), - ...range(0x0b32, 0x0b33), - ...range(0x0b36, 0x0b39), - ...range(0x0b3d, 0x0b3e), - 0x0b40, - ...range(0x0b47, 0x0b48), - ...range(0x0b4b, 0x0b4c), - 0x0b57, - ...range(0x0b5c, 0x0b5d), - ...range(0x0b5f, 0x0b61), - ...range(0x0b66, 0x0b70), - 0x0b83, - ...range(0x0b85, 0x0b8a), - ...range(0x0b8e, 0x0b90), - ...range(0x0b92, 0x0b95), - ...range(0x0b99, 0x0b9a), - 0x0b9c, - ...range(0x0b9e, 0x0b9f), - ...range(0x0ba3, 0x0ba4), - ...range(0x0ba8, 0x0baa), - ...range(0x0bae, 0x0bb5), - ...range(0x0bb7, 0x0bb9), - ...range(0x0bbe, 0x0bbf), - ...range(0x0bc1, 0x0bc2), - ...range(0x0bc6, 0x0bc8), - ...range(0x0bca, 0x0bcc), - 0x0bd7, - ...range(0x0be7, 0x0bf2), - ...range(0x0c01, 0x0c03), - ...range(0x0c05, 0x0c0c), - ...range(0x0c0e, 0x0c10), - ...range(0x0c12, 0x0c28), - ...range(0x0c2a, 0x0c33), - ...range(0x0c35, 0x0c39), - ...range(0x0c41, 0x0c44), - ...range(0x0c60, 0x0c61), - ...range(0x0c66, 0x0c6f), - ...range(0x0c82, 0x0c83), - ...range(0x0c85, 0x0c8c), - ...range(0x0c8e, 0x0c90), - ...range(0x0c92, 0x0ca8), - ...range(0x0caa, 0x0cb3), - ...range(0x0cb5, 0x0cb9), - 0x0cbe, - ...range(0x0cc0, 0x0cc4), - ...range(0x0cc7, 0x0cc8), - ...range(0x0cca, 0x0ccb), - ...range(0x0cd5, 0x0cd6), - 0x0cde, - ...range(0x0ce0, 0x0ce1), - ...range(0x0ce6, 0x0cef), - ...range(0x0d02, 0x0d03), - ...range(0x0d05, 0x0d0c), - ...range(0x0d0e, 0x0d10), - ...range(0x0d12, 0x0d28), - ...range(0x0d2a, 0x0d39), - ...range(0x0d3e, 0x0d40), - ...range(0x0d46, 0x0d48), - ...range(0x0d4a, 0x0d4c), - 0x0d57, - ...range(0x0d60, 0x0d61), - ...range(0x0d66, 0x0d6f), - ...range(0x0d82, 0x0d83), - ...range(0x0d85, 0x0d96), - ...range(0x0d9a, 0x0db1), - ...range(0x0db3, 0x0dbb), - 0x0dbd, - ...range(0x0dc0, 0x0dc6), - ...range(0x0dcf, 0x0dd1), - ...range(0x0dd8, 0x0ddf), - ...range(0x0df2, 0x0df4), - ...range(0x0e01, 0x0e30), - ...range(0x0e32, 0x0e33), - ...range(0x0e40, 0x0e46), - ...range(0x0e4f, 0x0e5b), - ...range(0x0e81, 0x0e82), - 0x0e84, - ...range(0x0e87, 0x0e88), - 0x0e8a, - 0x0e8d, - ...range(0x0e94, 0x0e97), - ...range(0x0e99, 0x0e9f), - ...range(0x0ea1, 0x0ea3), - 0x0ea5, - 0x0ea7, - ...range(0x0eaa, 0x0eab), - ...range(0x0ead, 0x0eb0), - ...range(0x0eb2, 0x0eb3), - 0x0ebd, - ...range(0x0ec0, 0x0ec4), - 0x0ec6, - ...range(0x0ed0, 0x0ed9), - ...range(0x0edc, 0x0edd), - ...range(0x0f00, 0x0f17), - ...range(0x0f1a, 0x0f34), - 0x0f36, - 0x0f38, - ...range(0x0f3e, 0x0f47), - ...range(0x0f49, 0x0f6a), - 0x0f7f, - 0x0f85, - ...range(0x0f88, 0x0f8b), - ...range(0x0fbe, 0x0fc5), - ...range(0x0fc7, 0x0fcc), - 0x0fcf, - ...range(0x1000, 0x1021), - ...range(0x1023, 0x1027), - ...range(0x1029, 0x102a), - 0x102c, - 0x1031, - 0x1038, - ...range(0x1040, 0x1057), - ...range(0x10a0, 0x10c5), - ...range(0x10d0, 0x10f8), - 0x10fb, - ...range(0x1100, 0x1159), - ...range(0x115f, 0x11a2), - ...range(0x11a8, 0x11f9), - ...range(0x1200, 0x1206), - ...range(0x1208, 0x1246), - 0x1248, - ...range(0x124a, 0x124d), - ...range(0x1250, 0x1256), - 0x1258, - ...range(0x125a, 0x125d), - ...range(0x1260, 0x1286), - 0x1288, - ...range(0x128a, 0x128d), - ...range(0x1290, 0x12ae), - 0x12b0, - ...range(0x12b2, 0x12b5), - ...range(0x12b8, 0x12be), - 0x12c0, - ...range(0x12c2, 0x12c5), - ...range(0x12c8, 0x12ce), - ...range(0x12d0, 0x12d6), - ...range(0x12d8, 0x12ee), - ...range(0x12f0, 0x130e), - 0x1310, - ...range(0x1312, 0x1315), - ...range(0x1318, 0x131e), - ...range(0x1320, 0x1346), - ...range(0x1348, 0x135a), - ...range(0x1361, 0x137c), - ...range(0x13a0, 0x13f4), - ...range(0x1401, 0x1676), - ...range(0x1681, 0x169a), - ...range(0x16a0, 0x16f0), - ...range(0x1700, 0x170c), - ...range(0x170e, 0x1711), - ...range(0x1720, 0x1731), - ...range(0x1735, 0x1736), - ...range(0x1740, 0x1751), - ...range(0x1760, 0x176c), - ...range(0x176e, 0x1770), - ...range(0x1780, 0x17b6), - ...range(0x17be, 0x17c5), - ...range(0x17c7, 0x17c8), - ...range(0x17d4, 0x17da), - 0x17dc, - ...range(0x17e0, 0x17e9), - ...range(0x1810, 0x1819), - ...range(0x1820, 0x1877), - ...range(0x1880, 0x18a8), - ...range(0x1e00, 0x1e9b), - ...range(0x1ea0, 0x1ef9), - ...range(0x1f00, 0x1f15), - ...range(0x1f18, 0x1f1d), - ...range(0x1f20, 0x1f45), - ...range(0x1f48, 0x1f4d), - ...range(0x1f50, 0x1f57), - 0x1f59, - 0x1f5b, - 0x1f5d, - ...range(0x1f5f, 0x1f7d), - ...range(0x1f80, 0x1fb4), - ...range(0x1fb6, 0x1fbc), - 0x1fbe, - ...range(0x1fc2, 0x1fc4), - ...range(0x1fc6, 0x1fcc), - ...range(0x1fd0, 0x1fd3), - ...range(0x1fd6, 0x1fdb), - ...range(0x1fe0, 0x1fec), - ...range(0x1ff2, 0x1ff4), - ...range(0x1ff6, 0x1ffc), - 0x200e, - 0x2071, - 0x207f, - 0x2102, - 0x2107, - ...range(0x210a, 0x2113), - 0x2115, - ...range(0x2119, 0x211d), - 0x2124, - 0x2126, - 0x2128, - ...range(0x212a, 0x212d), - ...range(0x212f, 0x2131), - ...range(0x2133, 0x2139), - ...range(0x213d, 0x213f), - ...range(0x2145, 0x2149), - ...range(0x2160, 0x2183), - ...range(0x2336, 0x237a), - 0x2395, - ...range(0x249c, 0x24e9), - ...range(0x3005, 0x3007), - ...range(0x3021, 0x3029), - ...range(0x3031, 0x3035), - ...range(0x3038, 0x303c), - ...range(0x3041, 0x3096), - ...range(0x309d, 0x309f), - ...range(0x30a1, 0x30fa), - ...range(0x30fc, 0x30ff), - ...range(0x3105, 0x312c), - ...range(0x3131, 0x318e), - ...range(0x3190, 0x31b7), - ...range(0x31f0, 0x321c), - ...range(0x3220, 0x3243), - ...range(0x3260, 0x327b), - ...range(0x327f, 0x32b0), - ...range(0x32c0, 0x32cb), - ...range(0x32d0, 0x32fe), - ...range(0x3300, 0x3376), - ...range(0x337b, 0x33dd), - ...range(0x33e0, 0x33fe), - ...range(0x3400, 0x4db5), - ...range(0x4e00, 0x9fa5), - ...range(0xa000, 0xa48c), - ...range(0xac00, 0xd7a3), - ...range(0xd800, 0xfa2d), - ...range(0xfa30, 0xfa6a), - ...range(0xfb00, 0xfb06), - ...range(0xfb13, 0xfb17), - ...range(0xff21, 0xff3a), - ...range(0xff41, 0xff5a), - ...range(0xff66, 0xffbe), - ...range(0xffc2, 0xffc7), - ...range(0xffca, 0xffcf), - ...range(0xffd2, 0xffd7), - ...range(0xffda, 0xffdc), - ...range(0x10300, 0x1031e), - ...range(0x10320, 0x10323), - ...range(0x10330, 0x1034a), - ...range(0x10400, 0x10425), - ...range(0x10428, 0x1044d), - ...range(0x1d000, 0x1d0f5), - ...range(0x1d100, 0x1d126), - ...range(0x1d12a, 0x1d166), - ...range(0x1d16a, 0x1d172), - ...range(0x1d183, 0x1d184), - ...range(0x1d18c, 0x1d1a9), - ...range(0x1d1ae, 0x1d1dd), - ...range(0x1d400, 0x1d454), - ...range(0x1d456, 0x1d49c), - ...range(0x1d49e, 0x1d49f), - 0x1d4a2, - ...range(0x1d4a5, 0x1d4a6), - ...range(0x1d4a9, 0x1d4ac), - ...range(0x1d4ae, 0x1d4b9), - 0x1d4bb, - ...range(0x1d4bd, 0x1d4c0), - ...range(0x1d4c2, 0x1d4c3), - ...range(0x1d4c5, 0x1d505), - ...range(0x1d507, 0x1d50a), - ...range(0x1d50d, 0x1d514), - ...range(0x1d516, 0x1d51c), - ...range(0x1d51e, 0x1d539), - ...range(0x1d53b, 0x1d53e), - ...range(0x1d540, 0x1d544), - 0x1d546, - ...range(0x1d54a, 0x1d550), - ...range(0x1d552, 0x1d6a3), - ...range(0x1d6a8, 0x1d7c9), - ...range(0x20000, 0x2a6d6), - ...range(0x2f800, 0x2fa1d), - ...range(0xf0000, 0xffffd), - ...range(0x100000, 0x10fffd), -]); - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -}; diff --git a/reverse_engineering/node_modules/saslprep/lib/memory-code-points.js b/reverse_engineering/node_modules/saslprep/lib/memory-code-points.js deleted file mode 100644 index cb0289c..0000000 --- a/reverse_engineering/node_modules/saslprep/lib/memory-code-points.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const bitfield = require('sparse-bitfield'); - -/* eslint-disable-next-line security/detect-non-literal-fs-filename */ -const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); -let offset = 0; - -/** - * Loads each code points sequence from buffer. - * @returns {bitfield} - */ -function read() { - const size = memory.readUInt32BE(offset); - offset += 4; - - const codepoints = memory.slice(offset, offset + size); - offset += size; - - return bitfield({ buffer: codepoints }); -} - -const unassigned_code_points = read(); -const commonly_mapped_to_nothing = read(); -const non_ASCII_space_characters = read(); -const prohibited_characters = read(); -const bidirectional_r_al = read(); -const bidirectional_l = read(); - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -}; diff --git a/reverse_engineering/node_modules/saslprep/lib/util.js b/reverse_engineering/node_modules/saslprep/lib/util.js deleted file mode 100644 index 506bdc9..0000000 --- a/reverse_engineering/node_modules/saslprep/lib/util.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -/** - * Create an array of numbers. - * @param {number} from - * @param {number} to - * @returns {number[]} - */ -function range(from, to) { - // TODO: make this inlined. - const list = new Array(to - from + 1); - - for (let i = 0; i < list.length; i += 1) { - list[i] = from + i; - } - return list; -} - -module.exports = { - range, -}; diff --git a/reverse_engineering/node_modules/saslprep/package.json b/reverse_engineering/node_modules/saslprep/package.json deleted file mode 100644 index 23c3562..0000000 --- a/reverse_engineering/node_modules/saslprep/package.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "name": "saslprep", - "version": "1.0.3", - "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", - "main": "index.js", - "scripts": { - "test": "npm run lint && npm run unit-test", - "lint": "npx eslint --quiet .", - "unit-test": "npx jest", - "gen-code-points": "node generate-code-points.js > code-points.mem" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/reklatsmasters/saslprep.git" - }, - "keywords": [ - "sasl", - "saslprep", - "stringprep", - "rfc4013", - "4013" - ], - "author": "Dmitry Tsvettsikh ", - "license": "MIT", - "bugs": { - "url": "https://github.com/reklatsmasters/saslprep/issues" - }, - "engines": { - "node": ">=6" - }, - "homepage": "https://github.com/reklatsmasters/saslprep#readme", - "devDependencies": { - "@nodertc/eslint-config": "^0.2.1", - "eslint": "^5.16.0", - "jest": "^23.6.0", - "prettier": "^1.14.3" - }, - "dependencies": { - "sparse-bitfield": "^3.0.3" - }, - "eslintConfig": { - "extends": "@nodertc", - "rules": { - "camelcase": "off", - "no-continue": "off" - }, - "overrides": [ - { - "files": [ - "test/*.js" - ], - "env": { - "jest": true - }, - "rules": { - "require-jsdoc": "off" - } - } - ] - }, - "jest": { - "modulePaths": [ - "" - ], - "testMatch": [ - "**/test/*.js" - ], - "testPathIgnorePatterns": [ - "/node_modules/" - ] - } -} diff --git a/reverse_engineering/node_modules/saslprep/readme.md b/reverse_engineering/node_modules/saslprep/readme.md deleted file mode 100644 index 8ff3d70..0000000 --- a/reverse_engineering/node_modules/saslprep/readme.md +++ /dev/null @@ -1,31 +0,0 @@ -# saslprep -[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) -[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) -[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) -[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) -[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) - -Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) - -### Usage - -```js -const saslprep = require('saslprep') - -saslprep('password\u00AD') // password -saslprep('password\u0007') // Error: prohibited character -``` - -### API - -##### `saslprep(input: String, opts: Options): String` - -Normalize user name or password. - -##### `Options.allowUnassigned: bool` - -A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. - -## License - -MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/reverse_engineering/node_modules/saslprep/test/index.js b/reverse_engineering/node_modules/saslprep/test/index.js deleted file mode 100644 index 80c71af..0000000 --- a/reverse_engineering/node_modules/saslprep/test/index.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -const saslprep = require('..'); - -const chr = String.fromCodePoint; - -test('should work with liatin letters', () => { - const str = 'user'; - expect(saslprep(str)).toEqual(str); -}); - -test('should work be case preserved', () => { - const str = 'USER'; - expect(saslprep(str)).toEqual(str); -}); - -test('should work with high code points (> U+FFFF)', () => { - const str = '\uD83D\uDE00'; - expect(saslprep(str, { allowUnassigned: true })).toEqual(str); -}); - -test('should remove `mapped to nothing` characters', () => { - expect(saslprep('I\u00ADX')).toEqual('IX'); -}); - -test('should replace `Non-ASCII space characters` with space', () => { - expect(saslprep('a\u00A0b')).toEqual('a\u0020b'); -}); - -test('should normalize as NFKC', () => { - expect(saslprep('\u00AA')).toEqual('a'); - expect(saslprep('\u2168')).toEqual('IX'); -}); - -test('should throws when prohibited characters', () => { - // C.2.1 ASCII control characters - expect(() => saslprep('a\u007Fb')).toThrow(); - - // C.2.2 Non-ASCII control characters - expect(() => saslprep('a\u06DDb')).toThrow(); - - // C.3 Private use - expect(() => saslprep('a\uE000b')).toThrow(); - - // C.4 Non-character code points - expect(() => saslprep(`a${chr(0x1fffe)}b`)).toThrow(); - - // C.5 Surrogate codes - expect(() => saslprep('a\uD800b')).toThrow(); - - // C.6 Inappropriate for plain text - expect(() => saslprep('a\uFFF9b')).toThrow(); - - // C.7 Inappropriate for canonical representation - expect(() => saslprep('a\u2FF0b')).toThrow(); - - // C.8 Change display properties or are deprecated - expect(() => saslprep('a\u200Eb')).toThrow(); - - // C.9 Tagging characters - expect(() => saslprep(`a${chr(0xe0001)}b`)).toThrow(); -}); - -test('should not containt RandALCat and LCat bidi', () => { - expect(() => saslprep('a\u06DD\u00AAb')).toThrow(); -}); - -test('RandALCat should be first and last', () => { - expect(() => saslprep('\u0627\u0031\u0628')).not.toThrow(); - expect(() => saslprep('\u0627\u0031')).toThrow(); -}); - -test('should handle unassigned code points', () => { - expect(() => saslprep('a\u0487')).toThrow(); - expect(() => saslprep('a\u0487', { allowUnassigned: true })).not.toThrow(); -}); diff --git a/reverse_engineering/node_modules/saslprep/test/util.js b/reverse_engineering/node_modules/saslprep/test/util.js deleted file mode 100644 index 355db3f..0000000 --- a/reverse_engineering/node_modules/saslprep/test/util.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const { setFlagsFromString } = require('v8'); -const { range } = require('../lib/util'); - -// 984 by default. -setFlagsFromString('--stack_size=500'); - -test('should work', () => { - const list = range(1, 3); - expect(list).toEqual([1, 2, 3]); -}); - -test('should work for large ranges', () => { - expect(() => range(1, 1e6)).not.toThrow(); -}); diff --git a/reverse_engineering/node_modules/semver/CHANGELOG.md b/reverse_engineering/node_modules/semver/CHANGELOG.md deleted file mode 100644 index 66304fd..0000000 --- a/reverse_engineering/node_modules/semver/CHANGELOG.md +++ /dev/null @@ -1,39 +0,0 @@ -# changes log - -## 5.7 - -* Add `minVersion` method - -## 5.6 - -* Move boolean `loose` param to an options object, with - backwards-compatibility protection. -* Add ability to opt out of special prerelease version handling with - the `includePrerelease` option flag. - -## 5.5 - -* Add version coercion capabilities - -## 5.4 - -* Add intersection checking - -## 5.3 - -* Add `minSatisfying` method - -## 5.2 - -* Add `prerelease(v)` that returns prerelease components - -## 5.1 - -* Add Backus-Naur for ranges -* Remove excessively cute inspection methods - -## 5.0 - -* Remove AMD/Browserified build artifacts -* Fix ltr and gtr when using the `*` range -* Fix for range `*` with a prerelease identifier diff --git a/reverse_engineering/node_modules/semver/LICENSE b/reverse_engineering/node_modules/semver/LICENSE deleted file mode 100644 index 19129e3..0000000 --- a/reverse_engineering/node_modules/semver/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/semver/README.md b/reverse_engineering/node_modules/semver/README.md deleted file mode 100644 index f8dfa5a..0000000 --- a/reverse_engineering/node_modules/semver/README.md +++ /dev/null @@ -1,412 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Install - -```bash -npm install --save semver -```` - -## Usage - -As a node module: - -```js -const semver = require('semver') - -semver.valid('1.2.3') // '1.2.3' -semver.valid('a.b.c') // null -semver.clean(' =v1.2.3 ') // '1.2.3' -semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true -semver.gt('1.2.3', '9.8.7') // false -semver.lt('1.2.3', '9.8.7') // true -semver.minVersion('>=1.0.0') // '1.0.0' -semver.valid(semver.coerce('v2')) // '2.0.0' -semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' -``` - -As a command-line utility: - -``` -$ semver -h - -A JavaScript implementation of the https://semver.org/ specification -Copyright Isaac Z. Schlueter - -Usage: semver [options] [ [...]] -Prints valid versions sorted by SemVer precedence - -Options: --r --range - Print versions that match the specified range. - --i --increment [] - Increment a version by the specified level. Level can - be one of: major, minor, patch, premajor, preminor, - prepatch, or prerelease. Default level is 'patch'. - Only one version may be specified. - ---preid - Identifier to be used to prefix premajor, preminor, - prepatch or prerelease version increments. - --l --loose - Interpret versions and ranges loosely - --p --include-prerelease - Always include prerelease versions in range matching - --c --coerce - Coerce a string into SemVer if possible - (does not imply --loose) - -Program exits successfully if any valid version satisfies -all supplied ranges, and prints all satisfying versions. - -If no satisfying versions are found, then exits failure. - -Versions are printed in ascending order, so supplying -multiple versions to the utility will just sort them. -``` - -## Versions - -A "version" is described by the `v2.0.0` specification found at -. - -A leading `"="` or `"v"` character is stripped off and ignored. - -## Ranges - -A `version range` is a set of `comparators` which specify versions -that satisfy the range. - -A `comparator` is composed of an `operator` and a `version`. The set -of primitive `operators` is: - -* `<` Less than -* `<=` Less than or equal to -* `>` Greater than -* `>=` Greater than or equal to -* `=` Equal. If no operator is specified, then equality is assumed, - so this operator is optional, but MAY be included. - -For example, the comparator `>=1.2.7` would match the versions -`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` -or `1.1.0`. - -Comparators can be joined by whitespace to form a `comparator set`, -which is satisfied by the **intersection** of all of the comparators -it includes. - -A range is composed of one or more comparator sets, joined by `||`. A -version matches a range if and only if every comparator in at least -one of the `||`-separated comparator sets is satisfied by the version. - -For example, the range `>=1.2.7 <1.3.0` would match the versions -`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, -or `1.1.0`. - -The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, -`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. - -### Prerelease Tags - -If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then -it will only be allowed to satisfy comparator sets if at least one -comparator with the same `[major, minor, patch]` tuple also has a -prerelease tag. - -For example, the range `>1.2.3-alpha.3` would be allowed to match the -version `1.2.3-alpha.7`, but it would *not* be satisfied by -`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater -than" `1.2.3-alpha.3` according to the SemVer sort rules. The version -range only accepts prerelease tags on the `1.2.3` version. The -version `3.4.5` *would* satisfy the range, because it does not have a -prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. - -The purpose for this behavior is twofold. First, prerelease versions -frequently are updated very quickly, and contain many breaking changes -that are (by the author's design) not yet fit for public consumption. -Therefore, by default, they are excluded from range matching -semantics. - -Second, a user who has opted into using a prerelease version has -clearly indicated the intent to use *that specific* set of -alpha/beta/rc versions. By including a prerelease tag in the range, -the user is indicating that they are aware of the risk. However, it -is still not appropriate to assume that they have opted into taking a -similar risk on the *next* set of prerelease versions. - -Note that this behavior can be suppressed (treating all prerelease -versions as if they were normal versions, for the purpose of range -matching) by setting the `includePrerelease` flag on the options -object to any -[functions](https://github.com/npm/node-semver#functions) that do -range matching. - -#### Prerelease Identifiers - -The method `.inc` takes an additional `identifier` string argument that -will append the value of the string as a prerelease identifier: - -```javascript -semver.inc('1.2.3', 'prerelease', 'beta') -// '1.2.4-beta.0' -``` - -command-line example: - -```bash -$ semver 1.2.3 -i prerelease --preid beta -1.2.4-beta.0 -``` - -Which then can be used to increment further: - -```bash -$ semver 1.2.4-beta.0 -i prerelease -1.2.4-beta.1 -``` - -### Advanced Range Syntax - -Advanced range syntax desugars to primitive comparators in -deterministic ways. - -Advanced ranges may be combined in the same way as primitive -comparators using white space or `||`. - -#### Hyphen Ranges `X.Y.Z - A.B.C` - -Specifies an inclusive set. - -* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` - -If a partial version is provided as the first version in the inclusive -range, then the missing pieces are replaced with zeroes. - -* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` - -If a partial version is provided as the second version in the -inclusive range, then all versions that start with the supplied parts -of the tuple are accepted, but nothing that would be greater than the -provided tuple parts. - -* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` -* `1.2.3 - 2` := `>=1.2.3 <3.0.0` - -#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` - -Any of `X`, `x`, or `*` may be used to "stand in" for one of the -numeric values in the `[major, minor, patch]` tuple. - -* `*` := `>=0.0.0` (Any version satisfies) -* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) -* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) - -A partial version range is treated as an X-Range, so the special -character is in fact optional. - -* `""` (empty string) := `*` := `>=0.0.0` -* `1` := `1.x.x` := `>=1.0.0 <2.0.0` -* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` - -#### Tilde Ranges `~1.2.3` `~1.2` `~1` - -Allows patch-level changes if a minor version is specified on the -comparator. Allows minor-level changes if not. - -* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` -* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) -* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) -* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` -* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) -* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) -* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. - -#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` - -Allows changes that do not modify the left-most non-zero digit in the -`[major, minor, patch]` tuple. In other words, this allows patch and -minor updates for versions `1.0.0` and above, patch updates for -versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. - -Many authors treat a `0.x` version as if the `x` were the major -"breaking-change" indicator. - -Caret ranges are ideal when an author may make breaking changes -between `0.2.4` and `0.3.0` releases, which is a common practice. -However, it presumes that there will *not* be breaking changes between -`0.2.4` and `0.2.5`. It allows for changes that are presumed to be -additive (but non-breaking), according to commonly observed practices. - -* `^1.2.3` := `>=1.2.3 <2.0.0` -* `^0.2.3` := `>=0.2.3 <0.3.0` -* `^0.0.3` := `>=0.0.3 <0.0.4` -* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. -* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the - `0.0.3` version *only* will be allowed, if they are greater than or - equal to `beta`. So, `0.0.3-pr.2` would be allowed. - -When parsing caret ranges, a missing `patch` value desugars to the -number `0`, but will allow flexibility within that value, even if the -major and minor versions are both `0`. - -* `^1.2.x` := `>=1.2.0 <2.0.0` -* `^0.0.x` := `>=0.0.0 <0.1.0` -* `^0.0` := `>=0.0.0 <0.1.0` - -A missing `minor` and `patch` values will desugar to zero, but also -allow flexibility within those values, even if the major version is -zero. - -* `^1.x` := `>=1.0.0 <2.0.0` -* `^0.x` := `>=0.0.0 <1.0.0` - -### Range Grammar - -Putting all this together, here is a Backus-Naur grammar for ranges, -for the benefit of parser authors: - -```bnf -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ -``` - -## Functions - -All methods and classes take a final `options` object argument. All -options in this object are `false` by default. The options supported -are: - -- `loose` Be more forgiving about not-quite-valid semver strings. - (Any resulting output will always be 100% strict compliant, of - course.) For backwards compatibility reasons, if the `options` - argument is a boolean value instead of an object, it is interpreted - to be the `loose` param. -- `includePrerelease` Set to suppress the [default - behavior](https://github.com/npm/node-semver#prerelease-tags) of - excluding prerelease tagged versions from ranges unless they are - explicitly opted into. - -Strict-mode Comparators and Ranges will be strict about the SemVer -strings that they parse. - -* `valid(v)`: Return the parsed version, or null if it's not valid. -* `inc(v, release)`: Return the version incremented by the release - type (`major`, `premajor`, `minor`, `preminor`, `patch`, - `prepatch`, or `prerelease`), or null if it's not valid - * `premajor` in one call will bump the version up to the next major - version and down to a prerelease of that major version. - `preminor`, and `prepatch` work the same way. - * If called from a non-prerelease version, the `prerelease` will work the - same as `prepatch`. It increments the patch version, then makes a - prerelease. If the input version is already a prerelease it simply - increments it. -* `prerelease(v)`: Returns an array of prerelease components, or null - if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` -* `major(v)`: Return the major version number. -* `minor(v)`: Return the minor version number. -* `patch(v)`: Return the patch version number. -* `intersects(r1, r2, loose)`: Return true if the two supplied ranges - or comparators intersect. -* `parse(v)`: Attempt to parse a string as a semantic version, returning either - a `SemVer` object or `null`. - -### Comparison - -* `gt(v1, v2)`: `v1 > v2` -* `gte(v1, v2)`: `v1 >= v2` -* `lt(v1, v2)`: `v1 < v2` -* `lte(v1, v2)`: `v1 <= v2` -* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, - even if they're not the exact same string. You already know how to - compare strings. -* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. -* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call - the corresponding function above. `"==="` and `"!=="` do simple - string comparison, but are included for completeness. Throws if an - invalid comparison string is provided. -* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if - `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. -* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions - in descending order when passed to `Array.sort()`. -* `diff(v1, v2)`: Returns difference between two versions by the release type - (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), - or null if the versions are the same. - -### Comparators - -* `intersects(comparator)`: Return true if the comparators intersect - -### Ranges - -* `validRange(range)`: Return the valid range or null if it's not valid -* `satisfies(version, range)`: Return true if the version satisfies the - range. -* `maxSatisfying(versions, range)`: Return the highest version in the list - that satisfies the range, or `null` if none of them do. -* `minSatisfying(versions, range)`: Return the lowest version in the list - that satisfies the range, or `null` if none of them do. -* `minVersion(range)`: Return the lowest version that can possibly match - the given range. -* `gtr(version, range)`: Return `true` if version is greater than all the - versions possible in the range. -* `ltr(version, range)`: Return `true` if version is less than all the - versions possible in the range. -* `outside(version, range, hilo)`: Return true if the version is outside - the bounds of the range in either the high or low direction. The - `hilo` argument must be either the string `'>'` or `'<'`. (This is - the function called by `gtr` and `ltr`.) -* `intersects(range)`: Return true if any of the ranges comparators intersect - -Note that, since ranges may be non-contiguous, a version might not be -greater than a range, less than a range, *or* satisfy a range! For -example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` -until `2.0.0`, so the version `1.2.10` would not be greater than the -range (because `2.0.1` satisfies, which is higher), nor less than the -range (since `1.2.8` satisfies, which is lower), and it also does not -satisfy the range. - -If you want to know if a version satisfies or does not satisfy a -range, use the `satisfies(version, range)` function. - -### Coercion - -* `coerce(version)`: Coerces a string to semver if possible - -This aims to provide a very forgiving translation of a non-semver string to -semver. It looks for the first digit in a string, and consumes all -remaining characters which satisfy at least a partial semver (e.g., `1`, -`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer -versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All -surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes -`3.4.0`). Only text which lacks digits will fail coercion (`version one` -is not valid). The maximum length for any semver component considered for -coercion is 16 characters; longer components will be ignored -(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any -semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value -components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/reverse_engineering/node_modules/semver/bin/semver b/reverse_engineering/node_modules/semver/bin/semver deleted file mode 100755 index 801e77f..0000000 --- a/reverse_engineering/node_modules/semver/bin/semver +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - -var versions = [] - -var range = [] - -var inc = null - -var version = require('../package.json').version - -var loose = false - -var includePrerelease = false - -var coerce = false - -var identifier - -var semver = require('../semver') - -var reverse = false - -var options = {} - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a = argv.shift() - var indexOfEqualSign = a.indexOf('=') - if (indexOfEqualSign !== -1) { - a = a.slice(0, indexOfEqualSign) - argv.unshift(a.slice(indexOfEqualSign + 1)) - } - switch (a) { - case '-rv': case '-rev': case '--rev': case '--reverse': - reverse = true - break - case '-l': case '--loose': - loose = true - break - case '-p': case '--include-prerelease': - includePrerelease = true - break - case '-v': case '--version': - versions.push(argv.shift()) - break - case '-i': case '--inc': case '--increment': - switch (argv[0]) { - case 'major': case 'minor': case 'patch': case 'prerelease': - case 'premajor': case 'preminor': case 'prepatch': - inc = argv.shift() - break - default: - inc = 'patch' - break - } - break - case '--preid': - identifier = argv.shift() - break - case '-r': case '--range': - range.push(argv.shift()) - break - case '-c': case '--coerce': - coerce = true - break - case '-h': case '--help': case '-?': - return help() - default: - versions.push(a) - break - } - } - - var options = { loose: loose, includePrerelease: includePrerelease } - - versions = versions.map(function (v) { - return coerce ? (semver.coerce(v) || { version: v }).version : v - }).filter(function (v) { - return semver.valid(v) - }) - if (!versions.length) return fail() - if (inc && (versions.length !== 1 || range.length)) { return failInc() } - - for (var i = 0, l = range.length; i < l; i++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i], options) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function failInc () { - console.error('--inc can only be used on a single version with no range') - fail() -} - -function fail () { process.exit(1) } - -function success () { - var compare = reverse ? 'rcompare' : 'compare' - versions.sort(function (a, b) { - return semver[compare](a, b, options) - }).map(function (v) { - return semver.clean(v, options) - }).map(function (v) { - return inc ? semver.inc(v, inc, options, identifier) : v - }).forEach(function (v, i, _) { console.log(v) }) -} - -function help () { - console.log(['SemVer ' + version, - '', - 'A JavaScript implementation of the https://semver.org/ specification', - 'Copyright Isaac Z. Schlueter', - '', - 'Usage: semver [options] [ [...]]', - 'Prints valid versions sorted by SemVer precedence', - '', - 'Options:', - '-r --range ', - ' Print versions that match the specified range.', - '', - '-i --increment []', - ' Increment a version by the specified level. Level can', - ' be one of: major, minor, patch, premajor, preminor,', - " prepatch, or prerelease. Default level is 'patch'.", - ' Only one version may be specified.', - '', - '--preid ', - ' Identifier to be used to prefix premajor, preminor,', - ' prepatch or prerelease version increments.', - '', - '-l --loose', - ' Interpret versions and ranges loosely', - '', - '-p --include-prerelease', - ' Always include prerelease versions in range matching', - '', - '-c --coerce', - ' Coerce a string into SemVer if possible', - ' (does not imply --loose)', - '', - 'Program exits successfully if any valid version satisfies', - 'all supplied ranges, and prints all satisfying versions.', - '', - 'If no satisfying versions are found, then exits failure.', - '', - 'Versions are printed in ascending order, so supplying', - 'multiple versions to the utility will just sort them.' - ].join('\n')) -} diff --git a/reverse_engineering/node_modules/semver/package.json b/reverse_engineering/node_modules/semver/package.json deleted file mode 100644 index 69d2db1..0000000 --- a/reverse_engineering/node_modules/semver/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "semver", - "version": "5.7.1", - "description": "The semantic version parser used by npm.", - "main": "semver.js", - "scripts": { - "test": "tap", - "preversion": "npm test", - "postversion": "npm publish", - "postpublish": "git push origin --all; git push origin --tags" - }, - "devDependencies": { - "tap": "^13.0.0-rc.18" - }, - "license": "ISC", - "repository": "https://github.com/npm/node-semver", - "bin": { - "semver": "./bin/semver" - }, - "files": [ - "bin", - "range.bnf", - "semver.js" - ], - "tap": { - "check-coverage": true - } -} diff --git a/reverse_engineering/node_modules/semver/range.bnf b/reverse_engineering/node_modules/semver/range.bnf deleted file mode 100644 index d4c6ae0..0000000 --- a/reverse_engineering/node_modules/semver/range.bnf +++ /dev/null @@ -1,16 +0,0 @@ -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | [1-9] ( [0-9] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ diff --git a/reverse_engineering/node_modules/semver/semver.js b/reverse_engineering/node_modules/semver/semver.js deleted file mode 100644 index d315d5d..0000000 --- a/reverse_engineering/node_modules/semver/semver.js +++ /dev/null @@ -1,1483 +0,0 @@ -exports = module.exports = SemVer - -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' - -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' - -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' - -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' - -src[FULL] = '^' + FULLPLAIN + '$' - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' - -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' - -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' - -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' - -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' - -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' - -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' - -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} - -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} - -exports.SemVer = SemVer - -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version -} - -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return this.compareMain(other) || this.comparePre(other) -} - -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } - - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} - -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} - -exports.compareIdentifiers = compareIdentifiers - -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} - -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} - -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} - -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} - -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} - -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} - -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} - -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} - -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} - -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} - -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} - -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} - -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError('Invalid operator: ' + op) - } -} - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) -} - -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} - -Comparator.prototype.toString = function () { - return this.value -} - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY) { - return true - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - return cmp(version, this.operator, this.semver, this.options) -} - -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - var rangeTmp - - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} - -Range.prototype.toString = function () { - return this.range -} - -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - - return set -} - -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} - -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} - -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} - -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - - return (from + ' ' + to).trim() -} - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} - -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} - -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} - -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} - -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} - -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} - -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) - - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - var high = null - var low = null - - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} - -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} - -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - var match = version.match(re[COERCE]) - - if (match == null) { - return null - } - - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) -} diff --git a/reverse_engineering/node_modules/set-blocking/CHANGELOG.md b/reverse_engineering/node_modules/set-blocking/CHANGELOG.md deleted file mode 100644 index 03bf591..0000000 --- a/reverse_engineering/node_modules/set-blocking/CHANGELOG.md +++ /dev/null @@ -1,26 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -# [2.0.0](https://github.com/yargs/set-blocking/compare/v1.0.0...v2.0.0) (2016-05-17) - - -### Features - -* add an isTTY check ([#3](https://github.com/yargs/set-blocking/issues/3)) ([66ce277](https://github.com/yargs/set-blocking/commit/66ce277)) - - -### BREAKING CHANGES - -* stdio/stderr will not be set to blocking if isTTY === false - - - - -# 1.0.0 (2016-05-14) - - -### Features - -* implemented shim for stream._handle.setBlocking ([6bde0c0](https://github.com/yargs/set-blocking/commit/6bde0c0)) diff --git a/reverse_engineering/node_modules/set-blocking/LICENSE.txt b/reverse_engineering/node_modules/set-blocking/LICENSE.txt deleted file mode 100644 index 836440b..0000000 --- a/reverse_engineering/node_modules/set-blocking/LICENSE.txt +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) 2016, Contributors - -Permission to use, copy, modify, and/or distribute this software -for any purpose with or without fee is hereby granted, provided -that the above copyright notice and this permission notice -appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE -LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/set-blocking/README.md b/reverse_engineering/node_modules/set-blocking/README.md deleted file mode 100644 index e93b420..0000000 --- a/reverse_engineering/node_modules/set-blocking/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# set-blocking - -[![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) -[![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) -[![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) -[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) - -set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. - -```js -const setBlocking = require('set-blocking') -setBlocking(true) -console.log(someLargeStringToOutput) -``` - -## Historical Context/Word of Warning - -This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on -newer versions of Node.js (`0.12+`), truncating terminal output. - -You should be mindful of the side-effects caused by using `set-blocking`: - -* if your module sets blocking to `true`, it will effect other modules - consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call - `setBlocking(true)` once we already know we are about to call `process.exit(code)`. -* this patch will not apply to subprocesses spawned with `isTTY = true`, this is - the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). - -## License - -ISC diff --git a/reverse_engineering/node_modules/set-blocking/index.js b/reverse_engineering/node_modules/set-blocking/index.js deleted file mode 100644 index 6f78774..0000000 --- a/reverse_engineering/node_modules/set-blocking/index.js +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = function (blocking) { - [process.stdout, process.stderr].forEach(function (stream) { - if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { - stream._handle.setBlocking(blocking) - } - }) -} diff --git a/reverse_engineering/node_modules/set-blocking/package.json b/reverse_engineering/node_modules/set-blocking/package.json deleted file mode 100644 index c082db7..0000000 --- a/reverse_engineering/node_modules/set-blocking/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "set-blocking", - "version": "2.0.0", - "description": "set blocking stdio and stderr ensuring that terminal output does not truncate", - "main": "index.js", - "scripts": { - "pretest": "standard", - "test": "nyc mocha ./test/*.js", - "coverage": "nyc report --reporter=text-lcov | coveralls", - "version": "standard-version" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/yargs/set-blocking.git" - }, - "keywords": [ - "flush", - "terminal", - "blocking", - "shim", - "stdio", - "stderr" - ], - "author": "Ben Coe ", - "license": "ISC", - "bugs": { - "url": "https://github.com/yargs/set-blocking/issues" - }, - "homepage": "https://github.com/yargs/set-blocking#readme", - "devDependencies": { - "chai": "^3.5.0", - "coveralls": "^2.11.9", - "mocha": "^2.4.5", - "nyc": "^6.4.4", - "standard": "^7.0.1", - "standard-version": "^2.2.1" - }, - "files": [ - "index.js", - "LICENSE.txt" - ] -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/sparse-bitfield/.npmignore b/reverse_engineering/node_modules/sparse-bitfield/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/reverse_engineering/node_modules/sparse-bitfield/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/reverse_engineering/node_modules/sparse-bitfield/.travis.yml b/reverse_engineering/node_modules/sparse-bitfield/.travis.yml deleted file mode 100644 index c042821..0000000 --- a/reverse_engineering/node_modules/sparse-bitfield/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - '0.10' - - '0.12' - - '4.0' - - '5.0' diff --git a/reverse_engineering/node_modules/sparse-bitfield/LICENSE b/reverse_engineering/node_modules/sparse-bitfield/LICENSE deleted file mode 100644 index bae9da7..0000000 --- a/reverse_engineering/node_modules/sparse-bitfield/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/sparse-bitfield/README.md b/reverse_engineering/node_modules/sparse-bitfield/README.md deleted file mode 100644 index 7b6b8f9..0000000 --- a/reverse_engineering/node_modules/sparse-bitfield/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# sparse-bitfield - -Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields -without allocating a massive buffer. If you want to simple implementation of a flat bitfield -see the [bitfield](https://github.com/fb55/bitfield) module. - -This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. - -``` -npm install sparse-bitfield -``` - -[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) - -## Usage - -``` js -var bitfield = require('sparse-bitfield') -var bits = bitfield() - -bits.set(0, true) // set first bit -bits.set(1, true) // set second bit -bits.set(1000000000000, true) // set the 1.000.000.000.000th bit -``` - -Running the above example will allocate two 1kb buffers internally. -Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. - -## API - -#### `var bits = bitfield([options])` - -Create a new bitfield. Options include - -``` js -{ - pageSize: 1024, // how big should the partial buffers be - buffer: anExistingBitfield, - trackUpdates: false // track when pages are being updated in the pager -} -``` - -#### `bits.set(index, value)` - -Set a bit to true or false. - -#### `bits.get(index)` - -Get the value of a bit. - -#### `bits.pages` - -A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. -If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. - -#### `var buffer = bits.toBuffer()` - -Get a single buffer representing the entire bitfield. - -## License - -MIT diff --git a/reverse_engineering/node_modules/sparse-bitfield/index.js b/reverse_engineering/node_modules/sparse-bitfield/index.js deleted file mode 100644 index ff458c9..0000000 --- a/reverse_engineering/node_modules/sparse-bitfield/index.js +++ /dev/null @@ -1,95 +0,0 @@ -var pager = require('memory-pager') - -module.exports = Bitfield - -function Bitfield (opts) { - if (!(this instanceof Bitfield)) return new Bitfield(opts) - if (!opts) opts = {} - if (Buffer.isBuffer(opts)) opts = {buffer: opts} - - this.pageOffset = opts.pageOffset || 0 - this.pageSize = opts.pageSize || 1024 - this.pages = opts.pages || pager(this.pageSize) - - this.byteLength = this.pages.length * this.pageSize - this.length = 8 * this.byteLength - - if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') - - this._trackUpdates = !!opts.trackUpdates - this._pageMask = this.pageSize - 1 - - if (opts.buffer) { - for (var i = 0; i < opts.buffer.length; i += this.pageSize) { - this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) - } - this.byteLength = opts.buffer.length - this.length = 8 * this.byteLength - } -} - -Bitfield.prototype.get = function (i) { - var o = i & 7 - var j = (i - o) / 8 - - return !!(this.getByte(j) & (128 >> o)) -} - -Bitfield.prototype.getByte = function (i) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, true) - - return page ? page.buffer[o + this.pageOffset] : 0 -} - -Bitfield.prototype.set = function (i, v) { - var o = i & 7 - var j = (i - o) / 8 - var b = this.getByte(j) - - return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) -} - -Bitfield.prototype.toBuffer = function () { - var all = alloc(this.pages.length * this.pageSize) - - for (var i = 0; i < this.pages.length; i++) { - var next = this.pages.get(i, true) - var allOffset = i * this.pageSize - if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) - } - - return all -} - -Bitfield.prototype.setByte = function (i, b) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, false) - - o += this.pageOffset - - if (page.buffer[o] === b) return false - page.buffer[o] = b - - if (i >= this.byteLength) { - this.byteLength = i + 1 - this.length = this.byteLength * 8 - } - - if (this._trackUpdates) this.pages.updated(page) - - return true -} - -function alloc (n) { - if (Buffer.alloc) return Buffer.alloc(n) - var b = new Buffer(n) - b.fill(0) - return b -} - -function powerOfTwo (x) { - return !(x & (x - 1)) -} diff --git a/reverse_engineering/node_modules/sparse-bitfield/package.json b/reverse_engineering/node_modules/sparse-bitfield/package.json deleted file mode 100644 index 092a23f..0000000 --- a/reverse_engineering/node_modules/sparse-bitfield/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "sparse-bitfield", - "version": "3.0.3", - "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", - "main": "index.js", - "dependencies": { - "memory-pager": "^1.0.2" - }, - "devDependencies": { - "buffer-alloc": "^1.1.0", - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/mafintosh/sparse-bitfield.git" - }, - "author": "Mathias Buus (@mafintosh)", - "license": "MIT", - "bugs": { - "url": "https://github.com/mafintosh/sparse-bitfield/issues" - }, - "homepage": "https://github.com/mafintosh/sparse-bitfield" -} diff --git a/reverse_engineering/node_modules/sparse-bitfield/test.js b/reverse_engineering/node_modules/sparse-bitfield/test.js deleted file mode 100644 index ae42ef4..0000000 --- a/reverse_engineering/node_modules/sparse-bitfield/test.js +++ /dev/null @@ -1,79 +0,0 @@ -var alloc = require('buffer-alloc') -var tape = require('tape') -var bitfield = require('./') - -tape('set and get', function (t) { - var bits = bitfield() - - t.same(bits.get(0), false, 'first bit is false') - bits.set(0, true) - t.same(bits.get(0), true, 'first bit is true') - t.same(bits.get(1), false, 'second bit is false') - bits.set(0, false) - t.same(bits.get(0), false, 'first bit is reset') - t.end() -}) - -tape('set large and get', function (t) { - var bits = bitfield() - - t.same(bits.get(9999999999999), false, 'large bit is false') - bits.set(9999999999999, true) - t.same(bits.get(9999999999999), true, 'large bit is true') - t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') - bits.set(9999999999999, false) - t.same(bits.get(9999999999999), false, 'large bit is reset') - t.end() -}) - -tape('get and set buffer', function (t) { - var bits = bitfield({trackUpdates: true}) - - t.same(bits.pages.get(0, true), undefined) - t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) - bits.set(9999999999999, true) - - var bits2 = bitfield() - var upd = bits.pages.lastUpdate() - bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) - t.same(bits2.get(9999999999999), true, 'bit is set') - t.end() -}) - -tape('toBuffer', function (t) { - var bits = bitfield() - - t.same(bits.toBuffer(), alloc(0)) - - bits.set(0, true) - - t.same(bits.toBuffer(), bits.pages.get(0).buffer) - - bits.set(9000, true) - - t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) - t.end() -}) - -tape('pass in buffer', function (t) { - var bits = bitfield() - - bits.set(0, true) - bits.set(9000, true) - - var clone = bitfield(bits.toBuffer()) - - t.same(clone.get(0), true) - t.same(clone.get(9000), true) - t.end() -}) - -tape('set small buffer', function (t) { - var buf = alloc(1) - buf[0] = 255 - var bits = bitfield(buf) - - t.same(bits.get(0), true) - t.same(bits.pages.get(0).buffer.length, bits.pageSize) - t.end() -}) diff --git a/reverse_engineering/node_modules/split/.npmignore b/reverse_engineering/node_modules/split/.npmignore deleted file mode 100644 index 13abef4..0000000 --- a/reverse_engineering/node_modules/split/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -node_modules/* -npm_debug.log diff --git a/reverse_engineering/node_modules/split/.travis.yml b/reverse_engineering/node_modules/split/.travis.yml deleted file mode 100644 index 6e5919d..0000000 --- a/reverse_engineering/node_modules/split/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - "0.10" diff --git a/reverse_engineering/node_modules/split/LICENCE b/reverse_engineering/node_modules/split/LICENCE deleted file mode 100644 index 171dd97..0000000 --- a/reverse_engineering/node_modules/split/LICENCE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2011 Dominic Tarr - -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom -the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/split/examples/pretty.js b/reverse_engineering/node_modules/split/examples/pretty.js deleted file mode 100644 index 2e89131..0000000 --- a/reverse_engineering/node_modules/split/examples/pretty.js +++ /dev/null @@ -1,26 +0,0 @@ - -var inspect = require('util').inspect -var es = require('event-stream') //load event-stream -var split = require('../') - -if(!module.parent) { - es.pipe( //pipe joins streams together - process.openStdin(), //open stdin - split(), //split stream to break on newlines - es.map(function (data, callback) {//turn this async function into a stream - var j - try { - j = JSON.parse(data) //try to parse input into json - } catch (err) { - return callback(null, data) //if it fails just pass it anyway - } - callback(null, inspect(j)) //render it nicely - }), - process.stdout // pipe it to stdout ! - ) - } - -// run this -// -// curl -sS registry.npmjs.org/event-stream | node pretty.js -// diff --git a/reverse_engineering/node_modules/split/index.js b/reverse_engineering/node_modules/split/index.js deleted file mode 100644 index d2bbe5d..0000000 --- a/reverse_engineering/node_modules/split/index.js +++ /dev/null @@ -1,63 +0,0 @@ -//filter will reemit the data if cb(err,pass) pass is truthy - -// reduce is more tricky -// maybe we want to group the reductions or emit progress updates occasionally -// the most basic reduce just emits one 'data' event after it has recieved 'end' - - -var through = require('through') -var Decoder = require('string_decoder').StringDecoder - -module.exports = split - -//TODO pass in a function to map across the lines. - -function split (matcher, mapper, options) { - var decoder = new Decoder() - var soFar = '' - var maxLength = options && options.maxLength; - var trailing = options && options.trailing === false ? false : true - if('function' === typeof matcher) - mapper = matcher, matcher = null - if (!matcher) - matcher = /\r?\n/ - - function emit(stream, piece) { - if(mapper) { - try { - piece = mapper(piece) - } - catch (err) { - return stream.emit('error', err) - } - if('undefined' !== typeof piece) - stream.queue(piece) - } - else - stream.queue(piece) - } - - function next (stream, buffer) { - var pieces = ((soFar != null ? soFar : '') + buffer).split(matcher) - soFar = pieces.pop() - - if (maxLength && soFar.length > maxLength) - return stream.emit('error', new Error('maximum buffer reached')) - - for (var i = 0; i < pieces.length; i++) { - var piece = pieces[i] - emit(stream, piece) - } - } - - return through(function (b) { - next(this, decoder.write(b)) - }, - function () { - if(decoder.end) - next(this, decoder.end()) - if(trailing && soFar != null) - emit(this, soFar) - this.queue(null) - }) -} diff --git a/reverse_engineering/node_modules/split/package.json b/reverse_engineering/node_modules/split/package.json deleted file mode 100644 index 7540698..0000000 --- a/reverse_engineering/node_modules/split/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "split", - "version": "1.0.1", - "license": "MIT", - "description": "split a Text Stream into a Line Stream", - "homepage": "http://github.com/dominictarr/split", - "repository": { - "type": "git", - "url": "git://github.com/dominictarr/split.git" - }, - "dependencies": { - "through": "2" - }, - "devDependencies": { - "asynct": "*", - "event-stream": "~3.0.2", - "it-is": "1", - "stream-spec": "~0.2", - "ubelt": "~2.9", - "string-to-stream": "~1.0.0" - }, - "scripts": { - "test": "asynct test/" - }, - "author": "Dominic Tarr (http://bit.ly/dominictarr)", - "optionalDependencies": {}, - "engines": { - "node": "*" - } -} diff --git a/reverse_engineering/node_modules/split/readme.markdown b/reverse_engineering/node_modules/split/readme.markdown deleted file mode 100644 index c2e527d..0000000 --- a/reverse_engineering/node_modules/split/readme.markdown +++ /dev/null @@ -1,72 +0,0 @@ -# Split (matcher) - -[![build status](https://secure.travis-ci.org/dominictarr/split.png)](http://travis-ci.org/dominictarr/split) - -Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` - -Example, read every line in a file ... - -``` js - fs.createReadStream(file) - .pipe(split()) - .on('data', function (line) { - //each chunk now is a separate line! - }) - -``` - -`split` takes the same arguments as `string.split` except it defaults to '/\r?\n/' instead of ',', and the optional `limit` parameter is ignored. -[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split) - -`split` takes an optional options object on its third argument. - -``` js - split(matcher, mapper, options) -``` - -Valid options: - -* maxLength - The maximum buffer length without seeing a newline or `matcher`, - if a single line exceeds this, the split stream will emit an error. - -``` js - split(JSON.parse, null, { maxLength: 2}) -``` - -* trailing - By default the last buffer not delimited by a newline or `matcher` will be emitted. To prevent this set `options.trailing` to `false`. - -``` js - split(JSON.parse, null, { trailing: false }) -``` - -## keep matched splitter - -As with `String#split`, if you split by a regular expression with a matching group, -the matches will be retained in the collection. - -``` -stdin -.pipe(split(/(\r?\n)/)) -... //lines + separators. -``` - - -# NDJ - Newline Delimited Json - -`split` accepts a function which transforms each line. - -``` js -fs.createReadStream(file) - .pipe(split(JSON.parse)) - .on('data', function (obj) { - //each chunk now is a a js object - }) - .on('error', function (err) { - //syntax errors will land here - //note, this ends the stream. - }) -``` - -# License - -MIT diff --git a/reverse_engineering/node_modules/split/test/options.asynct.js b/reverse_engineering/node_modules/split/test/options.asynct.js deleted file mode 100644 index 3f137d9..0000000 --- a/reverse_engineering/node_modules/split/test/options.asynct.js +++ /dev/null @@ -1,46 +0,0 @@ -var it = require('it-is').style('colour') - , split = require('..') - -exports ['maximum buffer limit'] = function (test) { - var s = split(JSON.parse, null, { - maxLength: 2 - }) - , caughtError = false - , rows = [] - - s.on('error', function (err) { - caughtError = true - }) - - s.on('data', function (row) { rows.push(row) }) - - s.write('{"a":1}\n{"') - s.write('{ "') - it(caughtError).equal(true) - - s.end() - test.done() -} - -exports ['ignore trailing buffers'] = function (test) { - var s = split(JSON.parse, null, { - trailing: false - }) - , caughtError = false - , rows = [] - - s.on('error', function (err) { - caughtError = true - }) - - s.on('data', function (row) { rows.push(row) }) - - s.write('{"a":1}\n{"') - s.write('{ "') - s.end() - - it(caughtError).equal(false) - it(rows).deepEqual([ { a: 1 } ]) - - test.done() -} diff --git a/reverse_engineering/node_modules/split/test/partitioned_unicode.js b/reverse_engineering/node_modules/split/test/partitioned_unicode.js deleted file mode 100644 index aff3d5d..0000000 --- a/reverse_engineering/node_modules/split/test/partitioned_unicode.js +++ /dev/null @@ -1,34 +0,0 @@ -var it = require('it-is').style('colour') - , split = require('..') - -exports ['split data with partitioned unicode character'] = function (test) { - var s = split(/,/g) - , caughtError = false - , rows = [] - - s.on('error', function (err) { - caughtError = true - }) - - s.on('data', function (row) { rows.push(row) }) - - var x = 'テスト試験今日とても,よい天気で' - unicodeData = new Buffer(x); - - // partition of 日 - piece1 = unicodeData.slice(0, 20); - piece2 = unicodeData.slice(20, unicodeData.length); - - s.write(piece1); - s.write(piece2); - - s.end() - - it(caughtError).equal(false) - - it(rows).deepEqual(['テスト試験今日とても', 'よい天気で']); - - it(rows).deepEqual(x.split(',')) - - test.done() -} diff --git a/reverse_engineering/node_modules/split/test/split.asynct.js b/reverse_engineering/node_modules/split/test/split.asynct.js deleted file mode 100644 index a586e12..0000000 --- a/reverse_engineering/node_modules/split/test/split.asynct.js +++ /dev/null @@ -1,137 +0,0 @@ -var es = require('event-stream') - , it = require('it-is').style('colour') - , d = require('ubelt') - , split = require('..') - , join = require('path').join - , fs = require('fs') - , Stream = require('stream').Stream - , Readable = require('stream').Readable - , spec = require('stream-spec') - , through = require('through') - , stringStream = require('string-to-stream') - -exports ['split() works like String#split'] = function (test) { - var readme = join(__filename) - , expected = fs.readFileSync(readme, 'utf-8').split('\n') - , cs = split() - , actual = [] - , ended = false - , x = spec(cs).through() - - var a = new Stream () - - a.write = function (l) { - actual.push(l.trim()) - } - a.end = function () { - - ended = true - expected.forEach(function (v,k) { - //String.split will append an empty string '' - //if the string ends in a split pattern. - //es.split doesn't which was breaking this test. - //clearly, appending the empty string is correct. - //tests are passing though. which is the current job. - if(v) - it(actual[k]).like(v) - }) - //give the stream time to close - process.nextTick(function () { - test.done() - x.validate() - }) - } - a.writable = true - - fs.createReadStream(readme, {flags: 'r'}).pipe(cs) - cs.pipe(a) - -} - -exports ['split() takes mapper function'] = function (test) { - var readme = join(__filename) - , expected = fs.readFileSync(readme, 'utf-8').split('\n') - , cs = split(function (line) { return line.toUpperCase() }) - , actual = [] - , ended = false - , x = spec(cs).through() - - var a = new Stream () - - a.write = function (l) { - actual.push(l.trim()) - } - a.end = function () { - - ended = true - expected.forEach(function (v,k) { - //String.split will append an empty string '' - //if the string ends in a split pattern. - //es.split doesn't which was breaking this test. - //clearly, appending the empty string is correct. - //tests are passing though. which is the current job. - if(v) - it(actual[k]).equal(v.trim().toUpperCase()) - }) - //give the stream time to close - process.nextTick(function () { - test.done() - x.validate() - }) - } - a.writable = true - - fs.createReadStream(readme, {flags: 'r'}).pipe(cs) - cs.pipe(a) - -} - -exports ['split() works with empty string chunks'] = function (test) { - var str = ' foo' - , expected = str.split(/[\s]*/).reduce(splitBy(/[\s]*/), []) - , cs1 = split(/[\s]*/) - , cs2 = split(/[\s]*/) - , actual = [] - , ended = false - , x = spec(cs1).through() - , y = spec(cs2).through() - - var a = new Stream () - - a.write = function (l) { - actual.push(l.trim()) - } - a.end = function () { - - ended = true - expected.forEach(function (v,k) { - //String.split will append an empty string '' - //if the string ends in a split pattern. - //es.split doesn't which was breaking this test. - //clearly, appending the empty string is correct. - //tests are passing though. which is the current job. - if(v) - it(actual[k]).like(v) - }) - //give the stream time to close - process.nextTick(function () { - test.done() - x.validate() - y.validate() - }) - } - a.writable = true - - cs1.pipe(cs2) - cs2.pipe(a) - - cs1.write(str) - cs1.end() - -} - -function splitBy (delimiter) { - return function (arr, piece) { - return arr.concat(piece.split(delimiter)) - } -} diff --git a/reverse_engineering/node_modules/split/test/try_catch.asynct.js b/reverse_engineering/node_modules/split/test/try_catch.asynct.js deleted file mode 100644 index 39e49f7..0000000 --- a/reverse_engineering/node_modules/split/test/try_catch.asynct.js +++ /dev/null @@ -1,51 +0,0 @@ -var it = require('it-is').style('colour') - , split = require('..') - -exports ['emit mapper exceptions as error events'] = function (test) { - var s = split(JSON.parse) - , caughtError = false - , rows = [] - - s.on('error', function (err) { - caughtError = true - }) - - s.on('data', function (row) { rows.push(row) }) - - s.write('{"a":1}\n{"') - it(caughtError).equal(false) - it(rows).deepEqual([ { a: 1 } ]) - - s.write('b":2}\n{"c":}\n') - it(caughtError).equal(true) - it(rows).deepEqual([ { a: 1 }, { b: 2 } ]) - - s.end() - test.done() -} - -exports ['mapper error events on trailing chunks'] = function (test) { - var s = split(JSON.parse) - , caughtError = false - , rows = [] - - s.on('error', function (err) { - caughtError = true - }) - - s.on('data', function (row) { rows.push(row) }) - - s.write('{"a":1}\n{"') - it(caughtError).equal(false) - it(rows).deepEqual([ { a: 1 } ]) - - s.write('b":2}\n{"c":}') - it(caughtError).equal(false) - it(rows).deepEqual([ { a: 1 }, { b: 2 } ]) - - s.end() - it(caughtError).equal(true) - it(rows).deepEqual([ { a: 1 }, { b: 2 } ]) - - test.done() -} diff --git a/reverse_engineering/node_modules/ssh2/.eslintignore b/reverse_engineering/node_modules/ssh2/.eslintignore deleted file mode 100644 index 73ed104..0000000 --- a/reverse_engineering/node_modules/ssh2/.eslintignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules -lib/protocol/crypto/poly1305.js -.eslint-plugins -!.eslintrc.js diff --git a/reverse_engineering/node_modules/ssh2/.eslintrc.js b/reverse_engineering/node_modules/ssh2/.eslintrc.js deleted file mode 100644 index be9311d..0000000 --- a/reverse_engineering/node_modules/ssh2/.eslintrc.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = { - extends: '@mscdex/eslint-config', -}; diff --git a/reverse_engineering/node_modules/ssh2/.github/workflows/ci.yml b/reverse_engineering/node_modules/ssh2/.github/workflows/ci.yml deleted file mode 100644 index c6f610a..0000000 --- a/reverse_engineering/node_modules/ssh2/.github/workflows/ci.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: CI - -on: - pull_request: - push: - branches: [ master ] - -jobs: - tests-linux: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - node-version: [10.16.0, 10.x, 12.x, 14.x, 16.x] - steps: - - uses: actions/checkout@v2 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v1 - with: - node-version: ${{ matrix.node-version }} - - name: Install module - run: npm install - - name: Run tests - run: npm test - tests-windows: - runs-on: windows-latest - strategy: - fail-fast: false - matrix: - node-version: [16.x] - steps: - - uses: actions/checkout@v2 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v1 - with: - node-version: ${{ matrix.node-version }} - - name: Install module - run: npm install - - name: Run tests - run: npm test diff --git a/reverse_engineering/node_modules/ssh2/.github/workflows/lint.yml b/reverse_engineering/node_modules/ssh2/.github/workflows/lint.yml deleted file mode 100644 index ec109fd..0000000 --- a/reverse_engineering/node_modules/ssh2/.github/workflows/lint.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: lint - -on: - pull_request: - push: - branches: [ master ] - -env: - NODE_VERSION: 14.x - -jobs: - lint-js: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Use Node.js ${{ env.NODE_VERSION }} - uses: actions/setup-node@v1 - with: - node-version: ${{ env.NODE_VERSION }} - - name: Install ESLint + ESLint configs/plugins - run: npm install --only=dev - - name: Lint files - run: npm run lint diff --git a/reverse_engineering/node_modules/ssh2/LICENSE b/reverse_engineering/node_modules/ssh2/LICENSE deleted file mode 100644 index 290762e..0000000 --- a/reverse_engineering/node_modules/ssh2/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Brian White. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/ssh2/README.md b/reverse_engineering/node_modules/ssh2/README.md deleted file mode 100644 index e39ec73..0000000 --- a/reverse_engineering/node_modules/ssh2/README.md +++ /dev/null @@ -1,1473 +0,0 @@ -# Description - -SSH2 client and server modules written in pure JavaScript for [node.js](http://nodejs.org/). - -Development/testing is done against OpenSSH (8.7 currently). - -Changes (breaking or otherwise) in v1.0.0 can be found [here](https://github.com/mscdex/ssh2/issues/935). - -# Table of Contents - -* [Requirements](#requirements) -* [Installation](#installation) -* [Client Examples](#client-examples) - * [Execute 'uptime' on a server](#execute-uptime-on-a-server) - * [Start an interactive shell session](#start-an-interactive-shell-session) - * [Send a raw HTTP request to port 80 on the server](#send-a-raw-http-request-to-port-80-on-the-server) - * [Forward local connections to port 8000 on the server to us](#forward-local-connections-to-port-8000-on-the-server-to-us) - * [Get a directory listing via SFTP](#get-a-directory-listing-via-sftp) - * [Connection hopping](#connection-hopping) - * [Forward remote X11 connections](#forward-remote-x11-connections) - * [Dynamic (1:1) port forwarding using a SOCKSv5 proxy (using `socksv5`)](#dynamic-11-port-forwarding-using-a-socksv5-proxy-using-socksv5) - * [Make HTTP(S) connections easily using a custom http(s).Agent](#make-https-connections-easily-using-a-custom-httpsagent) - * [Invoke an arbitrary subsystem (e.g. netconf)](#invoke-an-arbitrary-subsystem) -* [Server Examples](#server-examples) - * [Password and public key authentication and non-interactive (exec) command execution](#password-and-public-key-authentication-and-non-interactive-exec-command-execution) - * [SFTP-only server](#sftp-only-server) -* [API](#api) - * [Client](#client) - * [Client events](#client-events) - * [Client methods](#client-methods) - * [Server](#server) - * [Server events](#server-events) - * [Server methods](#server-methods) - * [Connection events](#connection-events) - * [Connection methods](#connection-methods) - * [Session events](#session-events) - * [Channel](#channel) - * [Pseudo-TTY settings](#pseudo-tty-settings) - * [Terminal modes](#terminal-modes) - * [HTTPAgent](#httpagent) - * [HTTPAgent methods](#httpagent-methods) - * [HTTPSAgent](#httpsagent) - * [HTTPSAgent methods](#httpsagent-methods) - * [Utilities](#utilities) - -## Requirements - -* [node.js](http://nodejs.org/) -- v10.16.0 or newer - * node v12.0.0 or newer for Ed25519 key support -* (Optional) [`cpu-features`](https://github.com/mscdex/cpu-features) is set as an optional package dependency (you do not need to install it explicitly/separately from `ssh2`) that will be automatically built and used if possible. See the project's documentation for its own requirements. - * This addon is currently used to help generate an optimal default cipher list - -## Installation - - npm install ssh2 - -## Client Examples - -### Execute 'uptime' on a server - -```js -const { readFileSync } = require('fs'); - -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.exec('uptime', (err, stream) => { - if (err) throw err; - stream.on('close', (code, signal) => { - console.log('Stream :: close :: code: ' + code + ', signal: ' + signal); - conn.end(); - }).on('data', (data) => { - console.log('STDOUT: ' + data); - }).stderr.on('data', (data) => { - console.log('STDERR: ' + data); - }); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - privateKey: readFileSync('/path/to/my/key') -}); - -// example output: -// Client :: ready -// STDOUT: 17:41:15 up 22 days, 18:09, 1 user, load average: 0.00, 0.01, 0.05 -// -// Stream :: exit :: code: 0, signal: undefined -// Stream :: close -``` - -### Start an interactive shell session - -```js -const { readFileSync } = require('fs'); - -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.shell((err, stream) => { - if (err) throw err; - stream.on('close', () => { - console.log('Stream :: close'); - conn.end(); - }).on('data', (data) => { - console.log('OUTPUT: ' + data); - }); - stream.end('ls -l\nexit\n'); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - privateKey: readFileSync('/path/to/my/key') -}); - -// example output: -// Client :: ready -// STDOUT: Last login: Sun Jun 15 09:37:21 2014 from 192.168.100.100 -// -// STDOUT: ls -l -// exit -// -// STDOUT: frylock@athf:~$ ls -l -// -// STDOUT: total 8 -// -// STDOUT: drwxr-xr-x 2 frylock frylock 4096 Nov 18 2012 mydir -// -// STDOUT: -rw-r--r-- 1 frylock frylock 25 Apr 11 2013 test.txt -// -// STDOUT: frylock@athf:~$ exit -// -// STDOUT: logout -// -// Stream :: close -``` - -### Send a raw HTTP request to port 80 on the server - -```js -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.forwardOut('192.168.100.102', 8000, '127.0.0.1', 80, (err, stream) => { - if (err) throw err; - stream.on('close', () => { - console.log('TCP :: CLOSED'); - conn.end(); - }).on('data', (data) => { - console.log('TCP :: DATA: ' + data); - }).end([ - 'HEAD / HTTP/1.1', - 'User-Agent: curl/7.27.0', - 'Host: 127.0.0.1', - 'Accept: */*', - 'Connection: close', - '', - '' - ].join('\r\n')); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - password: 'nodejsrules' -}); - -// example output: -// Client :: ready -// TCP :: DATA: HTTP/1.1 200 OK -// Date: Thu, 15 Nov 2012 13:52:58 GMT -// Server: Apache/2.2.22 (Ubuntu) -// X-Powered-By: PHP/5.4.6-1ubuntu1 -// Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT -// Content-Encoding: gzip -// Vary: Accept-Encoding -// Connection: close -// Content-Type: text/html; charset=UTF-8 -// -// -// TCP :: CLOSED -``` - -### Forward local connections to port 8000 on the server to us - -```js -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.forwardIn('127.0.0.1', 8000, (err) => { - if (err) throw err; - console.log('Listening for connections on server on port 8000!'); - }); -}).on('tcp connection', (info, accept, reject) => { - console.log('TCP :: INCOMING CONNECTION:'); - console.dir(info); - accept().on('close', () => { - console.log('TCP :: CLOSED'); - }).on('data', (data) => { - console.log('TCP :: DATA: ' + data); - }).end([ - 'HTTP/1.1 404 Not Found', - 'Date: Thu, 15 Nov 2012 02:07:58 GMT', - 'Server: ForwardedConnection', - 'Content-Length: 0', - 'Connection: close', - '', - '' - ].join('\r\n')); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - password: 'nodejsrules' -}); - -// example output: -// Client :: ready -// Listening for connections on server on port 8000! -// (.... then from another terminal on the server: `curl -I http://127.0.0.1:8000`) -// TCP :: INCOMING CONNECTION: { destIP: '127.0.0.1', -// destPort: 8000, -// srcIP: '127.0.0.1', -// srcPort: 41969 } -// TCP DATA: HEAD / HTTP/1.1 -// User-Agent: curl/7.27.0 -// Host: 127.0.0.1:8000 -// Accept: */* -// -// -// TCP :: CLOSED -``` - -### Get a directory listing via SFTP - -```js -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.sftp((err, sftp) => { - if (err) throw err; - sftp.readdir('foo', (err, list) => { - if (err) throw err; - console.dir(list); - conn.end(); - }); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - password: 'nodejsrules' -}); - -// example output: -// Client :: ready -// [ { filename: 'test.txt', -// longname: '-rw-r--r-- 1 frylock frylock 12 Nov 18 11:05 test.txt', -// attrs: -// { size: 12, -// uid: 1000, -// gid: 1000, -// mode: 33188, -// atime: 1353254750, -// mtime: 1353254744 } }, -// { filename: 'mydir', -// longname: 'drwxr-xr-x 2 frylock frylock 4096 Nov 18 15:03 mydir', -// attrs: -// { size: 1048576, -// uid: 1000, -// gid: 1000, -// mode: 16877, -// atime: 1353269007, -// mtime: 1353269007 } } ] -``` - -### Connection hopping - -```js -const { Client } = require('ssh2'); - -const conn1 = new Client(); -const conn2 = new Client(); - -// Checks uptime on 10.1.1.40 via 192.168.1.1 - -conn1.on('ready', () => { - console.log('FIRST :: connection ready'); - // Alternatively, you could use something like netcat or socat with exec() - // instead of forwardOut(), depending on what the server allows - conn1.forwardOut('127.0.0.1', 12345, '10.1.1.40', 22, (err, stream) => { - if (err) { - console.log('FIRST :: forwardOut error: ' + err); - return conn1.end(); - } - conn2.connect({ - sock: stream, - username: 'user2', - password: 'password2', - }); - }); -}).connect({ - host: '192.168.1.1', - username: 'user1', - password: 'password1', -}); - -conn2.on('ready', () => { - // This connection is the one to 10.1.1.40 - - console.log('SECOND :: connection ready'); - conn2.exec('uptime', (err, stream) => { - if (err) { - console.log('SECOND :: exec error: ' + err); - return conn1.end(); - } - stream.on('close', () => { - conn1.end(); // close parent (and this) connection - }).on('data', (data) => { - console.log(data.toString()); - }); - }); -}); -``` - -### Forward remote X11 connections - -```js -const { Socket } = require('net'); - -const { Client } = require('ssh2'); - -const conn = new Client(); - -conn.on('x11', (info, accept, reject) => { - const xserversock = new net.Socket(); - xserversock.on('connect', () => { - const xclientsock = accept(); - xclientsock.pipe(xserversock).pipe(xclientsock); - }); - // connects to localhost:0.0 - xserversock.connect(6000, 'localhost'); -}); - -conn.on('ready', () => { - conn.exec('xeyes', { x11: true }, (err, stream) => { - if (err) throw err; - let code = 0; - stream.on('close', () => { - if (code !== 0) - console.log('Do you have X11 forwarding enabled on your SSH server?'); - conn.end(); - }).on('exit', (exitcode) => { - code = exitcode; - }); - }); -}).connect({ - host: '192.168.1.1', - username: 'foo', - password: 'bar' -}); -``` - -### Dynamic (1:1) port forwarding using a SOCKSv5 proxy (using [socksv5](https://github.com/mscdex/socksv5)) - -```js -const socks = require('socksv5'); -const { Client } = require('ssh2'); - -const sshConfig = { - host: '192.168.100.1', - port: 22, - username: 'nodejs', - password: 'rules' -}; - -socks.createServer((info, accept, deny) => { - // NOTE: you could just use one ssh2 client connection for all forwards, but - // you could run into server-imposed limits if you have too many forwards open - // at any given time - const conn = new Client(); - conn.on('ready', () => { - conn.forwardOut(info.srcAddr, - info.srcPort, - info.dstAddr, - info.dstPort, - (err, stream) => { - if (err) { - conn.end(); - return deny(); - } - - const clientSocket = accept(true); - if (clientSocket) { - stream.pipe(clientSocket).pipe(stream).on('close', () => { - conn.end(); - }); - } else { - conn.end(); - } - }); - }).on('error', (err) => { - deny(); - }).connect(sshConfig); -}).listen(1080, 'localhost', () => { - console.log('SOCKSv5 proxy server started on port 1080'); -}).useAuth(socks.auth.None()); - -// test with cURL: -// curl -i --socks5 localhost:1080 google.com -``` - -### Make HTTP(S) connections easily using a custom http(s).Agent - -```js -const http = require('http'); - -const { Client, HTTPAgent, HTTPSAgent } = require('ssh2'); - -const sshConfig = { - host: '192.168.100.1', - port: 22, - username: 'nodejs', - password: 'rules' -}; - -// Use `HTTPSAgent` instead for an HTTPS request -const agent = new HTTPAgent(sshConfig); -http.get({ - host: '192.168.200.1', - agent, - headers: { Connection: 'close' } -}, (res) => { - console.log(res.statusCode); - console.dir(res.headers); - res.resume(); -}); -``` - - -### Invoke an arbitrary subsystem - -```js -const { Client } = require('ssh2'); - -const xmlhello = ` - - - - urn:ietf:params:netconf:base:1.0 - - ]]>]]>`; - -const conn = new Client(); - -conn.on('ready', () => { - console.log('Client :: ready'); - conn.subsys('netconf', (err, stream) => { - if (err) throw err; - stream.on('data', (data) => { - console.log(data); - }).write(xmlhello); - }); -}).connect({ - host: '1.2.3.4', - port: 22, - username: 'blargh', - password: 'honk' -}); -``` - -## Server Examples - -### Password and public key authentication and non-interactive (exec) command execution - -```js -const { timingSafeEqual } = require('crypto'); -const { readFileSync } = require('fs'); -const { inspect } = require('util'); - -const { utils: { parseKey }, Server } = require('ssh2'); - -const allowedUser = Buffer.from('foo'); -const allowedPassword = Buffer.from('bar'); -const allowedPubKey = parseKey(readFileSync('foo.pub')); - -function checkValue(input, allowed) { - const autoReject = (input.length !== allowed.length); - if (autoReject) { - // Prevent leaking length information by always making a comparison with the - // same input when lengths don't match what we expect ... - allowed = input; - } - const isMatch = timingSafeEqual(input, allowed); - return (!autoReject && isMatch); -} - -new Server({ - hostKeys: [readFileSync('host.key')] -}, (client) => { - console.log('Client connected!'); - - client.on('authentication', (ctx) => { - let allowed = true; - if (!checkValue(Buffer.from(ctx.username), allowedUser)) - allowed = false; - - switch (ctx.method) { - case 'password': - if (!checkValue(Buffer.from(ctx.password), allowedPassword)) - return ctx.reject(); - break; - case 'publickey': - if (ctx.key.algo !== allowedPubKey.type - || !checkValue(ctx.key.data, allowedPubKey.getPublicSSH()) - || (ctx.signature && allowedPubKey.verify(ctx.blob, ctx.signature) !== true)) { - return ctx.reject(); - } - break; - default: - return ctx.reject(); - } - - if (allowed) - ctx.accept(); - else - ctx.reject(); - }).on('ready', () => { - console.log('Client authenticated!'); - - client.on('session', (accept, reject) => { - const session = accept(); - session.once('exec', (accept, reject, info) => { - console.log('Client wants to execute: ' + inspect(info.command)); - const stream = accept(); - stream.stderr.write('Oh no, the dreaded errors!\n'); - stream.write('Just kidding about the errors!\n'); - stream.exit(0); - stream.end(); - }); - }); - }).on('close', () => { - console.log('Client disconnected'); - }); -}).listen(0, '127.0.0.1', function() { - console.log('Listening on port ' + this.address().port); -}); -``` - -### SFTP-only server - -```js -const { timingSafeEqual } = require('crypto'); -const { readFileSync } = require('fs'); -const { inspect } = require('util'); - -const { - Server, - sftp: { - OPEN_MODE, - STATUS_CODE, - }, -} = require('ssh2'); - -const allowedUser = Buffer.from('foo'); -const allowedPassword = Buffer.from('bar'); - -function checkValue(input, allowed) { - const autoReject = (input.length !== allowed.length); - if (autoReject) { - // Prevent leaking length information by always making a comparison with the - // same input when lengths don't match what we expect ... - allowed = input; - } - const isMatch = timingSafeEqual(input, allowed); - return (!autoReject && isMatch); -} - -// This simple SFTP server implements file uploading where the contents get -// ignored ... - -new ssh2.Server({ - hostKeys: [readFileSync('host.key')] -}, (client) => { - console.log('Client connected!'); - - client.on('authentication', (ctx) => { - let allowed = true; - if (!checkValue(Buffer.from(ctx.username), allowedUser)) - allowed = false; - - switch (ctx.method) { - case 'password': - if (!checkValue(Buffer.from(ctx.password), allowedPassword)) - return ctx.reject(); - break; - default: - return ctx.reject(); - } - - if (allowed) - ctx.accept(); - else - ctx.reject(); - }).on('ready', () => { - console.log('Client authenticated!'); - - client.on('session', (accept, reject) => { - const session = accept(); - session.on('sftp', (accept, reject) => { - console.log('Client SFTP session'); - const openFiles = new Map(); - let handleCount = 0; - const sftp = accept(); - sftp.on('OPEN', (reqid, filename, flags, attrs) => { - // Only allow opening /tmp/foo.txt for writing - if (filename !== '/tmp/foo.txt' || !(flags & OPEN_MODE.WRITE)) - return sftp.status(reqid, STATUS_CODE.FAILURE); - - // Create a fake handle to return to the client, this could easily - // be a real file descriptor number for example if actually opening - // a file on disk - const handle = Buffer.alloc(4); - openFiles.set(handleCount, true); - handle.writeUInt32BE(handleCount++, 0); - - console.log('Opening file for write') - sftp.handle(reqid, handle); - }).on('WRITE', (reqid, handle, offset, data) => { - if (handle.length !== 4 - || !openFiles.has(handle.readUInt32BE(0))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - // Fake the write operation - sftp.status(reqid, STATUS_CODE.OK); - - console.log('Write to file at offset ${offset}: ${inspect(data)}'); - }).on('CLOSE', (reqid, handle) => { - let fnum; - if (handle.length !== 4 - || !openFiles.has(fnum = handle.readUInt32BE(0))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - console.log('Closing file'); - openFiles.delete(fnum); - - sftp.status(reqid, STATUS_CODE.OK); - }); - }); - }); - }).on('close', () => { - console.log('Client disconnected'); - }); -}).listen(0, '127.0.0.1', function() { - console.log('Listening on port ' + this.address().port); -}); -``` - -You can find more examples in the `examples` directory of this repository. - -## API - -`require('ssh2').Client` is the **_Client_** constructor. - -`require('ssh2').Server` is the **_Server_** constructor. - -`require('ssh2').utils` is an object containing some useful [utilities](#utilities). - -`require('ssh2').HTTPAgent` is an [`http.Agent`](https://nodejs.org/docs/latest/api/http.html#http_class_http_agent) constructor. - -`require('ssh2').HTTPSAgent` is an [`https.Agent`](https://nodejs.org/docs/latest/api/https.html#https_class_https_agent) constructor. Its API is the same as `HTTPAgent` except it's for HTTPS connections. - -### Agent-related - -`require('ssh2').AgentProtocol` is a Duplex stream [class](#agentprotocol) that aids in communicating over the OpenSSH agent protocol. - -`require('ssh2').BaseAgent` is a base [class](#baseagent) for creating custom authentication agents. - -`require('ssh2').createAgent` is a helper [function](#createagent) that creates a new agent instance using the same logic as the `agent` configuration option: if the platform is Windows and it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not a path to a Windows pipe it creates a `CygwinAgent`. In all other cases, it creates an `OpenSSHAgent`. - -`require('ssh2').CygwinAgent` is an agent [class](#cygwinagent) implementation that communicates with agents in a Cygwin environment. - -`require('ssh2').OpenSSHAgent` is an agent [class](#opensshagent) implementation that communicates with OpenSSH agents over a UNIX socket. - -`require('ssh2').PageantAgent` is an agent [class](#pageantagent) implementation that communicates with Pageant agent processes. - -### Client - -#### Client events - -* **banner**(< _string_ >message, < _string_ >language) - A notice was sent by the server upon connection. - -* **change password**(< _string_ >prompt, < _function_ >done) - If using password-based user authentication, the server has requested that the user's password be changed. Call `done` with the new password. - -* **close**() - The socket was closed. - -* **end**() - The socket was disconnected. - -* **error**(< _Error_ >err) - An error occurred. A 'level' property indicates 'client-socket' for socket-level errors and 'client-ssh' for SSH disconnection messages. In the case of 'client-ssh' messages, there may be a 'description' property that provides more detail. - -* **handshake**(< _object_ >negotiated) - Emitted when a handshake has completed (either initial or rekey). `negotiated` contains the negotiated details of the handshake and is of the form: - -```js - // In this particular case `mac` is empty because there is no separate MAC - // because it's integrated into AES in GCM mode - { kex: 'ecdh-sha2-nistp256', - srvHostKey: 'rsa-sha2-512', - cs: { // Client to server algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - }, - sc: { // Server to client algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - } - } -``` - -* **hostkeys**(< _array_ >keys) - Emitted when the server announces its available host keys. `keys` is the list of parsed (using [`parseKey()`](#utilities)) host public keys. - -* **keyboard-interactive**(< _string_ >name, < _string_ >instructions, < _string_ >instructionsLang, < _array_ >prompts, < _function_ >finish) - The server is asking for replies to the given `prompts` for keyboard-interactive user authentication. `name` is generally what you'd use as a window title (for GUI apps). `prompts` is an array of `{ prompt: 'Password: ', echo: false }` style objects (here `echo` indicates whether user input should be displayed on the screen). The answers for all prompts must be provided as an array of strings and passed to `finish` when you are ready to continue. Note: It's possible for the server to come back and ask more questions. - -* **ready**() - Authentication was successful. - -* **rekey**() - Emitted when a rekeying operation has completed (either client or server-initiated). - -* **tcp connection**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming forwarded TCP connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains: - - * **destIP** - _string_ - The remote IP the connection was received on (given in earlier call to `forwardIn()`). - - * **destPort** - _integer_ - The remote port the connection was received on (given in earlier call to `forwardIn()`). - - * **srcIP** - _string_ - The originating IP of the connection. - - * **srcPort** - _integer_ - The originating port of the connection. - -* **unix connection**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming forwarded UNIX socket connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains: - - * **socketPath** - _string_ - The originating UNIX socket path of the connection. - -* **x11**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming X11 connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains: - - * **srcIP** - _string_ - The originating IP of the connection. - - * **srcPort** - _integer_ - The originating port of the connection. - -#### Client methods - -* **(constructor)**() - Creates and returns a new Client instance. - -* **connect**(< _object_ >config) - _(void)_ - Attempts a connection to a server using the information given in `config`: - - * **agent** - _string_ - Path to ssh-agent's UNIX socket for ssh-agent-based user authentication. **Windows users: set to 'pageant' for authenticating with Pageant or (actual) path to a cygwin "UNIX socket."** **Default:** (none) - - * **agentForward** - _boolean_ - Set to `true` to use OpenSSH agent forwarding (`auth-agent@openssh.com`) for the life of the connection. `agent` must also be set to use this feature. **Default:** `false` - - * **algorithms** - _object_ - This option allows you to explicitly override the default transport layer algorithms used for the connection. The value for each category must either be an array of valid algorithm names to set an exact list (with the most preferable first) or an object containing `append`, `prepend`, and/or `remove` properties that each contain an _array_ of algorithm names or RegExps to match to adjust default lists for each category. Valid keys: - - * **cipher** - _mixed_ - Ciphers. - * Default list (in order from most to least preferable): - * `chacha20-poly1305@openssh.com` (priority of chacha20-poly1305 may vary depending upon CPU and/or optional binding availability) - * `aes128-gcm` - * `aes128-gcm@openssh.com` - * `aes256-gcm` - * `aes256-gcm@openssh.com` - * `aes128-ctr` - * `aes192-ctr` - * `aes256-ctr` - * Other supported names: - * `3des-cbc` - * `aes256-cbc` - * `aes192-cbc` - * `aes128-cbc` - * `arcfour256` - * `arcfour128` - * `arcfour` - * `blowfish-cbc` - * `cast128-cbc` - - * **compress** - _mixed_ - Compression algorithms. - * Default list (in order from most to least preferable): - * `none` - * `zlib@openssh.com` - * `zlib` - * Other supported names: - - * **hmac** - _mixed_ - (H)MAC algorithms. - * Default list (in order from most to least preferable): - * `hmac-sha2-256-etm@openssh.com` - * `hmac-sha2-512-etm@openssh.com` - * `hmac-sha1-etm@openssh.com` - * `hmac-sha2-256` - * `hmac-sha2-512` - * `hmac-sha1` - * Other supported names: - * `hmac-md5` - * `hmac-sha2-256-96` - * `hmac-sha2-512-96` - * `hmac-ripemd160` - * `hmac-sha1-96` - * `hmac-md5-96` - - * **kex** - _mixed_ - Key exchange algorithms. - * Default list (in order from most to least preferable): - * `curve25519-sha256 (node v14.0.0+)` - * `curve25519-sha256@libssh.org (node v14.0.0+)` - * `ecdh-sha2-nistp256` - * `ecdh-sha2-nistp384` - * `ecdh-sha2-nistp521` - * `diffie-hellman-group-exchange-sha256` - * `diffie-hellman-group14-sha256` - * `diffie-hellman-group15-sha512` - * `diffie-hellman-group16-sha512` - * `diffie-hellman-group17-sha512` - * `diffie-hellman-group18-sha512` - * Other supported names: - * `diffie-hellman-group-exchange-sha1` - * `diffie-hellman-group14-sha1` - * `diffie-hellman-group1-sha1` - - * **serverHostKey** - _mixed_ - Server host key formats. - * Default list (in order from most to least preferable): - * `ssh-ed25519` (node v12.0.0+) - * `ecdsa-sha2-nistp256` - * `ecdsa-sha2-nistp384` - * `ecdsa-sha2-nistp521` - * `rsa-sha2-512` - * `rsa-sha2-256` - * `ssh-rsa` - * Other supported names: - * `ssh-dss` - - * **authHandler** - _mixed_ - Either an array of objects as described below or a function with parameters `(methodsLeft, partialSuccess, callback)` where `methodsLeft` and `partialSuccess` are `null` on the first authentication attempt, otherwise are an array and boolean respectively. Return or call `callback()` with either the name of the authentication method or an object containing the method name along with method-specific details to try next (return/pass `false` to signal no more methods to try). Valid method names are: `'none', 'password', 'publickey', 'agent', 'keyboard-interactive', 'hostbased'`. **Default:** function that follows a set method order: None -> Password -> Private Key -> Agent (-> keyboard-interactive if `tryKeyboard` is `true`) -> Hostbased - - * When returning or calling `callback()` with an object, it can take one of the following forms: - - ```js - { - type: 'none', - username: 'foo', - } - ``` - - ```js - { - type: 'password' - username: 'foo', - password: 'bar', - } - ``` - - ```js - { - type: 'publickey' - username: 'foo', - // Can be a string, Buffer, or parsed key containing a private key - key: ..., - // `passphrase` only required for encrypted keys - passphrase: ..., - } - ``` - - ```js - { - type: 'hostbased' - username: 'foo', - localHostname: 'baz', - localUsername: 'quux', - // Can be a string, Buffer, or parsed key containing a private key - key: ..., - // `passphrase` only required for encrypted keys - passphrase: ..., - } - ``` - - ```js - { - type: 'agent' - username: 'foo', - // Can be a string that is interpreted exactly like the `agent` - // connection config option or can be a custom agent - // object/instance that extends and implements `BaseAgent` - agent: ..., - } - ``` - - ```js - { - type: 'keyboard-interactive' - username: 'foo', - // This works exactly the same way as a 'keyboard-interactive' - // Client event handler - prompt: (name, instructions, instructionsLang, prompts, finish) => { - // ... - }, - } - ``` - - * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none) - - * **forceIPv4** - _boolean_ - Only connect via resolved IPv4 address for `host`. **Default:** `false` - - * **forceIPv6** - _boolean_ - Only connect via resolved IPv6 address for `host`. **Default:** `false` - - * **host** - _string_ - Hostname or IP address of the server. **Default:** `'localhost'` - - * **hostHash** - _string_ - Any valid hash algorithm supported by node. The host's key is hashed using this algorithm and passed to the **hostVerifier** function as a hex string. **Default:** (none) - - * **hostVerifier** - _function_ - Function with parameters `(hashedKey[, callback])` where `hashedKey` is a string hex hash of the host's key for verification purposes. Return `true` to continue with the handshake or `false` to reject and disconnect, or call `callback()` with `true` or `false` if you need to perform asynchronous verification. **Default:** (auto-accept if `hostVerifier` is not set) - - * **keepaliveCountMax** - _integer_ - How many consecutive, unanswered SSH-level keepalive packets that can be sent to the server before disconnection (similar to OpenSSH's ServerAliveCountMax config option). **Default:** `3` - - * **keepaliveInterval** - _integer_ - How often (in milliseconds) to send SSH-level keepalive packets to the server (in a similar way as OpenSSH's ServerAliveInterval config option). Set to 0 to disable. **Default:** `0` - - * **localAddress** - _string_ - IP address of the network interface to use to connect to the server. **Default:** (none -- determined by OS) - - * **localHostname** - _string_ - Along with **localUsername** and **privateKey**, set this to a non-empty string for hostbased user authentication. **Default:** (none) - - * **localPort** - _string_ - The local port number to connect from. **Default:** (none -- determined by OS) - - * **localUsername** - _string_ - Along with **localHostname** and **privateKey**, set this to a non-empty string for hostbased user authentication. **Default:** (none) - - * **passphrase** - _string_ - For an encrypted `privateKey`, this is the passphrase used to decrypt it. **Default:** (none) - - * **password** - _string_ - Password for password-based user authentication. **Default:** (none) - - * **port** - _integer_ - Port number of the server. **Default:** `22` - - * **privateKey** - _mixed_ - _Buffer_ or _string_ that contains a private key for either key-based or hostbased user authentication (OpenSSH format). **Default:** (none) - - * **readyTimeout** - _integer_ - How long (in milliseconds) to wait for the SSH handshake to complete. **Default:** `20000` - - * **sock** - _ReadableStream_ - A _ReadableStream_ to use for communicating with the server instead of creating and using a new TCP connection (useful for connection hopping). - - * **strictVendor** - _boolean_ - Performs a strict server vendor check before sending vendor-specific requests, etc. (e.g. check for OpenSSH server when using `openssh_noMoreSessions()`) **Default:** `true` - - * **tryKeyboard** - _boolean_ - Try keyboard-interactive user authentication if primary user authentication method fails. If you set this to `true`, you need to handle the `keyboard-interactive` event. **Default:** `false` - - * **username** - _string_ - Username for authentication. **Default:** (none) - -* **end**() - _(void)_ - Disconnects the socket. - -* **exec**(< _string_ >command[, < _object_ >options], < _function_ >callback) - _(void)_ - Executes `command` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. Valid `options` properties are: - - * **env** - _object_ - An environment to use for the execution of the command. - - * **pty** - _mixed_ - Set to `true` to allocate a pseudo-tty with defaults, or an object containing specific pseudo-tty settings (see 'Pseudo-TTY settings'). Setting up a pseudo-tty can be useful when working with remote processes that expect input from an actual terminal (e.g. sudo's password prompt). - - * **x11** - _mixed_ - Set to `true` to use defaults below, set to a number to specify a specific screen number, or an object with the following valid properties: - - * **cookie** - _mixed_ - The authentication cookie. Can be a hex _string_ or a _Buffer_ containing the raw cookie value (which will be converted to a hex string). **Default:** (random 16 byte value) - - * **protocol** - _string_ - The authentication protocol name. **Default:** `'MIT-MAGIC-COOKIE-1'` - - * **screen** - _number_ - Screen number to use **Default:** `0` - - * **single** - _boolean_ - Allow just a single connection? **Default:** `false` - -* **forwardIn**(< _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Bind to `remoteAddr` on `remotePort` on the server and forward incoming TCP connections. `callback` has 2 parameters: < _Error_ >err, < _integer_ >port (`port` is the assigned port number if `remotePort` was 0). Here are some special values for `remoteAddr` and their associated binding behaviors: - - * '' - Connections are to be accepted on all protocol families supported by the server. - - * '0.0.0.0' - Listen on all IPv4 addresses. - - * '::' - Listen on all IPv6 addresses. - - * 'localhost' - Listen on all protocol families supported by the server on loopback addresses only. - - * '127.0.0.1' and '::1' - Listen on the loopback interfaces for IPv4 and IPv6, respectively. - -* **forwardOut**(< _string_ >srcIP, < _integer_ >srcPort, < _string_ >dstIP, < _integer_ >dstPort, < _function_ >callback) - _(void)_ - Open a connection with `srcIP` and `srcPort` as the originating address and port and `dstIP` and `dstPort` as the remote destination address and port. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **openssh_forwardInStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that binds to a UNIX domain socket at `socketPath` on the server and forwards incoming connections. `callback` has 1 parameter: < _Error_ >err. - -* **openssh_forwardOutStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that opens a connection to a UNIX domain socket at `socketPath` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **openssh_noMoreSessions**(< _function_ >callback) - _(void)_ - OpenSSH extension that sends a request to reject any new sessions (e.g. exec, shell, sftp, subsys) for this connection. `callback` has 1 parameter: < _Error_ >err. - -* **openssh_unforwardInStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that unbinds from a UNIX domain socket at `socketPath` on the server and stops forwarding incoming connections. `callback` has 1 parameter: < _Error_ >err. - -* **rekey**([< _function_ >callback]) - _(void)_ - Initiates a rekey with the server. If `callback` is supplied, it is added as a one-time handler for the `rekey` event. - -* **sftp**(< _function_ >callback) - _(void)_ - Starts an SFTP session. `callback` has 2 parameters: < _Error_ >err, < _SFTP_ >sftp. For methods available on `sftp`, see the [`SFTP` client documentation](https://github.com/mscdex/ssh2/blob/master/SFTP.md). - -* **shell**([[< _mixed_ >window,] < _object_ >options]< _function_ >callback) - _(void)_ - Starts an interactive shell session on the server, with an optional `window` object containing pseudo-tty settings (see 'Pseudo-TTY settings'). If `window === false`, then no pseudo-tty is allocated. `options` supports the `x11` and `env` options as described in `exec()`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **subsys**(< _string_ >subsystem, < _function_ >callback) - _(void)_ - Invokes `subsystem` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **unforwardIn**(< _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Unbind from `remoteAddr` on `remotePort` on the server and stop forwarding incoming TCP connections. Until `callback` is called, more connections may still come in. `callback` has 1 parameter: < _Error_ >err. - -### Server - -#### Server events - -* **connection**(< _Connection_ >client, < _object_ >info) - A new client has connected. `info` contains the following properties: - - * **family** - _string_ - The `remoteFamily` of the connection. - - * **header** - _object_ - Information about the client's header: - - * **identRaw** - _string_ - The raw client identification string. - - * **versions** - _object_ - Various version information: - - * **protocol** - _string_ - The SSH protocol version (always `1.99` or `2.0`). - - * **software** - _string_ - The software name and version of the client. - - * **comments** - _string_ - Any text that comes after the software name/version. - - Example: the identification string `SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2` would be parsed as: - -```js - { identRaw: 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2', - version: { - protocol: '2.0', - software: 'OpenSSH_6.6.1p1' - }, - comments: 'Ubuntu-2ubuntu2' } -``` - - * **ip** - _string_ - The `remoteAddress` of the connection. - - * **port** - _integer_ - The `remotePort` of the connection. - -#### Server methods - -* **(constructor)**(< _object_ >config[, < _function_ >connectionListener]) - Creates and returns a new Server instance. Server instances also have the same methods/properties/events as [`net.Server`](http://nodejs.org/docs/latest/api/net.html#net_class_net_server). `connectionListener` if supplied, is added as a `connection` listener. Valid `config` properties: - - * **algorithms** - _object_ - This option allows you to explicitly override the default transport layer algorithms used for incoming client connections. Each value must be an array of valid algorithms for that category. The order of the algorithms in the arrays are important, with the most favorable being first. For a list of valid and default algorithm names, please review the documentation for the version of `ssh2` used by this module. Valid keys: - - * **cipher** - _array_ - Ciphers. - - * **compress** - _array_ - Compression algorithms. - - * **hmac** - _array_ - (H)MAC algorithms. - - * **kex** - _array_ - Key exchange algorithms. - - * **serverHostKey** - _array_ - Server host key formats. - - * **banner** - _string_ - A message that is sent to clients once, right before authentication begins. **Default:** (none) - - * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none) - - * **greeting** - _string_ - A message that is sent to clients immediately upon connection, before handshaking begins. **Note:** Most clients usually ignore this. **Default:** (none) - - * **highWaterMark** - _integer_ - This is the `highWaterMark` to use for the parser stream. **Default:** `32 * 1024` - - * **hostKeys** - _array_ - An array of either Buffers/strings that contain host private keys or objects in the format of `{ key: , passphrase: }` for encrypted private keys. (**Required**) **Default:** (none) - - * **ident** - _string_ - A custom server software name/version identifier. **Default:** `'ssh2js' + moduleVersion + 'srv'` - -* **injectSocket**(< _DuplexStream_ >socket) - Injects a bidirectional stream as though it were a TCP socket connection. Additionally, `socket` should include `net.Socket`-like properties to ensure the best compatibility (e.g. `socket.remoteAddress`, `socket.remotePort`, `socket.remoteFamily`). - -#### Connection events - -* **authentication**(< _AuthContext_ >ctx) - The client has requested authentication. `ctx.username` contains the client username, `ctx.method` contains the requested authentication method, and `ctx.accept()` and `ctx.reject([< Array >authMethodsLeft[, < Boolean >isPartialSuccess]])` are used to accept or reject the authentication request respectively. `abort` is emitted if the client aborts the authentication request. Other properties/methods available on `ctx` depends on the `ctx.method` of authentication the client has requested: - - * `hostbased`: - - * **blob** - _Buffer_ - This contains the data to be verified that is passed to (along with the signature) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - - * **key** - _object_ - Contains information about the public key sent by the client: - - * **algo** - _string_ - The name of the key algorithm (e.g. `ssh-rsa`). - - * **data** - _Buffer_ - The actual key data. - - * **localHostname** - _string_ - The local hostname provided by the client. - - * **localUsername** - _string_ - The local username provided by the client. - - * **signature** - _Buffer_ - This contains a signature to be verified that is passed to (along with the blob) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - - * `keyboard-interactive`: - - * **prompt**(< _array_ >prompts[, < _string_ >title[, < _string_ >instructions]], < _function_ >callback) - _(void)_ - Send prompts to the client. `prompts` is an array of `{ prompt: 'Prompt text', echo: true }` objects (`prompt` being the prompt text and `echo` indicating whether the client's response to the prompt should be echoed to their display). `callback` is called with `(responses)`, where `responses` is an array of string responses matching up to the `prompts`. - - * **submethods** - _array_ - A list of preferred authentication "sub-methods" sent by the client. This may be used to determine what (if any) prompts to send to the client. - - * `password`: - - * **password** - _string_ - This is the password sent by the client. - - * **requestChange**(< _string_ >prompt, < _function_ >callback) - _(void)_ - Sends a password change request to the client. `callback` is called with `(newPassword)`, where `newPassword` is the new password supplied by the client. You may accept, reject, or prompt for another password change after `callback` is called. - - * `publickey`: - - * **blob** - _mixed_ - If the value is `undefined`, the client is only checking the validity of the `key`. If the value is a _Buffer_, then this contains the data to be verified that is passed to (along with the signature) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - - * **key** - _object_ - Contains information about the public key sent by the client: - - * **algo** - _string_ - The name of the key algorithm (e.g. `ssh-rsa`). - - * **data** - _Buffer_ - The actual key data. - - * **signature** - _mixed_ - If the value is `undefined`, the client is only checking the validity of the `key`. If the value is a _Buffer_, then this contains a signature to be verified that is passed to (along with the blob) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - -* **close**() - The client socket was closed. - -* **end**() - The client socket disconnected. - -* **error**(< _Error_ >err) - An error occurred. - -* **handshake**(< _object_ >negotiated) - Emitted when a handshake has completed (either initial or rekey). `negotiated` contains the negotiated details of the handshake and is of the form: - -```js - // In this particular case `mac` is empty because there is no separate MAC - // because it's integrated into AES in GCM mode - { kex: 'ecdh-sha2-nistp256', - srvHostKey: 'rsa-sha2-512', - cs: { // Client to server algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - }, - sc: { // Server to client algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - } - } -``` - -* **openssh.streamlocal**(< _function_ >accept, < _function_ >reject, < _object_ >info) - Emitted when the client has requested a connection to a UNIX domain socket. `accept()` returns a new _Channel_ instance representing the connection. `info` contains: - - * **socketPath** - _string_ - Destination socket path of outgoing connection. - -* **ready**() - Emitted when the client has been successfully authenticated. - -* **rekey**() - Emitted when a rekeying operation has completed (either client or server-initiated). - -* **request**(< _mixed_ >accept, < _mixed_ >reject, < _string_ >name, < _object_ >info) - Emitted when the client has sent a global request for `name` (e.g. `tcpip-forward` or `cancel-tcpip-forward`). `accept` and `reject` are functions if the client requested a response. If `bindPort === 0`, you should pass the chosen port to `accept()` so that the client will know what port was bound. `info` contains additional details about the request: - - * `cancel-tcpip-forward` and `tcpip-forward`: - - * **bindAddr** - _string_ - The IP address to start/stop binding to. - - * **bindPort** - _integer_ - The port to start/stop binding to. - - * `cancel-streamlocal-forward@openssh.com` and `streamlocal-forward@openssh.com`: - - * **socketPath** - _string_ - The socket path to start/stop binding to. - -* **session**(< _function_ >accept, < _function_ >reject) - Emitted when the client has requested a new session. Sessions are used to start interactive shells, execute commands, request X11 forwarding, etc. `accept()` returns a new _Session_ instance. - -* **tcpip**(< _function_ >accept, < _function_ >reject, < _object_ >info) - Emitted when the client has requested an outbound (TCP) connection. `accept()` returns a new _Channel_ instance representing the connection. `info` contains: - - * **destIP** - _string_ - Destination IP address of outgoing connection. - - * **destPort** - _string_ - Destination port of outgoing connection. - - * **srcIP** - _string_ - Source IP address of outgoing connection. - - * **srcPort** - _string_ - Source port of outgoing connection. - -#### Connection methods - -* **end**() - _(void)_ - Closes the client connection. - -* **forwardOut**(< _string_ >boundAddr, < _integer_ >boundPort, < _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Alert the client of an incoming TCP connection on `boundAddr` on port `boundPort` from `remoteAddr` on port `remotePort`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **openssh_forwardOutStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - Alert the client of an incoming UNIX domain socket connection on `socketPath`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **rekey**([< _function_ >callback]) - _(void)_ - Initiates a rekey with the client. If `callback` is supplied, it is added as a one-time handler for the `rekey` event. - -* **x11**(< _string_ >originAddr, < _integer_ >originPort, < _function_ >callback) - _(void)_ - Alert the client of an incoming X11 client connection from `originAddr` on port `originPort`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -#### Session events - -* **auth-agent**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested incoming ssh-agent requests be forwarded to them. `accept` and `reject` are functions if the client requested a response. - -* **close**() - The session was closed. - -* **env**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested an environment variable to be set for this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **key** - _string_ - The environment variable's name. - - * **value** - _string_ - The environment variable's value. - -* **exec**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has requested execution of a command string. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the command execution. `info` has these properties: - - * **command** - _string_ - The command line to be executed. - -* **pty**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested allocation of a pseudo-TTY for this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **cols** - _integer_ - The number of columns for the pseudo-TTY. - - * **height** - _integer_ - The height of the pseudo-TTY in pixels. - - * **modes** - _object_ - Contains the requested terminal modes of the pseudo-TTY keyed on the mode name with the value being the mode argument. (See the table at the end for valid names). - - * **rows** - _integer_ - The number of rows for the pseudo-TTY. - - * **width** - _integer_ - The width of the pseudo-TTY in pixels. - -* **sftp**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested the SFTP subsystem. `accept` and `reject` are functions if the client requested a response. `accept()` returns an _SFTP_ instance in server mode (see the [`SFTP` documentation](https://github.com/mscdex/ssh2/blob/master/SFTP.md) for details). `info` has these properties: - -* **shell**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested an interactive shell. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the interactive shell. - -* **signal**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has sent a signal. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **name** - _string_ - The signal name (e.g. `SIGUSR1`). - -* **subsystem**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has requested an arbitrary subsystem. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the subsystem. `info` has these properties: - - * **name** - _string_ - The name of the subsystem. - -* **window-change**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client reported a change in window dimensions during this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **cols** - _integer_ - The new number of columns for the client window. - - * **height** - _integer_ - The new height of the client window in pixels. - - * **rows** - _integer_ - The new number of rows for the client window. - - * **width** - _integer_ - The new width of the client window in pixels. - -* **x11**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested X11 forwarding. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **cookie** - _string_ - The X11 authentication cookie encoded in hexadecimal. - - * **protocol** - _string_ - The name of the X11 authentication method used (e.g. `MIT-MAGIC-COOKIE-1`). - - * **screen** - _integer_ - The screen number to forward X11 connections for. - - * **single** - _boolean_ - `true` if only a single connection should be forwarded. - -### Channel - -This is a normal **streams2** Duplex Stream (used both by clients and servers), with the following changes: - -* A boolean property `allowHalfOpen` exists and behaves similarly to the property of the same name for `net.Socket`. When the stream's end() is called, if `allowHalfOpen` is `true`, only EOF will be sent (the server can still send data if they have not already sent EOF). The default value for this property is `true`. - -* A `close` event is emitted once the channel is completely closed on both the client and server. - -* Client-specific: - - * For exec(): - - * An `exit` event *may* (the SSH2 spec says it is optional) be emitted when the process finishes. If the process finished normally, the process's return value is passed to the `exit` callback. If the process was interrupted by a signal, the following are passed to the `exit` callback: null, < _string_ >signalName, < _boolean_ >didCoreDump, < _string_ >description. - - * If there was an `exit` event, the `close` event will be passed the same arguments for convenience. - - * A `stderr` property contains a Readable stream that represents output from stderr. - - * For exec() and shell(): - - * The readable side represents stdout and the writable side represents stdin. - - * **setWindow**(< _integer_ >rows, < _integer_ >cols, < _integer_ >height, < _integer_ >width) - _(void)_ - Lets the server know that the local terminal window has been resized. The meaning of these arguments are described in the 'Pseudo-TTY settings' section. - - * **signal**(< _string_ >signalName) - _(void)_ - Sends a POSIX signal to the current process on the server. Valid signal names are: 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'KILL', 'PIPE', 'QUIT', 'SEGV', 'TERM', 'USR1', and 'USR2'. Some server implementations may ignore this request if they do not support signals. Note: If you are trying to send SIGINT and you find `signal()` doesn't work, try writing `'\x03'` to the Channel stream instead. - - -* Server-specific: - - * For exec-enabled channel instances there is an additional method available that may be called right before you close the channel. It has two different signatures: - - * **exit**(< _integer_ >exitCode) - _(void)_ - Sends an exit status code to the client. - - * **exit**(< _string_ >signalName[, < _boolean_ >coreDumped[, < _string_ >errorMsg]]) - _(void)_ - Sends an exit status code to the client. - - * For exec and shell-enabled channel instances, `channel.stderr` is a writable stream. - -### Pseudo-TTY settings - -* **cols** - < _integer_ > - Number of columns. **Default:** `80` - -* **height** - < _integer_ > - Height in pixels. **Default:** `480` - -* **modes** - < _object_ > - An object containing [Terminal Modes](#terminal-modes) as keys, with each value set to each mode argument. **Default:** `null` - -* **rows** - < _integer_ > - Number of rows. **Default:** `24` - -* **term** - < _string_ > - The value to use for $TERM. **Default:** `'vt100'` - -* **width** - < _integer_ > - Width in pixels. **Default:** `640` - -`rows` and `cols` override `width` and `height` when `rows` and `cols` are non-zero. - -Pixel dimensions refer to the drawable area of the window. - -Zero dimension parameters are ignored. - -### Terminal modes - -Name | Description --------------- | ------------ -CS7 | 7 bit mode. -CS8 | 8 bit mode. -ECHOCTL | Echo control characters as ^(Char). -ECHO | Enable echoing. -ECHOE | Visually erase chars. -ECHOKE | Visual erase for line kill. -ECHOK | Kill character discards current line. -ECHONL | Echo NL even if ECHO is off. -ICANON | Canonicalize input lines. -ICRNL | Map CR to NL on input. -IEXTEN | Enable extensions. -IGNCR | Ignore CR on input. -IGNPAR | The ignore parity flag. The parameter SHOULD be 0 if this flag is FALSE, and 1 if it is TRUE. -IMAXBEL | Ring bell on input queue full. -INLCR | Map NL into CR on input. -INPCK | Enable checking of parity errors. -ISIG | Enable signals INTR, QUIT, [D]SUSP. -ISTRIP | Strip 8th bit off characters. -IUCLC | Translate uppercase characters to lowercase. -IXANY | Any char will restart after stop. -IXOFF | Enable input flow control. -IXON | Enable output flow control. -NOFLSH | Don't flush after interrupt. -OCRNL | Translate carriage return to newline (output). -OLCUC | Convert lowercase to uppercase. -ONLCR | Map NL to CR-NL. -ONLRET | Newline performs a carriage return (output). -ONOCR | Translate newline to carriage return-newline (output). -OPOST | Enable output processing. -PARENB | Parity enable. -PARMRK | Mark parity and framing errors. -PARODD | Odd parity, else even. -PENDIN | Retype pending input. -TOSTOP | Stop background jobs from output. -TTY_OP_ISPEED | Specifies the input baud rate in bits per second. -TTY_OP_OSPEED | Specifies the output baud rate in bits per second. -VDISCARD | Toggles the flushing of terminal output. -VDSUSP | Another suspend character. -VEOF | End-of-file character (sends EOF from the terminal). -VEOL2 | Additional end-of-line character. -VEOL | End-of-line character in addition to carriage return and/or linefeed. -VERASE | Erase the character to left of the cursor. -VFLUSH | Character to flush output. -VINTR | Interrupt character; 255 if none. Similarly for the other characters. Not all of these characters are supported on all systems. -VKILL | Kill the current input line. -VLNEXT | Enter the next character typed literally, even if it is a special character -VQUIT | The quit character (sends SIGQUIT signal on POSIX systems). -VREPRINT | Reprints the current input line. -VSTART | Continues paused output (normally control-Q). -VSTATUS | Prints system status line (load, command, pid, etc). -VSTOP | Pauses output (normally control-S). -VSUSP | Suspends the current program. -VSWTCH | Switch to a different shell layer. -VWERASE | Erases a word left of cursor. -XCASE | Enable input and output of uppercase characters by preceding their lowercase equivalents with "\". - -### HTTPAgent - -#### HTTPAgent methods - -* **(constructor)**(< _object_ >sshConfig[, < _object_ >agentConfig]) - Creates and returns a new `http.Agent` instance used to tunnel an HTTP connection over SSH. `sshConfig` is what is passed to `client.connect()` and `agentOptions` is passed to the `http.Agent` constructor. - -### HTTPSAgent - -#### HTTPSAgent methods - -* **(constructor)**(< _object_ >sshConfig[, < _object_ >agentConfig]) - Creates and returns a new `https.Agent` instance used to tunnel an HTTP connection over SSH. `sshConfig` is what is passed to `client.connect()` and `agentOptions` is passed to the `https.Agent` constructor. - -### Utilities - -* **parseKey**(< _mixed_ >keyData[, < _string_ >passphrase]) - _mixed_ - Parses a private/public key in OpenSSH, RFC4716, or PPK format. For encrypted private keys, the key will be decrypted with the given `passphrase`. `keyData` can be a _Buffer_ or _string_ value containing the key contents. The returned value will be an array of objects (currently in the case of modern OpenSSH keys) or an object with these properties and methods: - - * **comment** - _string_ - The comment for the key - - * **equals**(< _mixed_ >otherKey) - _boolean_ - This returns `true` if `otherKey` (a parsed or parseable key) is the same as this key. This method does not compare the keys' comments - - * **getPrivatePEM**() - _string_ - This returns the PEM version of a private key - - * **getPublicPEM**() - _string_ - This returns the PEM version of a public key (for either public key or derived from a private key) - - * **getPublicSSH**() - _string_ - This returns the SSH version of a public key (for either public key or derived from a private key) - - * **isPrivateKey**() - _boolean_ - This returns `true` if the key is a private key or not - - * **sign**(< _mixed_ >data) - _mixed_ - This signs the given `data` using this key and returns a _Buffer_ containing the signature on success. On failure, an _Error_ will be returned. `data` can be anything accepted by node's [`sign.update()`](https://nodejs.org/docs/latest/api/crypto.html#crypto_sign_update_data_inputencoding). - - * **type** - _string_ - The full key type (e.g. `'ssh-rsa'`) - - * **verify**(< _mixed_ >data, < _Buffer_ >signature) - _mixed_ - This verifies a `signature` of the given `data` using this key and returns `true` if the signature could be verified. On failure, either `false` will be returned or an _Error_ will be returned upon a more critical failure. `data` can be anything accepted by node's [`verify.update()`](https://nodejs.org/docs/latest/api/crypto.html#crypto_verify_update_data_inputencoding). - -* **sftp.OPEN_MODE** - [`OPEN_MODE`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-data-structures) - -* **sftp.STATUS_CODE** - [`STATUS_CODE`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-data-structures) - -* **sftp.flagsToString** - [`flagsToString()`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-methods) - -* **sftp.stringToFlags** - [`stringToFlags()`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-methods) - -### AgentProtocol - -#### AgentProtocol events - -* **identities**(< _opaque_ >request) - **(Server mode only)** The client has requested a list of public keys stored in the agent. Use `failureReply()` or `getIdentitiesReply()` to reply appropriately. - -* **sign**(< _opaque_ >request, < _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options) - **(Server mode only)** The client has requested `data` to be signed using the key identified by `pubKey`. Use `failureReply()` or `signReply()` to reply appropriately. `options` may contain any of: - - * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys. - -#### AgentProtocol methods - -* **(constructor)**(< _boolean_ >isClient) - Creates and returns a new AgentProtocol instance. `isClient` determines whether the instance operates in client or server mode. - -* **failureReply**(< _opaque_ >request) - _(void)_ - **(Server mode only)** Replies to the given `request` with a failure response. - -* **getIdentities**(< _function_ >callback) - _(void)_ - **(Client mode only)** Requests a list of public keys from the agent. `callback` is passed `(err, keys)` where `keys` is a possible array of public keys for authentication. - -* **getIdentitiesReply**(< _opaque_ >request, < _array_ >keys) - _(void)_ - **(Server mode only)** Responds to a identities list `request` with the given array of keys in `keys`. - -* **sign**(< _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options, < _function_ >callback) - _(void)_ - **(Client mode only)** Requests that the agent sign `data` using the key identified by `pubKey`. `pubKey` can be any parsed (using `utils.parseKey()`) or parseable key value. `callback` is passed `(err, signature)` where `signature` is a possible _Buffer_ containing the signature for the `data`. `options` may contain any of: - - * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys. - -* **signReply**(< _opaque_ >request, < _Buffer_ >signature) - _(void)_ - **(Server mode only)** Responds to a sign `request` with the given signature in `signature`. - -### BaseAgent - -In order to create a custom agent, your class *must*: - - * Extend `BaseAgent` - * Call `super()` in its constructor - * Implement *at least* the following methods: - -* **getIdentities**(< _function_ >callback) - _(void)_ - Passes `(err, keys)` to `callback` where `keys` is a possible array of public keys for authentication. - -* **sign**(< _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options, < _function_ >callback) - _(void)_ - Signs `data` using the key identified by `pubKey`. `pubKey` can be any parsed (using `utils.parseKey()`) or parseable key value. `callback` should be passed `(err, signature)` where `signature` is a possible _Buffer_ containing the signature for the `data`. `options` may contain any of: - - * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys. - -Additionally your class may implement the following method in order to support agent forwarding on the client: - -* **getStream**(< _function_ >callback) - _(void)_ - Passes `(err, stream)` to `callback` where `stream` is a possible Duplex stream to be used to communicate with your agent. You will probably want to utilize `AgentProtocol` as agent forwarding is an OpenSSH feature, so the `stream` needs to be able to transmit/receive OpenSSH agent protocol packets. - -### createAgent - -* **createAgent**(< _string_ >agentValue) - _(Agent)_ - Creates and returns a new agent instance using the same logic as the `Client`'s `agent` configuration option: if the platform is Windows and it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not a path to a Windows pipe it creates a `CygwinAgent`. In all other cases, it creates an `OpenSSHAgent`. - -### CygwinAgent - -#### CygwinAgent methods - -* **(constructor)**(< _string_ >socketPath) - Communicates with an agent listening at `socketPath` in a Cygwin environment. - -### OpenSSHAgent - -#### OpenSSHAgent methods - -* **(constructor)**(< _string_ >socketPath) - Communicates with an OpenSSH agent listening on the UNIX socket at `socketPath`. - -### PageantAgent - -#### PageantAgent methods - -* **(constructor)**() - Creates a new agent instance for communicating with a running Pageant agent process. diff --git a/reverse_engineering/node_modules/ssh2/SFTP.md b/reverse_engineering/node_modules/ssh2/SFTP.md deleted file mode 100644 index 60c33ba..0000000 --- a/reverse_engineering/node_modules/ssh2/SFTP.md +++ /dev/null @@ -1,403 +0,0 @@ -SFTP events ------------ - -**Client/Server events** - -* **ready**() - Emitted after initial protocol version check has passed. - -**Server-only events** - -_Responses to these client requests are sent using one of the methods listed further in this document under `Server-only methods`. The valid response(s) for each request are documented below._ - -* **OPEN**(< _integer_ >reqID, < _string_ >filename, < _integer_ >flags, < _ATTRS_ >attrs) - - `flags` is a bitfield containing any of the flags defined in `OPEN_MODE`. - Use the static method `flagsToString()` to convert the value to a mode - string to be used by `fs.open()` (e.g. `'r'`). - - Respond using one of the following: - - * `handle()` - This indicates a successful opening of the file and passes - the given handle back to the client to use to refer to this open file for - future operations (e.g. reading, writing, closing). - - * `status()` - Use this to indicate a failure to open the requested file. - -* **READ**(< _integer_ >reqID, < _Buffer_ >handle, < _integer_ >offset, < _integer_ >length) - - Respond using one of the following: - - * `data()` - Use this to send the requested chunk of data back to the client. - The amount of data sent is allowed to be less than the `length` requested, - for example if the file ends between `offset` and `offset + length`. - - * `status()` - Use this to indicate either end of file (`STATUS_CODE.EOF`) - has been reached (`offset` is past the end of the file) or if an error - occurred while reading the requested part of the file. - -* **WRITE**(< _integer_ >reqID, < _Buffer_ >handle, < _integer_ >offset, < _Buffer_ >data) - - Respond using: - - * `status()` - Use this to indicate success/failure of the write to the file. - -* **FSTAT**(< _integer_ >reqID, < _Buffer_ >handle) - - Respond using one of the following: - - * `attrs()` - Use this to send the attributes for the requested - file/directory back to the client. - - * `status()` - Use this to indicate an error occurred while accessing the - file/directory. - -* **FSETSTAT**(< _integer_ >reqID, < _Buffer_ >handle, < _ATTRS_ >attrs) - - Respond using: - - * `status()` - Use this to indicates success/failure of the setting of the - given file/directory attributes. - -* **CLOSE**(< _integer_ >reqID, < _Buffer_ >handle) - - Respond using: - - * `status()` - Use this to indicate success (`STATUS_CODE.OK`) or failure of - the closing of the file identified by `handle`. - -* **OPENDIR**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `handle()` - This indicates a successful opening of the directory and - passes the given handle back to the client to use to refer to this open - directory for future operations (e.g. reading directory contents, closing). - - * `status()` - Use this to indicate a failure to open the requested - directory. - -* **READDIR**(< _integer_ >reqID, < _Buffer_ >handle) - - Respond using one of the following: - - * `name()` - Use this to send one or more directory listings for the open - directory back to the client. - - * `status()` - Use this to indicate either end of directory contents - (`STATUS_CODE.EOF`) or if an error occurred while reading the directory - contents. - -* **LSTAT**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `attrs()` - Use this to send the attributes for the requested - file/directory back to the client. - - * `status()` - Use this to indicate an error occurred while accessing the - file/directory. - -* **STAT**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `attrs()` - Use this to send the attributes for the requested - file/directory back to the client. - - * `status()` - Use this to indicate an error occurred while accessing the - file/directory. - -* **REMOVE**(< _integer_ >reqID, < _string_ >path) - - Respond using: - - * `status()` - Use this to indicate success/failure of the removal of the - file at `path`. - -* **RMDIR**(< _integer_ >reqID, < _string_ >path) - - Respond using: - - * `status()` - Use this to indicate success/failure of the removal of the - directory at `path`. - -* **REALPATH**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `name()` - Use this to respond with a normalized version of `path`. - No file/directory attributes are required to be sent in this response. - - * `status()` - Use this to indicate a failure in normalizing `path`. - -* **READLINK**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `name()` - Use this to respond with the target of the symlink at `path`. - No file/directory attributes are required to be sent in this response. - - * `status()` - Use this to indicate a failure in reading the symlink at - `path`. - -* **SETSTAT**(< _integer_ >reqID, < _string_ >path, < _ATTRS_ >attrs) - - Respond using: - - * `status()` - Use this to indicates success/failure of the setting of the - given file/directory attributes. - -* **MKDIR**(< _integer_ >reqID, < _string_ >path, < _ATTRS_ >attrs) - - Respond using: - - * `status()` - Use this to indicate success/failure of the creation of the - directory at `path`. - -* **RENAME**(< _integer_ >reqID, < _string_ >oldPath, < _string_ >newPath) - - Respond using: - - * `status()` - Use this to indicate success/failure of the renaming of the - file/directory at `oldPath` to `newPath`. - -* **SYMLINK**(< _integer_ >reqID, < _string_ >linkPath, < _string_ >targetPath) - - Respond using: - - * `status()` - Use this to indicate success/failure of the symlink creation. - - -Useful standalone data structures ---------------------------------- - -* **STATUS_CODE** - _object_ - Contains the various status codes (for use especially with `status()`): - - * `OK` - - * `EOF` - - * `NO_SUCH_FILE` - - * `PERMISSION_DENIED` - - * `FAILURE` - - * `BAD_MESSAGE` - - * `OP_UNSUPPORTED` - -* **OPEN_MODE** - _object_ - Contains the various open file flags: - - * `READ` - - * `WRITE` - - * `APPEND` - - * `CREAT` - - * `TRUNC` - - * `EXCL` - - -Useful standalone methods -------------------------- - -* **stringToFlags**(< _string_ >flagsStr) - _integer_ - Converts string flags (e.g. `'r'`, `'a+'`, etc.) to the appropriate `OPEN_MODE` flag mask. Returns `null` if conversion failed. - -* **flagsToString**(< _integer_ >flagsMask) - _string_ - Converts flag mask (e.g. number containing `OPEN_MODE` values) to the appropriate string value. Returns `null` if conversion failed. - - -SFTP methods ------------- - -* **(constructor)**(< _object_ >config[, < _string_ >remoteIdentRaw]) - Creates and returns a new SFTP instance. `remoteIdentRaw` can be the raw SSH identification string of the remote party. This is used to change internal behavior based on particular SFTP implementations. `config` can contain: - - * **server** - _boolean_ - Set to `true` to create an instance in server mode. **Default:** `false` - - * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none) - - - -**Client-only methods** - -* **fastGet**(< _string_ >remotePath, < _string_ >localPath[, < _object_ >options], < _function_ >callback) - _(void)_ - Downloads a file at `remotePath` to `localPath` using parallel reads for faster throughput. `options` can have the following properties: - - * **concurrency** - _integer_ - Number of concurrent reads **Default:** `64` - - * **chunkSize** - _integer_ - Size of each read in bytes **Default:** `32768` - - * **step** - _function_(< _integer_ >total_transferred, < _integer_ >chunk, < _integer_ >total) - Called every time a part of a file was transferred - - `callback` has 1 parameter: < _Error_ >err. - -* **fastPut**(< _string_ >localPath, < _string_ >remotePath[, < _object_ >options], < _function_ >callback) - _(void)_ - Uploads a file from `localPath` to `remotePath` using parallel reads for faster throughput. `options` can have the following properties: - - * **concurrency** - _integer_ - Number of concurrent reads **Default:** `64` - - * **chunkSize** - _integer_ - Size of each read in bytes **Default:** `32768` - - * **step** - _function_(< _integer_ >total_transferred, < _integer_ >chunk, < _integer_ >total) - Called every time a part of a file was transferred - - * **mode** - _mixed_ - Integer or string representing the file mode to set for the uploaded file. - - `callback` has 1 parameter: < _Error_ >err. - -* **createReadStream**(< _string_ >path[, < _object_ >options]) - _ReadStream_ - Returns a new readable stream for `path`. `options` has the following defaults: - - ```javascript - { flags: 'r', - encoding: null, - handle: null, - mode: 0o666, - autoClose: true - } - ``` - - `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`. - - If `autoClose` is false, then the file handle won't be closed, even if there's an error. It is your responsibility to close it and make sure there's no file handle leak. If `autoClose` is set to true (default behavior), on `error` or `end` the file handle will be closed automatically. - - An example to read the last 10 bytes of a file which is 100 bytes long: - - ```javascript - sftp.createReadStream('sample.txt', {start: 90, end: 99}); - ``` - -* **createWriteStream**(< _string_ >path[, < _object_ >options]) - _WriteStream_ - Returns a new writable stream for `path`. `options` has the following defaults: - - ```javascript - { - flags: 'w', - encoding: null, - mode: 0o666, - autoClose: true - } - ``` - - `options` may also include a `start` option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of 'r+' rather than the default mode 'w'. - - If 'autoClose' is set to false and you pipe to this stream, this stream will not automatically close after there is no more data upstream -- allowing future pipes and/or manual writes. - -* **open**(< _string_ >filename, < _string_ >flags, [< _mixed_ >attrs_mode, ]< _function_ >callback) - _(void)_ - Opens a file `filename` with `flags` with optional _ATTRS_ object or file mode `attrs_mode`. `flags` is any of the flags supported by `fs.open` (except sync flag). `callback` has 2 parameters: < _Error_ >err, < _Buffer_ >handle. - -* **close**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - Closes the resource associated with `handle` given by open() or opendir(). `callback` has 1 parameter: < _Error_ >err. - -* **read**(< _Buffer_ >handle, < _Buffer_ >buffer, < _integer_ >offset, < _integer_ >length, < _integer_ >position, < _function_ >callback) - _(void)_ - Reads `length` bytes from the resource associated with `handle` starting at `position` and stores the bytes in `buffer` starting at `offset`. `callback` has 4 parameters: < _Error_ >err, < _integer_ >bytesRead, < _Buffer_ >buffer (offset adjusted), < _integer_ >position. - -* **write**(< _Buffer_ >handle, < _Buffer_ >buffer, < _integer_ >offset, < _integer_ >length, < _integer_ >position, < _function_ >callback) - _(void)_ - Writes `length` bytes from `buffer` starting at `offset` to the resource associated with `handle` starting at `position`. `callback` has 1 parameter: < _Error_ >err. - -* **fstat**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - Retrieves attributes for the resource associated with `handle`. `callback` has 2 parameters: < _Error_ >err, < _Stats_ >stats. - -* **fsetstat**(< _Buffer_ >handle, < _ATTRS_ >attributes, < _function_ >callback) - _(void)_ - Sets the attributes defined in `attributes` for the resource associated with `handle`. `callback` has 1 parameter: < _Error_ >err. - -* **futimes**(< _Buffer_ >handle, < _mixed_ >atime, < _mixed_ >mtime, < _function_ >callback) - _(void)_ - Sets the access time and modified time for the resource associated with `handle`. `atime` and `mtime` can be Date instances or UNIX timestamps. `callback` has 1 parameter: < _Error_ >err. - -* **fchown**(< _Buffer_ >handle, < _integer_ >uid, < _integer_ >gid, < _function_ >callback) - _(void)_ - Sets the owner for the resource associated with `handle`. `callback` has 1 parameter: < _Error_ >err. - -* **fchmod**(< _Buffer_ >handle, < _mixed_ >mode, < _function_ >callback) - _(void)_ - Sets the mode for the resource associated with `handle`. `mode` can be an integer or a string containing an octal number. `callback` has 1 parameter: < _Error_ >err. - -* **opendir**(< _string_ >path, < _function_ >callback) - _(void)_ - Opens a directory `path`. `callback` has 2 parameters: < _Error_ >err, < _Buffer_ >handle. - -* **readdir**(< _mixed_ >location, < _function_ >callback) - _(void)_ - Retrieves a directory listing. `location` can either be a _Buffer_ containing a valid directory handle from opendir() or a _string_ containing the path to a directory. `callback` has 2 parameters: < _Error_ >err, < _mixed_ >list. `list` is an _Array_ of `{ filename: 'foo', longname: '....', attrs: {...} }` style objects (attrs is of type _ATTR_). If `location` is a directory handle, this function may need to be called multiple times until `list` is boolean false, which indicates that no more directory entries are available for that directory handle. - -* **unlink**(< _string_ >path, < _function_ >callback) - _(void)_ - Removes the file/symlink at `path`. `callback` has 1 parameter: < _Error_ >err. - -* **rename**(< _string_ >srcPath, < _string_ >destPath, < _function_ >callback) - _(void)_ - Renames/moves `srcPath` to `destPath`. `callback` has 1 parameter: < _Error_ >err. - -* **mkdir**(< _string_ >path, [< _ATTRS_ >attributes, ]< _function_ >callback) - _(void)_ - Creates a new directory `path`. `callback` has 1 parameter: < _Error_ >err. - -* **rmdir**(< _string_ >path, < _function_ >callback) - _(void)_ - Removes the directory at `path`. `callback` has 1 parameter: < _Error_ >err. - -* **stat**(< _string_ >path, < _function_ >callback) - _(void)_ - Retrieves attributes for `path`. `callback` has 2 parameter: < _Error_ >err, < _Stats_ >stats. - -* **lstat**(< _string_ >path, < _function_ >callback) - _(void)_ - Retrieves attributes for `path`. If `path` is a symlink, the link itself is stat'ed instead of the resource it refers to. `callback` has 2 parameters: < _Error_ >err, < _Stats_ >stats. - -* **setstat**(< _string_ >path, < _ATTRS_ >attributes, < _function_ >callback) - _(void)_ - Sets the attributes defined in `attributes` for `path`. `callback` has 1 parameter: < _Error_ >err. - -* **utimes**(< _string_ >path, < _mixed_ >atime, < _mixed_ >mtime, < _function_ >callback) - _(void)_ - Sets the access time and modified time for `path`. `atime` and `mtime` can be Date instances or UNIX timestamps. `callback` has 1 parameter: < _Error_ >err. - -* **chown**(< _string_ >path, < _integer_ >uid, < _integer_ >gid, < _function_ >callback) - _(void)_ - Sets the owner for `path`. `callback` has 1 parameter: < _Error_ >err. - -* **chmod**(< _string_ >path, < _mixed_ >mode, < _function_ >callback) - _(void)_ - Sets the mode for `path`. `mode` can be an integer or a string containing an octal number. `callback` has 1 parameter: < _Error_ >err. - -* **readlink**(< _string_ >path, < _function_ >callback) - _(void)_ - Retrieves the target for a symlink at `path`. `callback` has 2 parameters: < _Error_ >err, < _string_ >target. - -* **symlink**(< _string_ >targetPath, < _string_ >linkPath, < _function_ >callback) - _(void)_ - Creates a symlink at `linkPath` to `targetPath`. `callback` has 1 parameter: < _Error_ >err. - -* **realpath**(< _string_ >path, < _function_ >callback) - _(void)_ - Resolves `path` to an absolute path. `callback` has 2 parameters: < _Error_ >err, < _string_ >absPath. - -* **ext_openssh_rename**(< _string_ >srcPath, < _string_ >destPath, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX rename(3) from `srcPath` to `destPath`. `callback` has 1 parameter: < _Error_ >err. - -* **ext_openssh_statvfs**(< _string_ >path, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX statvfs(2) on `path`. `callback` has 2 parameters: < _Error_ >err, < _object_ >fsInfo. `fsInfo` contains the information as found in the [statvfs struct](http://linux.die.net/man/2/statvfs). - -* **ext_openssh_fstatvfs**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX fstatvfs(2) on open handle `handle`. `callback` has 2 parameters: < _Error_ >err, < _object_ >fsInfo. `fsInfo` contains the information as found in the [statvfs struct](http://linux.die.net/man/2/statvfs). - -* **ext_openssh_hardlink**(< _string_ >targetPath, < _string_ >linkPath, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX link(2) to create a hard link to `targetPath` at `linkPath`. `callback` has 1 parameter: < _Error_ >err. - -* **ext_openssh_fsync**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX fsync(3) on the open handle `handle`. `callback` has 1 parameter: < _Error_ >err. - - -**Server-only methods** - -* **status**(< _integer_ >reqID, < _integer_ >statusCode[, < _string_ >message]) - _(void)_ - Sends a status response for the request identified by `id`. - -* **handle**(< _integer_ >reqID, < _Buffer_ >handle) - _(void)_ - Sends a handle response for the request identified by `id`. `handle` must be less than 256 bytes and is an opaque value that could merely contain the value of a backing file descriptor or some other unique, custom value. - -* **data**(< _integer_ >reqID, < _mixed_ >data[, < _string_ >encoding]) - _(void)_ - Sends a data response for the request identified by `id`. `data` can be a _Buffer_ or _string_. If `data` is a string, `encoding` is the encoding of `data`. - -* **name**(< _integer_ >reqID, < _array_ >names) - _(void)_ - Sends a name response for the request identified by `id`. `names` must be an _array_ of _object_ where each _object_ can contain: - - * **filename** - _string_ - The entry's name. - - * **longname** - _string_ - This is the `ls -l`-style format for the entry (e.g. `-rwxr--r-- 1 bar bar 718 Dec 8 2009 foo`) - - * **attrs** - _ATTRS_ - This is an optional _ATTRS_ object that contains requested/available attributes for the entry. - -* **attrs**(< _integer_ >reqID, < _ATTRS_ >attrs) - _(void)_ - Sends an attrs response for the request identified by `id`. `attrs` contains the requested/available attributes. - - -ATTRS ------ - -An object with the following valid properties: - -* **mode** - _integer_ - Mode/permissions for the resource. - -* **uid** - _integer_ - User ID of the resource. - -* **gid** - _integer_ - Group ID of the resource. - -* **size** - _integer_ - Resource size in bytes. - -* **atime** - _integer_ - UNIX timestamp of the access time of the resource. - -* **mtime** - _integer_ - UNIX timestamp of the modified time of the resource. - -When supplying an ATTRS object to one of the SFTP methods: - -* `atime` and `mtime` can be either a Date instance or a UNIX timestamp. - -* `mode` can either be an integer or a string containing an octal number. - - -Stats ------ - -An object with the same attributes as an ATTRS object with the addition of the following methods: - -* `stats.isDirectory()` - -* `stats.isFile()` - -* `stats.isBlockDevice()` - -* `stats.isCharacterDevice()` - -* `stats.isSymbolicLink()` - -* `stats.isFIFO()` - -* `stats.isSocket()` diff --git a/reverse_engineering/node_modules/ssh2/examples/server-chat.js b/reverse_engineering/node_modules/ssh2/examples/server-chat.js deleted file mode 100644 index a82a955..0000000 --- a/reverse_engineering/node_modules/ssh2/examples/server-chat.js +++ /dev/null @@ -1,238 +0,0 @@ -// **BEFORE RUNNING THIS SCRIPT:** -// 1. The server portion is best run on non-Windows systems because they have -// terminfo databases which are needed to properly work with different -// terminal types of client connections -// 2. Install `blessed`: `npm install blessed` -// 3. Create a server host key in this same directory and name it `host.key` -'use strict'; - -const { readFileSync } = require('fs'); - -const blessed = require('blessed'); -const { Server } = require('ssh2'); - -const RE_SPECIAL = -// eslint-disable-next-line no-control-regex - /[\x00-\x1F\x7F]+|(?:\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])/g; -const MAX_MSG_LEN = 128; -const MAX_NAME_LEN = 10; -const PROMPT_NAME = `Enter a nickname to use (max ${MAX_NAME_LEN} chars): `; - -const users = []; - -function formatMessage(msg, output) { - output.parseTags = true; - msg = output._parseTags(msg); - output.parseTags = false; - return msg; -} - -function userBroadcast(msg, source) { - const sourceMsg = `> ${msg}`; - const name = `{cyan-fg}{bold}${source.name}{/}`; - msg = `: ${msg}`; - for (const user of users) { - const output = user.output; - if (source === user) - output.add(sourceMsg); - else - output.add(formatMessage(name, output) + msg); - } -} - -function localMessage(msg, source) { - const output = source.output; - output.add(formatMessage(msg, output)); -} - -function noop(v) {} - -new Server({ - hostKeys: [readFileSync('host.key')], -}, (client) => { - let stream; - let name; - - client.on('authentication', (ctx) => { - let nick = ctx.username; - let prompt = PROMPT_NAME; - let lowered; - - // Try to use username as nickname - if (nick.length > 0 && nick.length <= MAX_NAME_LEN) { - lowered = nick.toLowerCase(); - let ok = true; - for (const user of users) { - if (user.name.toLowerCase() === lowered) { - ok = false; - prompt = `That nickname is already in use.\n${PROMPT_NAME}`; - break; - } - } - if (ok) { - name = nick; - return ctx.accept(); - } - } else if (nick.length === 0) { - prompt = 'A nickname is required.\n' + PROMPT_NAME; - } else { - prompt = 'That nickname is too long.\n' + PROMPT_NAME; - } - - if (ctx.method !== 'keyboard-interactive') - return ctx.reject(['keyboard-interactive']); - - ctx.prompt(prompt, function retryPrompt(answers) { - if (answers.length === 0) - return ctx.reject(['keyboard-interactive']); - nick = answers[0]; - if (nick.length > MAX_NAME_LEN) { - return ctx.prompt(`That nickname is too long.\n${PROMPT_NAME}`, - retryPrompt); - } else if (nick.length === 0) { - return ctx.prompt(`A nickname is required.\n${PROMPT_NAME}`, - retryPrompt); - } - lowered = nick.toLowerCase(); - for (const user of users) { - if (user.name.toLowerCase() === lowered) { - return ctx.prompt(`That nickname is already in use.\n${PROMPT_NAME}`, - retryPrompt); - } - } - name = nick; - ctx.accept(); - }); - }).on('ready', () => { - let rows; - let cols; - let term; - client.once('session', (accept, reject) => { - accept().once('pty', (accept, reject, info) => { - rows = info.rows; - cols = info.cols; - term = info.term; - accept && accept(); - }).on('window-change', (accept, reject, info) => { - rows = info.rows; - cols = info.cols; - if (stream) { - stream.rows = rows; - stream.columns = cols; - stream.emit('resize'); - } - accept && accept(); - }).once('shell', (accept, reject) => { - stream = accept(); - users.push(stream); - - stream.name = name; - stream.rows = rows || 24; - stream.columns = cols || 80; - stream.isTTY = true; - stream.setRawMode = noop; - stream.on('error', noop); - - const screen = new blessed.screen({ - autoPadding: true, - smartCSR: true, - program: new blessed.program({ - input: stream, - output: stream - }), - terminal: term || 'ansi' - }); - - screen.title = 'SSH Chatting as ' + name; - // Disable local echo - screen.program.attr('invisible', true); - - const output = stream.output = new blessed.log({ - screen: screen, - top: 0, - left: 0, - width: '100%', - bottom: 2, - scrollOnInput: true - }); - screen.append(output); - - screen.append(new blessed.box({ - screen: screen, - height: 1, - bottom: 1, - left: 0, - width: '100%', - type: 'line', - ch: '=' - })); - - const input = new blessed.textbox({ - screen: screen, - bottom: 0, - height: 1, - width: '100%', - inputOnFocus: true - }); - screen.append(input); - - input.focus(); - - // Local greetings - localMessage('{blue-bg}{white-fg}{bold}Welcome to SSH Chat!{/}\n' - + 'There are {bold}' - + (users.length - 1) - + '{/} other user(s) connected.\n' - + 'Type /quit or /exit to exit the chat.', - stream); - - // Let everyone else know that this user just joined - for (const user of users) { - const output = user.output; - if (user === stream) - continue; - output.add(formatMessage('{green-fg}*** {bold}', output) - + name - + formatMessage('{/bold} has joined the chat{/}', output)); - } - - screen.render(); - // XXX This fake resize event is needed for some terminals in order to - // have everything display correctly - screen.program.emit('resize'); - - // Read a line of input from the user - input.on('submit', (line) => { - input.clearValue(); - screen.render(); - if (!input.focused) - input.focus(); - line = line.replace(RE_SPECIAL, '').trim(); - if (line.length > MAX_MSG_LEN) - line = line.substring(0, MAX_MSG_LEN); - if (line.length > 0) { - if (line === '/quit' || line === '/exit') - stream.end(); - else - userBroadcast(line, stream); - } - }); - }); - }); - }).on('close', () => { - if (stream !== undefined) { - users.splice(users.indexOf(stream), 1); - // Let everyone else know that this user just left - for (const user of users) { - const output = user.output; - output.add(formatMessage('{magenta-fg}*** {bold}', output) - + name - + formatMessage('{/bold} has left the chat{/}', output)); - } - } - }).on('error', (err) => { - // Ignore errors - }); -}).listen(0, function() { - console.log('Listening on port ' + this.address().port); -}); diff --git a/reverse_engineering/node_modules/ssh2/examples/sftp-server-download-only.js b/reverse_engineering/node_modules/ssh2/examples/sftp-server-download-only.js deleted file mode 100644 index d4ae4c5..0000000 --- a/reverse_engineering/node_modules/ssh2/examples/sftp-server-download-only.js +++ /dev/null @@ -1,134 +0,0 @@ -'use strict'; - -const { timingSafeEqual } = require('crypto'); -const { constants, readFileSync } = require('fs'); - -const { Server, sftp: { OPEN_MODE, STATUS_CODE } } = require('ssh2'); - -const allowedUser = Buffer.from('foo'); -const allowedPassword = Buffer.from('bar'); - -function checkValue(input, allowed) { - const autoReject = (input.length !== allowed.length); - if (autoReject) { - // Prevent leaking length information by always making a comparison with the - // same input when lengths don't match what we expect ... - allowed = input; - } - const isMatch = timingSafeEqual(input, allowed); - return (!autoReject && isMatch); -} - -new Server({ - hostKeys: [readFileSync('host.key')] -}, (client) => { - console.log('Client connected!'); - - client.on('authentication', (ctx) => { - let allowed = true; - if (!checkValue(Buffer.from(ctx.username), allowedUser)) - allowed = false; - - switch (ctx.method) { - case 'password': - if (!checkValue(Buffer.from(ctx.password), allowedPassword)) - return ctx.reject(); - break; - default: - return ctx.reject(); - } - - if (allowed) - ctx.accept(); - else - ctx.reject(); - }).on('ready', () => { - console.log('Client authenticated!'); - - client.on('session', (accept, reject) => { - const session = accept(); - session.on('sftp', (accept, reject) => { - console.log('Client SFTP session'); - - const openFiles = new Map(); - let handleCount = 0; - const sftp = accept(); - sftp.on('OPEN', (reqid, filename, flags, attrs) => { - // Only allow opening /tmp/foo.txt for writing - if (filename !== '/tmp/foo.txt' || !(flags & OPEN_MODE.READ)) - return sftp.status(reqid, STATUS_CODE.FAILURE); - - // Create a fake handle to return to the client, this could easily - // be a real file descriptor number for example if actually opening - // the file on the disk - const handle = Buffer.alloc(4); - openFiles.set(handleCount, { read: false }); - handle.writeUInt32BE(handleCount++, 0, true); - - console.log('Opening file for read'); - sftp.handle(reqid, handle); - }).on('READ', (reqid, handle, offset, length) => { - let fnum; - if (handle.length !== 4 - || !openFiles.has(fnum = handle.readUInt32BE(0, true))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - // Fake the read - const state = openFiles.get(fnum); - if (state.read) { - sftp.status(reqid, STATUS_CODE.EOF); - } else { - state.read = true; - - console.log( - 'Read from file at offset %d, length %d', offset, length - ); - sftp.data(reqid, 'bar'); - } - }).on('CLOSE', (reqid, handle) => { - let fnum; - if (handle.length !== 4 - || !openFiles.has(fnum = handle.readUInt32BE(0))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - openFiles.delete(fnum); - - console.log('Closing file'); - sftp.status(reqid, STATUS_CODE.OK); - }).on('REALPATH', function(reqid, path) { - const name = [{ - filename: '/tmp/foo.txt', - longname: '-rwxrwxrwx 1 foo foo 3 Dec 8 2009 foo.txt', - attrs: {} - }]; - sftp.name(reqid, name); - }).on('STAT', onSTAT) - .on('LSTAT', onSTAT); - - function onSTAT(reqid, path) { - if (path !== '/tmp/foo.txt') - return sftp.status(reqid, STATUS_CODE.FAILURE); - - let mode = constants.S_IFREG; // Regular file - mode |= constants.S_IRWXU; // Read, write, execute for user - mode |= constants.S_IRWXG; // Read, write, execute for group - mode |= constants.S_IRWXO; // Read, write, execute for other - sftp.attrs(reqid, { - mode: mode, - uid: 0, - gid: 0, - size: 3, - atime: Date.now(), - mtime: Date.now(), - }); - } - }); - }); - }).on('close', () => { - console.log('Client disconnected'); - }); -}).listen(0, '127.0.0.1', function() { - console.log(`Listening on port ${this.address().port}`); -}); diff --git a/reverse_engineering/node_modules/ssh2/install.js b/reverse_engineering/node_modules/ssh2/install.js deleted file mode 100644 index e536366..0000000 --- a/reverse_engineering/node_modules/ssh2/install.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const { spawnSync } = require('child_process'); - -// Attempt to build the bundled optional binding -const result = spawnSync('node-gyp', [ - `--target=${process.version}`, - 'rebuild' -], { - cwd: 'lib/protocol/crypto', - encoding: 'utf8', - shell: true, - stdio: 'inherit', - windowsHide: true, -}); -if (result.error || result.status !== 0) - console.log('Failed to build optional crypto binding'); -else - console.log('Succeeded in building optional crypto binding'); -process.exit(0); diff --git a/reverse_engineering/node_modules/ssh2/lib/Channel.js b/reverse_engineering/node_modules/ssh2/lib/Channel.js deleted file mode 100644 index 0bf5553..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/Channel.js +++ /dev/null @@ -1,294 +0,0 @@ -'use strict'; - -const { - Duplex: DuplexStream, - Readable: ReadableStream, - Writable: WritableStream, -} = require('stream'); - -const { - CHANNEL_EXTENDED_DATATYPE: { STDERR }, -} = require('./protocol/constants.js'); -const { bufferSlice } = require('./protocol/utils.js'); - -const PACKET_SIZE = 32 * 1024; -const MAX_WINDOW = 2 * 1024 * 1024; -const WINDOW_THRESHOLD = MAX_WINDOW / 2; - -class ClientStderr extends ReadableStream { - constructor(channel, streamOpts) { - super(streamOpts); - - this._channel = channel; - } - _read(n) { - if (this._channel._waitChanDrain) { - this._channel._waitChanDrain = false; - if (this._channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this._channel); - } - } -} - -class ServerStderr extends WritableStream { - constructor(channel) { - super({ highWaterMark: MAX_WINDOW }); - - this._channel = channel; - } - - _write(data, encoding, cb) { - const channel = this._channel; - const protocol = channel._client._protocol; - const outgoing = channel.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelExtData(id, data, STDERR); - else - protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); - - p += sliceLen; - window -= sliceLen; - } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - channel._waitWindow = true; - if (p > 0) - channel._chunkErr = bufferSlice(data, p, len); - else - channel._chunkErr = data; - channel._chunkcbErr = cb; - return; - } - - cb(); - } -} - -class Channel extends DuplexStream { - constructor(client, info, opts) { - const streamOpts = { - highWaterMark: MAX_WINDOW, - allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), - emitClose: false, - }; - super(streamOpts); - this.allowHalfOpen = streamOpts.allowHalfOpen; - - const server = !!(opts && opts.server); - - this.server = server; - this.type = info.type; - this.subtype = undefined; - - /* - incoming and outgoing contain these properties: - { - id: undefined, - window: undefined, - packetSize: undefined, - state: 'closed' - } - */ - this.incoming = info.incoming; - this.outgoing = info.outgoing; - this._callbacks = []; - - this._client = client; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - - this.stdin = this.stdout = this; - - if (server) - this.stderr = new ServerStderr(this); - else - this.stderr = new ClientStderr(this, streamOpts); - - // Outgoing data - this._waitWindow = false; // SSH-level backpressure - - // Incoming data - this._waitChanDrain = false; // Channel Readable side backpressure - - this._chunk = undefined; - this._chunkcb = undefined; - this._chunkErr = undefined; - this._chunkcbErr = undefined; - - this.on('finish', onFinish) - .on('prefinish', onFinish); // For node v0.11+ - - this.on('end', onEnd).on('close', onEnd); - } - - _read(n) { - if (this._waitChanDrain) { - this._waitChanDrain = false; - if (this.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this); - } - } - - _write(data, encoding, cb) { - const protocol = this._client._protocol; - const outgoing = this.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelData(id, data); - else - protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); - - p += sliceLen; - window -= sliceLen; - } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - this._waitWindow = true; - if (p > 0) - this._chunk = bufferSlice(data, p, len); - else - this._chunk = data; - this._chunkcb = cb; - return; - } - - cb(); - } - - eof() { - if (this.outgoing.state === 'open') { - this.outgoing.state = 'eof'; - this._client._protocol.channelEOF(this.outgoing.id); - } - } - - close() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._client._protocol.channelClose(this.outgoing.id); - } - } - - destroy() { - this.end(); - this.close(); - } - - // Session type-specific methods ============================================= - setWindow(rows, cols, height, width) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && (this.subtype === 'shell' || this.subtype === 'exec') - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.windowChange(this.outgoing.id, - rows, - cols, - height, - width); - } - } - - signal(signalName) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.signal(this.outgoing.id, signalName); - } - } - - exit(statusOrSignal, coreDumped, msg) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - if (typeof statusOrSignal === 'number') { - this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); - } else { - this._client._protocol.exitSignal(this.outgoing.id, - statusOrSignal, - coreDumped, - msg); - } - } - } - -} - -function onFinish() { - this.eof(); - if (this.server || !this.allowHalfOpen) - this.close(); - this.writable = false; -} - -function onEnd() { - this.readable = false; -} - -function windowAdjust(self) { - if (self.outgoing.state === 'closed') - return; - const amt = MAX_WINDOW - self.incoming.window; - if (amt <= 0) - return; - self.incoming.window += amt; - self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); -} - -module.exports = { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/agent.js b/reverse_engineering/node_modules/ssh2/lib/agent.js deleted file mode 100644 index bb495d1..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/agent.js +++ /dev/null @@ -1,1123 +0,0 @@ -'use strict'; - -const { Socket } = require('net'); -const { Duplex } = require('stream'); -const { resolve } = require('path'); -const { readFile } = require('fs'); -const { execFile, spawn } = require('child_process'); - -const { isParsedKey, parseKey } = require('./protocol/keyParser.js'); - -const { - makeBufferParser, - readUInt32BE, - writeUInt32BE, - writeUInt32LE, -} = require('./protocol/utils.js'); - -function once(cb) { - let called = false; - return (...args) => { - if (called) - return; - called = true; - cb(...args); - }; -} - -function concat(buf1, buf2) { - const combined = Buffer.allocUnsafe(buf1.length + buf2.length); - buf1.copy(combined, 0); - buf2.copy(combined, buf1.length); - return combined; -} - -function noop() {} - -const EMPTY_BUF = Buffer.alloc(0); - -const binaryParser = makeBufferParser(); - -class BaseAgent { - getIdentities(cb) { - cb(new Error('Missing getIdentities() implementation')); - } - sign(pubKey, data, options, cb) { - if (typeof options === 'function') - cb = options; - cb(new Error('Missing sign() implementation')); - } -} - -class OpenSSHAgent extends BaseAgent { - constructor(socketPath) { - super(); - this.socketPath = socketPath; - } - - getStream(cb) { - cb = once(cb); - const sock = new Socket(); - sock.on('connect', () => { - cb(null, sock); - }); - sock.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - sock.connect(this.socketPath); - - function onFail() { - try { - sock.destroy(); - } catch {} - - cb(new Error('Failed to connect to agent')); - } - } - - getIdentities(cb) { - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to retrieve identities from agent'); - cb(err); - } - - if (err) - return onFail(err); - - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - - protocol.getIdentities((err, keys) => { - if (err) - return onFail(err); - try { - stream.destroy(); - } catch {} - cb(null, keys); - }); - }); - } - - sign(pubKey, data, options, cb) { - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } - - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to sign data with agent'); - cb(err); - } - - if (err) - return onFail(err); - - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - - protocol.sign(pubKey, data, options, (err, sig) => { - if (err) - return onFail(err); - - try { - stream.destroy(); - } catch {} - - cb(null, sig); - }); - }); - } -} - -const PageantAgent = (() => { - const RET_ERR_BADARGS = 10; - const RET_ERR_UNAVAILABLE = 11; - const RET_ERR_NOMAP = 12; - const RET_ERR_BINSTDIN = 13; - const RET_ERR_BINSTDOUT = 14; - const RET_ERR_BADLEN = 15; - - const EXEPATH = resolve(__dirname, '..', 'util/pagent.exe'); - const ERROR = { - [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), - [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), - [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), - [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), - [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), - [RET_ERR_BADLEN]: - new Error('pagent.exe did not get expected input payload'), - }; - - function destroy(stream) { - stream.buffer = null; - if (stream.proc) { - stream.proc.kill(); - stream.proc = undefined; - } - } - - class PageantSocket extends Duplex { - constructor() { - super(); - this.proc = undefined; - this.buffer = null; - } - _read(n) {} - _write(data, encoding, cb) { - if (this.buffer === null) { - this.buffer = data; - } else { - const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); - this.buffer.copy(newBuffer, 0); - data.copy(newBuffer, this.buffer.length); - this.buffer = newBuffer; - } - // Wait for at least all length bytes - if (this.buffer.length < 4) - return cb(); - - const len = readUInt32BE(this.buffer, 0); - // Make sure we have a full message before querying pageant - if ((this.buffer.length - 4) < len) - return cb(); - - data = this.buffer.slice(0, 4 + len); - if (this.buffer.length > (4 + len)) - return cb(new Error('Unexpected multiple agent requests')); - this.buffer = null; - - let error; - const proc = this.proc = spawn(EXEPATH, [ data.length ]); - proc.stdout.on('data', (data) => { - this.push(data); - }); - proc.on('error', (err) => { - error = err; - cb(error); - }); - proc.on('close', (code) => { - this.proc = undefined; - if (!error) { - if (error = ERROR[code]) - return cb(error); - cb(); - } - }); - proc.stdin.end(data); - } - _final(cb) { - destroy(this); - cb(); - } - _destroy(err, cb) { - destroy(this); - cb(); - } - } - - return class PageantAgent extends OpenSSHAgent { - getStream(cb) { - cb(null, new PageantSocket()); - } - }; -})(); - -const CygwinAgent = (() => { - const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; - - return class CygwinAgent extends OpenSSHAgent { - getStream(cb) { - cb = once(cb); - - // The cygwin ssh-agent connection process looks like this: - // 1. Read the "socket" as a file to get the underlying TCP port and a - // special "secret" that must be sent to the TCP server. - // 2. Connect to the server listening on localhost at the TCP port. - // 3. Send the "secret" to the server. - // 4. The server sends back the same "secret". - // 5. Send three 32-bit integer values of zero. This is ordinarily the - // pid, uid, and gid of this process, but cygwin will actually - // send us the correct values as a response. - // 6. The server sends back the pid, uid, gid. - // 7. Disconnect. - // 8. Repeat steps 2-6, except send the received pid, uid, and gid in - // step 5 instead of zeroes. - // 9. Connection is ready to be used. - - let socketPath = this.socketPath; - let triedCygpath = false; - readFile(socketPath, function readCygsocket(err, data) { - if (err) { - if (triedCygpath) - return cb(new Error('Invalid cygwin unix socket path')); - - // Try using `cygpath` to convert a possible *nix-style path to the - // real Windows path before giving up ... - execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { - if (err || stdout.length === 0) - return cb(new Error('Invalid cygwin unix socket path')); - - triedCygpath = true; - socketPath = stdout.toString().replace(/[\r\n]/g, ''); - readFile(socketPath, readCygsocket); - }); - return; - } - - const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); - if (!m) - return cb(new Error('Malformed cygwin unix socket file')); - - let state; - let bc = 0; - let isRetrying = false; - const inBuf = []; - let sock; - - // Use 0 for pid, uid, and gid to ensure we get an error and also - // a valid uid and gid from cygwin so that we don't have to figure it - // out ourselves - let credsBuf = Buffer.alloc(12); - - // Parse cygwin unix socket file contents - const port = parseInt(m[1], 10); - const secret = m[2].replace(/-/g, ''); - const secretBuf = Buffer.allocUnsafe(16); - for (let i = 0, j = 0; j < 32; ++i, j += 2) - secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); - - // Convert to host order (always LE for Windows) - for (let i = 0; i < 16; i += 4) - writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); - - tryConnect(); - - function _onconnect() { - bc = 0; - state = 'secret'; - sock.write(secretBuf); - } - - function _ondata(data) { - bc += data.length; - - if (state === 'secret') { - // The secret we sent is echoed back to us by cygwin, not sure of - // the reason for that, but we ignore it nonetheless ... - if (bc === 16) { - bc = 0; - state = 'creds'; - sock.write(credsBuf); - } - return; - } - - if (state === 'creds') { - // If this is the first attempt, make sure to gather the valid - // uid and gid for our next attempt - if (!isRetrying) - inBuf.push(data); - - if (bc === 12) { - sock.removeListener('connect', _onconnect); - sock.removeListener('data', _ondata); - sock.removeListener('error', onFail); - sock.removeListener('end', onFail); - sock.removeListener('close', onFail); - - if (isRetrying) - return cb(null, sock); - - isRetrying = true; - credsBuf = Buffer.concat(inBuf); - writeUInt32LE(credsBuf, process.pid, 0); - sock.on('error', () => {}); - sock.destroy(); - - tryConnect(); - } - } - } - - function onFail() { - cb(new Error('Problem negotiating cygwin unix socket security')); - } - - function tryConnect() { - sock = new Socket(); - sock.on('connect', _onconnect); - sock.on('data', _ondata); - sock.on('error', onFail); - sock.on('end', onFail); - sock.on('close', onFail); - sock.connect(port); - } - }); - } - }; -})(); - -// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes -// being interchangeable -const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; -function createAgent(path) { - if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { - return (path === 'pageant' - ? new PageantAgent() - : new CygwinAgent(path)); - } - return new OpenSSHAgent(path); -} - -const AgentProtocol = (() => { - // Client->Server messages - const SSH_AGENTC_REQUEST_IDENTITIES = 11; - const SSH_AGENTC_SIGN_REQUEST = 13; - // const SSH_AGENTC_ADD_IDENTITY = 17; - // const SSH_AGENTC_REMOVE_IDENTITY = 18; - // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; - // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; - // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; - // const SSH_AGENTC_LOCK = 22; - // const SSH_AGENTC_UNLOCK = 23; - // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; - // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; - // const SSH_AGENTC_EXTENSION = 27; - // Server->Client messages - const SSH_AGENT_FAILURE = 5; - // const SSH_AGENT_SUCCESS = 6; - const SSH_AGENT_IDENTITIES_ANSWER = 12; - const SSH_AGENT_SIGN_RESPONSE = 14; - // const SSH_AGENT_EXTENSION_FAILURE = 28; - - // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; - // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; - // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; - - const SSH_AGENT_RSA_SHA2_256 = (1 << 1); - const SSH_AGENT_RSA_SHA2_512 = (1 << 2); - - const ROLE_CLIENT = 0; - const ROLE_SERVER = 1; - - // Ensures that responses get sent back in the same order the requests were - // received - function processResponses(protocol) { - let ret; - while (protocol[SYM_REQS].length) { - const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; - if (nextResponse === undefined) - break; - - protocol[SYM_REQS].shift(); - ret = protocol.push(nextResponse); - } - return ret; - } - - const SYM_TYPE = Symbol('Inbound Request Type'); - const SYM_RESP = Symbol('Inbound Request Response'); - const SYM_CTX = Symbol('Inbound Request Context'); - class AgentInboundRequest { - constructor(type, ctx) { - this[SYM_TYPE] = type; - this[SYM_RESP] = undefined; - this[SYM_CTX] = ctx; - } - hasResponded() { - return (this[SYM_RESP] !== undefined); - } - getType() { - return this[SYM_TYPE]; - } - getContext() { - return this[SYM_CTX]; - } - } - function respond(protocol, req, data) { - req[SYM_RESP] = data; - return processResponses(protocol); - } - - function cleanup(protocol) { - protocol[SYM_BUFFER] = null; - if (protocol[SYM_MODE] === ROLE_CLIENT) { - const reqs = protocol[SYM_REQS]; - if (reqs && reqs.length) { - protocol[SYM_REQS] = []; - for (const req of reqs) - req.cb(new Error('No reply from server')); - } - } - - // Node streams hackery to make streams do the "right thing" - try { - protocol.end(); - } catch {} - setImmediate(() => { - if (!protocol[SYM_ENDED]) - protocol.emit('end'); - if (!protocol[SYM_CLOSED]) - protocol.emit('close'); - }); - } - - function onClose() { - this[SYM_CLOSED] = true; - } - - function onEnd() { - this[SYM_ENDED] = true; - } - - const SYM_REQS = Symbol('Requests'); - const SYM_MODE = Symbol('Agent Protocol Role'); - const SYM_BUFFER = Symbol('Agent Protocol Buffer'); - const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); - const SYM_CLOSED = Symbol('Agent Protocol Closed'); - const SYM_ENDED = Symbol('Agent Protocol Ended'); - // Implementation based on: - // https://tools.ietf.org/html/draft-miller-ssh-agent-04 - return class AgentProtocol extends Duplex { - /* - Notes: - - `constraint` type consists of: - byte constraint_type - byte[] constraint_data - where `constraint_type` is one of: - * SSH_AGENT_CONSTRAIN_LIFETIME - - `constraint_data` consists of: - uint32 seconds - * SSH_AGENT_CONSTRAIN_CONFIRM - - `constraint_data` N/A - * SSH_AGENT_CONSTRAIN_EXTENSION - - `constraint_data` consists of: - string extension name - byte[] extension-specific details - */ - - constructor(isClient) { - super({ autoDestroy: true, emitClose: false }); - this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); - this[SYM_REQS] = []; - this[SYM_BUFFER] = null; - this[SYM_MSGLEN] = -1; - this.once('end', onEnd); - this.once('close', onClose); - } - - _read(n) {} - - _write(data, encoding, cb) { - /* - Messages are of the format: - uint32 message length - byte message type - byte[message length - 1] message contents - */ - if (this[SYM_BUFFER] === null) - this[SYM_BUFFER] = data; - else - this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); - - let buffer = this[SYM_BUFFER]; - let bufferLen = buffer.length; - - let p = 0; - while (p < bufferLen) { - // Wait for length + type - if (bufferLen < 5) - break; - - if (this[SYM_MSGLEN] === -1) - this[SYM_MSGLEN] = readUInt32BE(buffer, p); - - // Check if we have the entire message - if (bufferLen < (4 + this[SYM_MSGLEN])) - break; - - const msgType = buffer[p += 4]; - ++p; - - if (this[SYM_MODE] === ROLE_CLIENT) { - if (this[SYM_REQS].length === 0) - return cb(new Error('Received unexpected message from server')); - - const req = this[SYM_REQS].shift(); - - switch (msgType) { - case SSH_AGENT_FAILURE: - req.cb(new Error('Agent responded with failure')); - break; - case SSH_AGENT_IDENTITIES_ANSWER: { - if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - binaryParser.init(buffer, p); - - const numKeys = binaryParser.readUInt32BE(); - - if (numKeys === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const keys = []; - for (let i = 0; i < numKeys; ++i) { - let pubKey = binaryParser.readString(); - if (pubKey === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const comment = binaryParser.readString(true); - if (comment === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - pubKey = parseKey(pubKey); - // We continue parsing the packet if we encounter an error - // in case the error is due to the key being an unsupported - // type - if (pubKey instanceof Error) - continue; - - pubKey.comment = pubKey.comment || comment; - - keys.push(pubKey); - } - p = binaryParser.pos(); - binaryParser.clear(); - - req.cb(null, keys); - break; - } - case SSH_AGENT_SIGN_RESPONSE: { - if (req.type !== SSH_AGENTC_SIGN_REQUEST) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - binaryParser.init(buffer, p); - let signature = binaryParser.readString(); - p = binaryParser.pos(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed agent response')); - - // We strip the algorithm from OpenSSH's output and assume it's - // using the algorithm we specified. This makes it easier on - // custom Agent implementations so they don't have to construct - // the correct binary format for a (OpenSSH-style) signature. - - // TODO: verify signature type based on key and options used - // during initial sign request - binaryParser.init(signature, 0); - binaryParser.readString(true); - signature = binaryParser.readString(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed OpenSSH signature format')); - - req.cb(null, signature); - break; - } - default: - return cb( - new Error('Agent responded with unsupported message type') - ); - } - } else { - switch (msgType) { - case SSH_AGENTC_REQUEST_IDENTITIES: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - this.emit('identities', req); - break; - } - case SSH_AGENTC_SIGN_REQUEST: { - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - binaryParser.init(buffer, p); - let pubKey = binaryParser.readString(); - const data = binaryParser.readString(); - const flagsVal = binaryParser.readUInt32BE(); - p = binaryParser.pos(); - binaryParser.clear(); - if (flagsVal === undefined) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - const flags = { - hash: undefined, - }; - let ctx; - if (pubKey.type === 'ssh-rsa') { - if (flagsVal & SSH_AGENT_RSA_SHA2_256) { - ctx = 'rsa-sha2-256'; - flags.hash = 'sha256'; - } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { - ctx = 'rsa-sha2-512'; - flags.hash = 'sha512'; - } - } - if (ctx === undefined) - ctx = pubKey.type; - - const req = new AgentInboundRequest(msgType, ctx); - this[SYM_REQS].push(req); - - this.emit('sign', req, pubKey, data, flags); - break; - } - default: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.failureReply(req); - } - } - } - - // Get ready for next message - this[SYM_MSGLEN] = -1; - if (p === bufferLen) { - // Nothing left to process for now - this[SYM_BUFFER] = null; - break; - } else { - this[SYM_BUFFER] = buffer = buffer.slice(p); - bufferLen = buffer.length; - p = 0; - } - } - - cb(); - } - - _destroy(err, cb) { - cleanup(this); - cb(); - } - - _final(cb) { - cleanup(this); - cb(); - } - - // Client->Server messages ================================================= - sign(pubKey, data, options, cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } - - let flags = 0; - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid public key argument'); - - if (pubKey.type === 'ssh-rsa' && options) { - switch (options.hash) { - case 'sha256': - flags = SSH_AGENT_RSA_SHA2_256; - break; - case 'sha512': - flags = SSH_AGENT_RSA_SHA2_512; - break; - } - } - pubKey = pubKey.getPublicSSH(); - - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - const type = SSH_AGENTC_SIGN_REQUEST; - const keyLen = pubKey.length; - const dataLen = data.length; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - writeUInt32BE(buf, keyLen, ++p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, dataLen, p += keyLen); - data.copy(buf, p += 4); - - writeUInt32BE(buf, flags, p += dataLen); - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); - } - getIdentities(cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - const type = SSH_AGENTC_REQUEST_IDENTITIES; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); - } - - // Server->Client messages ================================================= - failureReply(req) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_FAILURE; - - return respond(this, req, buf); - } - getIdentitiesReply(req, keys) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) - throw new Error('Invalid response to request'); - - if (!Array.isArray(keys)) - throw new Error('Keys argument must be an array'); - - let totalKeysLen = 4; // Include `nkeys` size - - const newKeys = []; - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - if (typeof entry !== 'object' || entry === null) - throw new Error(`Invalid key entry: ${entry}`); - - let pubKey; - let comment; - if (isParsedKey(entry)) { - pubKey = entry; - } else if (isParsedKey(entry.pubKey)) { - pubKey = entry.pubKey; - } else { - if (typeof entry.pubKey !== 'object' || entry.pubKey === null) - continue; - ({ pubKey, comment } = entry.pubKey); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; // TODO: add debug output - } - comment = pubKey.comment || comment; - pubKey = pubKey.getPublicSSH(); - - totalKeysLen += 4 + pubKey.length; - - if (comment && typeof comment === 'string') - comment = Buffer.from(comment); - else if (!Buffer.isBuffer(comment)) - comment = EMPTY_BUF; - - totalKeysLen += 4 + comment.length; - - newKeys.push({ pubKey, comment }); - } - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; - - writeUInt32BE(buf, newKeys.length, ++p); - p += 4; - for (let i = 0; i < newKeys.length; ++i) { - const { pubKey, comment } = newKeys[i]; - - writeUInt32BE(buf, pubKey.length, p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, comment.length, p += pubKey.length); - p += 4; - if (comment.length) { - comment.copy(buf, p); - p += comment.length; - } - } - - return respond(this, req, buf); - } - signReply(req, signature) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) - throw new Error('Invalid response to request'); - - if (!Buffer.isBuffer(signature)) - throw new Error('Signature argument must be a Buffer'); - - if (signature.length === 0) - throw new Error('Signature argument must be non-empty'); - - /* - OpenSSH agent signatures are encoded as: - - string signature format identifier (as specified by the - public key/certificate format) - byte[n] signature blob in format specific encoding. - - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 - types - */ - - let p = 0; - const sigFormat = req.getContext(); - const sigFormatLen = Buffer.byteLength(sigFormat); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length - ); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; - - writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); - writeUInt32BE(buf, sigFormatLen, p += 4); - buf.utf8Write(sigFormat, p += 4, sigFormatLen); - writeUInt32BE(buf, signature.length, p += sigFormatLen); - signature.copy(buf, p += 4); - - return respond(this, req, buf); - } - }; -})(); - -const SYM_AGENT = Symbol('Agent'); -const SYM_AGENT_KEYS = Symbol('Agent Keys'); -const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); -const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); -class AgentContext { - constructor(agent) { - if (typeof agent === 'string') - agent = createAgent(agent); - else if (!isAgent(agent)) - throw new Error('Invalid agent argument'); - this[SYM_AGENT] = agent; - this[SYM_AGENT_KEYS] = null; - this[SYM_AGENT_KEYS_IDX] = -1; - this[SYM_AGENT_CBS] = null; - } - init(cb) { - if (typeof cb !== 'function') - cb = noop; - - if (this[SYM_AGENT_KEYS] === null) { - if (this[SYM_AGENT_CBS] === null) { - this[SYM_AGENT_CBS] = [cb]; - - const doCbs = (...args) => { - process.nextTick(() => { - const cbs = this[SYM_AGENT_CBS]; - this[SYM_AGENT_CBS] = null; - for (const cb of cbs) - cb(...args); - }); - }; - - this[SYM_AGENT].getIdentities(once((err, keys) => { - if (err) - return doCbs(err); - - if (!Array.isArray(keys)) { - return doCbs(new Error( - 'Agent implementation failed to provide keys' - )); - } - - const newKeys = []; - for (let key of keys) { - key = parseKey(key); - if (key instanceof Error) { - // TODO: add debug output - continue; - } - newKeys.push(key); - } - - this[SYM_AGENT_KEYS] = newKeys; - this[SYM_AGENT_KEYS_IDX] = -1; - doCbs(); - })); - } else { - this[SYM_AGENT_CBS].push(cb); - } - } else { - process.nextTick(cb); - } - } - nextKey() { - if (this[SYM_AGENT_KEYS] === null - || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return false; - } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - currentKey() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return null; - } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - pos() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return -1; - } - - return this[SYM_AGENT_KEYS_IDX]; - } - reset() { - this[SYM_AGENT_KEYS_IDX] = -1; - } - - sign(...args) { - this[SYM_AGENT].sign(...args); - } -} - -function isAgent(val) { - return (val instanceof BaseAgent); -} - -module.exports = { - AgentContext, - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - isAgent, - OpenSSHAgent, - PageantAgent, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/client.js b/reverse_engineering/node_modules/ssh2/lib/client.js deleted file mode 100644 index 7c16c7b..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/client.js +++ /dev/null @@ -1,2013 +0,0 @@ -// TODO: -// * add `.connected` or similar property to allow immediate connection -// status checking -// * add/improve debug output during user authentication phase -'use strict'; - -const { - createHash, - getHashes, - randomFillSync, -} = require('crypto'); -const { Socket } = require('net'); -const { lookup: dnsLookup } = require('dns'); -const EventEmitter = require('events'); -const HASHES = getHashes(); - -const { - COMPAT, - CHANNEL_EXTENDED_DATATYPE: { STDERR }, - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = require('./protocol/constants.js'); -const { init: cryptoInit } = require('./protocol/crypto.js'); -const Protocol = require('./protocol/Protocol.js'); -const { parseKey } = require('./protocol/keyParser.js'); -const { SFTP } = require('./protocol/SFTP.js'); -const { - bufferCopy, - makeBufferParser, - makeError, - readUInt32BE, - sigSSHToASN1, - writeUInt32BE, -} = require('./protocol/utils.js'); - -const { AgentContext, createAgent, isAgent } = require('./agent.js'); -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = require('./Channel.js'); -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = require('./utils.js'); - -const bufferParser = makeBufferParser(); -const sigParser = makeBufferParser(); -const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; -const noop = (err) => {}; - -class Client extends EventEmitter { - constructor() { - super(); - - this.config = { - host: undefined, - port: undefined, - localAddress: undefined, - localPort: undefined, - forceIPv4: undefined, - forceIPv6: undefined, - keepaliveCountMax: undefined, - keepaliveInterval: undefined, - readyTimeout: undefined, - ident: undefined, - - username: undefined, - password: undefined, - privateKey: undefined, - tryKeyboard: undefined, - agent: undefined, - allowAgentFwd: undefined, - authHandler: undefined, - - hostHashAlgo: undefined, - hostHashCb: undefined, - strictVendor: undefined, - debug: undefined - }; - - this._agent = undefined; - this._readyTimeout = undefined; - this._chanMgr = undefined; - this._callbacks = undefined; - this._forwarding = undefined; - this._forwardingUnix = undefined; - this._acceptX11 = undefined; - this._agentFwdEnabled = undefined; - this._remoteVer = undefined; - - this._protocol = undefined; - this._sock = undefined; - this._resetKA = undefined; - } - - connect(cfg) { - if (this._sock && isWritable(this._sock)) { - this.once('close', () => { - this.connect(cfg); - }); - this.end(); - return this; - } - - this.config.host = cfg.hostname || cfg.host || 'localhost'; - this.config.port = cfg.port || 22; - this.config.localAddress = (typeof cfg.localAddress === 'string' - ? cfg.localAddress - : undefined); - this.config.localPort = (typeof cfg.localPort === 'string' - || typeof cfg.localPort === 'number' - ? cfg.localPort - : undefined); - this.config.forceIPv4 = cfg.forceIPv4 || false; - this.config.forceIPv6 = cfg.forceIPv6 || false; - this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' - && cfg.keepaliveCountMax >= 0 - ? cfg.keepaliveCountMax - : 3); - this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' - && cfg.keepaliveInterval > 0 - ? cfg.keepaliveInterval - : 0); - this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' - && cfg.readyTimeout >= 0 - ? cfg.readyTimeout - : 20000); - this.config.ident = (typeof cfg.ident === 'string' - || Buffer.isBuffer(cfg.ident) - ? cfg.ident - : undefined); - - const algorithms = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: [], - }, - sc: undefined, - }; - let allOfferDefaults = true; - if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { - algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, - DEFAULT_KEX, - SUPPORTED_KEX); - if (algorithms.kex !== DEFAULT_KEX) - allOfferDefaults = false; - - algorithms.serverHostKey = - generateAlgorithmList(cfg.algorithms.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY); - if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) - allOfferDefaults = false; - - algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER); - if (algorithms.cs.cipher !== DEFAULT_CIPHER) - allOfferDefaults = false; - - algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, - DEFAULT_MAC, - SUPPORTED_MAC); - if (algorithms.cs.mac !== DEFAULT_MAC) - allOfferDefaults = false; - - algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION); - if (algorithms.cs.compress !== DEFAULT_COMPRESSION) - allOfferDefaults = false; - - if (!allOfferDefaults) - algorithms.sc = algorithms.cs; - } - - if (typeof cfg.username === 'string') - this.config.username = cfg.username; - else if (typeof cfg.user === 'string') - this.config.username = cfg.user; - else - throw new Error('Invalid username'); - - this.config.password = (typeof cfg.password === 'string' - ? cfg.password - : undefined); - this.config.privateKey = (typeof cfg.privateKey === 'string' - || Buffer.isBuffer(cfg.privateKey) - ? cfg.privateKey - : undefined); - this.config.localHostname = (typeof cfg.localHostname === 'string' - ? cfg.localHostname - : undefined); - this.config.localUsername = (typeof cfg.localUsername === 'string' - ? cfg.localUsername - : undefined); - this.config.tryKeyboard = (cfg.tryKeyboard === true); - if (typeof cfg.agent === 'string' && cfg.agent.length) - this.config.agent = createAgent(cfg.agent); - else if (isAgent(cfg.agent)) - this.config.agent = cfg.agent; - else - this.config.agent = undefined; - this.config.allowAgentFwd = (cfg.agentForward === true - && this.config.agent !== undefined); - let authHandler = this.config.authHandler = ( - typeof cfg.authHandler === 'function' - || Array.isArray(cfg.authHandler) - ? cfg.authHandler - : undefined - ); - - this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' - ? cfg.strictVendor - : true); - - const debug = this.config.debug = (typeof cfg.debug === 'function' - ? cfg.debug - : undefined); - - if (cfg.agentForward === true && !this.config.allowAgentFwd) { - throw new Error( - 'You must set a valid agent path to allow agent forwarding' - ); - } - - let callbacks = this._callbacks = []; - this._chanMgr = new ChannelManager(this); - this._forwarding = {}; - this._forwardingUnix = {}; - this._acceptX11 = 0; - this._agentFwdEnabled = false; - this._agent = (this.config.agent ? this.config.agent : undefined); - this._remoteVer = undefined; - let privateKey; - - if (this.config.privateKey) { - privateKey = parseKey(this.config.privateKey, cfg.passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) { - throw new Error( - 'privateKey value does not contain a (valid) private key' - ); - } - } - - let hostVerifier; - if (typeof cfg.hostVerifier === 'function') { - const hashCb = cfg.hostVerifier; - let hasher; - if (HASHES.indexOf(cfg.hostHash) !== -1) { - // Default to old behavior of hashing on user's behalf - hasher = createHash(cfg.hostHash); - } - hostVerifier = (key, verify) => { - if (hasher) { - hasher.update(key); - key = hasher.digest('hex'); - } - const ret = hashCb(key, verify); - if (ret !== undefined) - verify(ret); - }; - } - - const sock = this._sock = (cfg.sock || new Socket()); - let ready = false; - let sawHeader = false; - if (this._protocol) - this._protocol.cleanup(); - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from server: ${JSON.stringify(msg)}`); - }); - const proto = this._protocol = new Protocol({ - ident: this.config.ident, - offer: (allOfferDefaults ? undefined : algorithms), - onWrite: (data) => { - if (isWritable(sock)) - sock.write(data); - }, - onError: (err) => { - if (err.level === 'handshake') - clearTimeout(this._readyTimeout); - if (!proto._destruct) - sock.removeAllListeners('data'); - this.emit('error', err); - try { - sock.end(); - } catch {} - }, - onHeader: (header) => { - sawHeader = true; - this._remoteVer = header.versions.software; - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - this.emit('handshake', negotiated); - if (!ready) { - ready = true; - proto.service('ssh-userauth'); - } - }, - debug, - hostVerifier, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - sock.end(); - }, - SERVICE_ACCEPT: (p, name) => { - if (name === 'ssh-userauth') - tryNextAuth(); - }, - USERAUTH_BANNER: (p, msg) => { - this.emit('banner', msg); - }, - USERAUTH_SUCCESS: (p) => { - // Start keepalive mechanism - resetKA(); - - clearTimeout(this._readyTimeout); - - this.emit('ready'); - }, - USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { - if (curAuth.type === 'agent') { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Client: Agent key #${pos + 1} failed`); - return tryNextAgentKey(); - } - - debug && debug(`Client: ${curAuth.type} auth failed`); - - curPartial = partialSuccess; - curAuthsLeft = authMethods; - tryNextAuth(); - }, - USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { - if (curAuth.type === 'password') { - // TODO: support a `changePrompt()` on `curAuth` that defaults to - // emitting 'change password' as before - this.emit('change password', prompt, (newPassword) => { - proto.authPassword( - this.config.username, - this.config.password, - newPassword - ); - }); - } - }, - USERAUTH_PK_OK: (p) => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.currentKey(); - proto.authPK(curAuth.username, key, (buf, cb) => { - curAuth.agentCtx.sign(key, buf, {}, (err, signed) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - } else { - return cb(signed); - } - - tryNextAgentKey(); - }); - }); - } else if (curAuth.type === 'publickey') { - proto.authPK(curAuth.username, curAuth.key, (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error signing data with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - cb(signature); - }); - } - }, - USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { - if (curAuth.type === 'keyboard-interactive') { - const nprompts = (Array.isArray(prompts) ? prompts.length : 0); - if (nprompts === 0) { - debug && debug( - 'Client: Sending automatic USERAUTH_INFO_RESPONSE' - ); - proto.authInfoRes(); - return; - } - // We sent a keyboard-interactive user authentication request and - // now the server is sending us the prompts we need to present to - // the user - curAuth.prompt( - name, - instructions, - '', - prompts, - (answers) => { - proto.authInfoRes(answers); - } - ); - } - }, - REQUEST_SUCCESS: (p, data) => { - if (callbacks.length) - callbacks.shift()(false, data); - }, - REQUEST_FAILURE: (p) => { - if (callbacks.length) - callbacks.shift()(true); - }, - GLOBAL_REQUEST: (p, name, wantReply, data) => { - switch (name) { - case 'hostkeys-00@openssh.com': - // Automatically verify keys before passing to end user - hostKeysProve(this, data, (err, keys) => { - if (err) - return; - this.emit('hostkeys', keys); - }); - if (wantReply) - proto.requestSuccess(); - break; - default: - // Auto-reject all other global requests, this can be especially - // useful if the server is sending us dummy keepalive global - // requests - if (wantReply) - proto.requestFailure(); - } - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from server, typically a forwarded TCP or - // X11 connection - onCHANNEL_OPEN(this, info); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const isSFTP = (channel.type === 'sftp'); - const type = (isSFTP ? 'session' : channel.type); - const chanInfo = { - type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const instance = ( - isSFTP - ? new SFTP(this, chanInfo, { debug }) - : new Channel(this, chanInfo) - ); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - if (type !== STDERR) - return; - - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (!channel.stderr.push(data)) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - const exit = channel._exit; - if (exit.code !== undefined) - return; - switch (type) { - case 'exit-status': - channel.emit('exit', exit.code = data); - return; - case 'exit-signal': - channel.emit('exit', - exit.code = null, - exit.signal = `SIG${data.signal}`, - exit.dump = data.coreDumped, - exit.desc = data.errorMessage); - return; - } - - // Keepalive request? OpenSSH will send one as a channel request if - // there is a channel open - - if (wantReply) - p.channelFailure(channel.outgoing.id); - }, - CHANNEL_EOF: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - if (channel.stderr.readable) - channel.stderr.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); - }, - }, - }); - - sock.pause(); - - // TODO: check keepalive implementation - // Keepalive-related - const kainterval = this.config.keepaliveInterval; - const kacountmax = this.config.keepaliveCountMax; - let kacount = 0; - let katimer; - const sendKA = () => { - if (++kacount > kacountmax) { - clearInterval(katimer); - if (sock.readable) { - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - } - return; - } - if (isWritable(sock)) { - // Append dummy callback to keep correct callback order - callbacks.push(resetKA); - proto.ping(); - } else { - clearInterval(katimer); - } - }; - function resetKA() { - if (kainterval > 0) { - kacount = 0; - clearInterval(katimer); - if (isWritable(sock)) - katimer = setInterval(sendKA, kainterval); - } - } - this._resetKA = resetKA; - - const onDone = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (wasConnected && !sawHeader) { - const err = - makeError('Connection lost before handshake', 'protocol', true); - this.emit('error', err); - } - }; - })(); - const onConnect = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - - wasConnected = true; - debug && debug('Socket connected'); - this.emit('connect'); - - cryptoInit.then(() => { - sock.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - } - }); - - // Drain stderr if we are connection hopping using an exec stream - if (sock.stderr && typeof sock.stderr.resume === 'function') - sock.stderr.resume(); - - sock.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - }); - }; - })(); - let wasConnected = false; - sock.on('connect', onConnect) - .on('timeout', () => { - this.emit('timeout'); - }).on('error', (err) => { - debug && debug(`Socket error: ${err.message}`); - clearTimeout(this._readyTimeout); - err.level = 'client-socket'; - this.emit('error', err); - }).on('end', () => { - debug && debug('Socket ended'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('end'); - }).on('close', () => { - debug && debug('Socket closed'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('close'); - - // Notify outstanding channel requests of disconnection ... - const callbacks_ = callbacks; - callbacks = this._callbacks = []; - const err = new Error('No response from server'); - for (let i = 0; i < callbacks_.length; ++i) - callbacks_[i](err); - - // Simulate error for any channels waiting to be opened - this._chanMgr.cleanup(err); - }); - - // Begin authentication handling =========================================== - let curAuth; - let curPartial = null; - let curAuthsLeft = null; - const authsAllowed = ['none']; - if (this.config.password !== undefined) - authsAllowed.push('password'); - if (privateKey !== undefined) - authsAllowed.push('publickey'); - if (this._agent !== undefined) - authsAllowed.push('agent'); - if (this.config.tryKeyboard) - authsAllowed.push('keyboard-interactive'); - if (privateKey !== undefined - && this.config.localHostname !== undefined - && this.config.localUsername !== undefined) { - authsAllowed.push('hostbased'); - } - - if (Array.isArray(authHandler)) - authHandler = makeSimpleAuthHandler(authHandler); - else if (typeof authHandler !== 'function') - authHandler = makeSimpleAuthHandler(authsAllowed); - - let hasSentAuth = false; - const doNextAuth = (nextAuth) => { - if (hasSentAuth) - return; - hasSentAuth = true; - - if (nextAuth === false) { - const err = new Error('All configured authentication methods failed'); - err.level = 'client-authentication'; - this.emit('error', err); - this.end(); - return; - } - - if (typeof nextAuth === 'string') { - // Remain backwards compatible with original `authHandler()` usage, - // which only supported passing names of next method to try using data - // from the `connect()` config object - - const type = nextAuth; - if (authsAllowed.indexOf(type) === -1) - return skipAuth(`Authentication method not allowed: ${type}`); - - const username = this.config.username; - switch (type) { - case 'password': - nextAuth = { type, username, password: this.config.password }; - break; - case 'publickey': - nextAuth = { type, username, key: privateKey }; - break; - case 'hostbased': - nextAuth = { - type, - username, - key: privateKey, - localHostname: this.config.localHostname, - localUsername: this.config.localUsername, - }; - break; - case 'agent': - nextAuth = { - type, - username, - agentCtx: new AgentContext(this._agent), - }; - break; - case 'keyboard-interactive': - nextAuth = { - type, - username, - prompt: (...args) => this.emit('keyboard-interactive', ...args), - }; - break; - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } else if (typeof nextAuth !== 'object' || nextAuth === null) { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } else { - const username = nextAuth.username; - if (typeof username !== 'string') { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } - const type = nextAuth.type; - switch (type) { - case 'password': { - const { password } = nextAuth; - if (typeof password !== 'string' && !Buffer.isBuffer(password)) - return skipAuth('Skipping invalid password auth attempt'); - nextAuth = { type, username, password }; - break; - } - case 'publickey': { - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error) - return skipAuth('Skipping invalid key auth attempt'); - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key }; - break; - } - case 'hostbased': { - const { localHostname, localUsername } = nextAuth; - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error - || typeof localHostname !== 'string' - || typeof localUsername !== 'string') { - return skipAuth('Skipping invalid hostbased auth attempt'); - } - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key, localHostname, localUsername }; - break; - } - case 'agent': { - let agent = nextAuth.agent; - if (typeof agent === 'string' && agent.length) { - agent = createAgent(agent); - } else if (!isAgent(agent)) { - return skipAuth( - `Skipping invalid agent: ${nextAuth.agent}` - ); - } - nextAuth = { type, username, agentCtx: new AgentContext(agent) }; - break; - } - case 'keyboard-interactive': { - const { prompt } = nextAuth; - if (typeof prompt !== 'function') { - return skipAuth( - 'Skipping invalid keyboard-interactive auth attempt' - ); - } - nextAuth = { type, username, prompt }; - break; - } - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } - curAuth = nextAuth; - - // Begin authentication method's process - try { - const username = curAuth.username; - switch (curAuth.type) { - case 'password': - proto.authPassword(username, curAuth.password); - break; - case 'publickey': - proto.authPK(username, curAuth.key); - break; - case 'hostbased': - proto.authHostbased(username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - - cb(signature); - }); - break; - case 'agent': - curAuth.agentCtx.init((err) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - return tryNextAuth(); - } - tryNextAgentKey(); - }); - break; - case 'keyboard-interactive': - proto.authKeyboard(username); - break; - case 'none': - proto.authNone(username); - break; - } - } finally { - hasSentAuth = false; - } - }; - - function skipAuth(msg) { - debug && debug(msg); - process.nextTick(tryNextAuth); - } - - function tryNextAuth() { - hasSentAuth = false; - const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); - if (hasSentAuth || auth === undefined) - return; - doNextAuth(auth); - } - - const tryNextAgentKey = () => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.nextKey(); - if (key === false) { - debug && debug('Agent: No more keys left to try'); - debug && debug('Client: agent auth failed'); - tryNextAuth(); - } else { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Agent: Trying key #${pos + 1}`); - proto.authPK(curAuth.username, key); - } - } - }; - - const startTimeout = () => { - if (this.config.readyTimeout > 0) { - this._readyTimeout = setTimeout(() => { - const err = new Error('Timed out while waiting for handshake'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - }, this.config.readyTimeout); - } - }; - - if (!cfg.sock) { - let host = this.config.host; - const forceIPv4 = this.config.forceIPv4; - const forceIPv6 = this.config.forceIPv6; - - debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); - - const doConnect = () => { - startTimeout(); - sock.connect({ - host, - port: this.config.port, - localAddress: this.config.localAddress, - localPort: this.config.localPort - }); - sock.setNoDelay(true); - sock.setMaxListeners(0); - sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); - }; - - if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { - doConnect(); - } else { - dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { - if (err) { - const type = (forceIPv4 ? 'IPv4' : 'IPv6'); - const error = new Error( - `Error while looking up ${type} address for '${host}': ${err}` - ); - clearTimeout(this._readyTimeout); - error.level = 'client-dns'; - this.emit('error', error); - this.emit('close'); - return; - } - host = address; - doConnect(); - }); - } - } else { - // Custom socket passed in - startTimeout(); - if (typeof sock.connecting === 'boolean') { - // net.Socket - - if (!sock.connecting) { - // Already connected - onConnect(); - } - } else { - // Assume socket/stream is already "connected" - onConnect(); - } - } - - return this; - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - - destroy() { - this._sock && isWritable(this._sock) && this._sock.destroy(); - return this; - } - - exec(cmd, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; - - openChannel(this, 'session', extraOpts, (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.pty === 'object' && opts.pty !== null) - || opts.pty === true) { - todo.push(() => reqPty(chan, opts.pty, reqCb)); - } - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqExec(chan, cmd, opts, cb)); - todo.shift()(); - }); - - return this; - } - - shell(wndopts, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof wndopts === 'function') { - cb = wndopts; - wndopts = opts = undefined; - } else if (typeof opts === 'function') { - cb = opts; - opts = undefined; - } - if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { - opts = wndopts; - wndopts = undefined; - } - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (wndopts !== false) - todo.push(() => reqPty(chan, wndopts, reqCb)); - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqShell(chan, cb)); - todo.shift()(); - }); - - return this; - } - - subsys(name, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(chan, name, (err, stream) => { - if (err) { - cb(err); - return; - } - - cb(undefined, stream); - }); - }); - - return this; - } - - forwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request for the server to start forwarding TCP connections to us - // on a particular address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); - return; - } - - let realPort = bindPort; - if (bindPort === 0 && data && data.length >= 4) { - realPort = readUInt32BE(data, 0); - if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) - bindPort = realPort; - } - - this._forwarding[`${bindAddr}:${bindPort}`] = realPort; - - cb(undefined, realPort); - }); - } - - this._protocol.tcpipForward(bindAddr, bindPort, wantReply); - - return this; - } - - unforwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request to stop forwarding us new connections for a particular - // address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); - return; - } - - delete this._forwarding[`${bindAddr}:${bindPort}`]; - - cb(); - }); - } - - this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); - - return this; - } - - forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request to forward a TCP connection to the server - - const cfg = { - srcIP: srcIP, - srcPort: srcPort, - dstIP: dstIP, - dstPort: dstPort - }; - - if (typeof cb !== 'function') - cb = noop; - - openChannel(this, 'direct-tcpip', cfg, cb); - - return this; - } - - openssh_noMoreSessions(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to disable future sessions')); - return; - } - - cb(); - }); - } - - this._protocol.openssh_noMoreSessions(wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${socketPath}`)); - return; - } - this._forwardingUnix[socketPath] = true; - cb(); - }); - } - - this._protocol.openssh_streamLocalForward(socketPath, wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_unforwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${socketPath}`)); - return; - } - delete this._forwardingUnix[socketPath]; - cb(); - }); - } - - this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof cb !== 'function') - cb = noop; - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); - return this; - } - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - sftp(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - openChannel(this, 'sftp', (err, sftp) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(sftp, 'sftp', (err, sftp_) => { - if (err) { - cb(err); - return; - } - - function removeListeners() { - sftp.removeListener('ready', onReady); - sftp.removeListener('error', onError); - sftp.removeListener('exit', onExit); - sftp.removeListener('close', onExit); - } - - function onReady() { - // TODO: do not remove exit/close in case remote end closes the - // channel abruptly and we need to notify outstanding callbacks - removeListeners(); - cb(undefined, sftp); - } - - function onError(err) { - removeListeners(); - cb(err); - } - - function onExit(code, signal) { - removeListeners(); - let msg; - if (typeof code === 'number') - msg = `Received exit code ${code} while establishing SFTP session`; - else if (signal !== undefined) - msg = `Received signal ${signal} while establishing SFTP session`; - else - msg = 'Received unexpected SFTP session termination'; - const err = new Error(msg); - err.code = code; - err.signal = signal; - cb(err); - } - - sftp.on('ready', onReady) - .on('error', onError) - .on('exit', onExit) - .on('close', onExit); - - sftp._init(); - }); - }); - - return this; - } -} - -function openChannel(self, type, opts, cb) { - // Ask the server to open a channel for some purpose - // (e.g. session (sftp, exec, shell), or forwarding a TCP connection - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'session': - case 'sftp': - self._protocol.session(localChan, initWindow, maxPacket); - break; - case 'direct-tcpip': - self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'direct-streamlocal@openssh.com': - self._protocol.openssh_directStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} - -function reqX11(chan, screen, cb) { - // Asks server to start sending us X11 connections - const cfg = { - single: false, - protocol: 'MIT-MAGIC-COOKIE-1', - cookie: undefined, - screen: 0 - }; - - if (typeof screen === 'function') { - cb = screen; - } else if (typeof screen === 'object' && screen !== null) { - if (typeof screen.single === 'boolean') - cfg.single = screen.single; - if (typeof screen.screen === 'number') - cfg.screen = screen.screen; - if (typeof screen.protocol === 'string') - cfg.protocol = screen.protocol; - if (typeof screen.cookie === 'string') - cfg.cookie = screen.cookie; - else if (Buffer.isBuffer(screen.cookie)) - cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); - } - if (cfg.cookie === undefined) - cfg.cookie = randomCookie(); - - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } - - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to request X11')); - return; - } - - chan._hasX11 = true; - ++chan._client._acceptX11; - chan.once('close', () => { - if (chan._client._acceptX11) - --chan._client._acceptX11; - }); - - cb(); - }); - } - - chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); -} - -function reqPty(chan, opts, cb) { - let rows = 24; - let cols = 80; - let width = 640; - let height = 480; - let term = 'vt100'; - let modes = null; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.rows === 'number') - rows = opts.rows; - if (typeof opts.cols === 'number') - cols = opts.cols; - if (typeof opts.width === 'number') - width = opts.width; - if (typeof opts.height === 'number') - height = opts.height; - if (typeof opts.term === 'string') - term = opts.term; - if (typeof opts.modes === 'object') - modes = opts.modes; - } - - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } - - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to request a pseudo-terminal')); - return; - } - cb(); - }); - } - - chan._client._protocol.pty(chan.outgoing.id, - rows, - cols, - height, - width, - term, - modes, - wantReply); -} - -function reqAgentFwd(chan, cb) { - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - wantReply && cb(new Error('Channel is not open')); - return; - } - if (chan._client._agentFwdEnabled) { - wantReply && cb(false); - return; - } - - chan._client._agentFwdEnabled = true; - - chan._callbacks.push((had_err) => { - if (had_err) { - chan._client._agentFwdEnabled = false; - if (wantReply) { - cb(had_err !== true - ? had_err - : new Error('Unable to request agent forwarding')); - } - return; - } - - if (wantReply) - cb(); - }); - - chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); -} - -function reqShell(chan, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to open shell')); - return; - } - chan.subtype = 'shell'; - cb(undefined, chan); - }); - - chan._client._protocol.shell(chan.outgoing.id, true); -} - -function reqExec(chan, cmd, opts, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to exec')); - return; - } - chan.subtype = 'exec'; - chan.allowHalfOpen = (opts.allowHalfOpen !== false); - cb(undefined, chan); - }); - - chan._client._protocol.exec(chan.outgoing.id, cmd, true); -} - -function reqEnv(chan, env) { - if (chan.outgoing.state !== 'open') - return; - - const keys = Object.keys(env || {}); - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const val = env[key]; - chan._client._protocol.env(chan.outgoing.id, key, val, false); - } -} - -function reqSubsystem(chan, name, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to start subsystem: ${name}`)); - return; - } - chan.subtype = 'subsystem'; - cb(undefined, chan); - }); - - chan._client._protocol.subsystem(chan.outgoing.id, name, true); -} - -// TODO: inline implementation into single call site -function onCHANNEL_OPEN(self, info) { - // The server is trying to open a channel with us, this is usually when - // we asked the server to forward us connections on some port and now they - // are asking us to accept/deny an incoming connection on their side - - let localChan = -1; - let reason; - - const accept = () => { - const chanInfo = { - type: info.type, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const stream = new Channel(self, chanInfo); - self._chanMgr.update(localChan, stream); - - self._protocol.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - return stream; - }; - const reject = () => { - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - - if (localChan !== -1) - self._chanMgr.remove(localChan); - - self._protocol.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = self._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of incoming channel open: ' - + 'no channels available' - ); - } - } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'forwarded-tcpip': { - const val = self._forwarding[`${data.destIP}:${data.destPort}`]; - if (val !== undefined && reserveChannel()) { - if (data.destPort === 0) - data.destPort = val; - self.emit('tcp connection', data, accept, reject); - return; - } - break; - } - case 'forwarded-streamlocal@openssh.com': - if (self._forwardingUnix[data.socketPath] !== undefined - && reserveChannel()) { - self.emit('unix connection', data, accept, reject); - return; - } - break; - case 'auth-agent@openssh.com': - if (self._agentFwdEnabled - && typeof self._agent.getStream === 'function' - && reserveChannel()) { - self._agent.getStream((err, stream) => { - if (err) - return reject(); - - const upstream = accept(); - upstream.pipe(stream).pipe(upstream); - }); - return; - } - break; - case 'x11': - if (self._acceptX11 !== 0 && reserveChannel()) { - self.emit('x11', data, accept, reject); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unsupported incoming channel open ' - + `type: ${info.type}` - ); - } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unexpected incoming channel open for: ' - + info.type - ); - } - } - - reject(); -} - -const randomCookie = (() => { - const buffer = Buffer.allocUnsafe(16); - return () => { - randomFillSync(buffer, 0, 16); - return buffer.hexSlice(0, 16); - }; -})(); - -function makeSimpleAuthHandler(authList) { - if (!Array.isArray(authList)) - throw new Error('authList must be an array'); - - let a = 0; - return (authsLeft, partialSuccess, cb) => { - if (a === authList.length) - return false; - return authList[a++]; - }; -} - -function hostKeysProve(client, keys_, cb) { - if (!client._sock || !isWritable(client._sock)) - return; - - if (typeof cb !== 'function') - cb = noop; - - if (!Array.isArray(keys_)) - throw new TypeError('Invalid keys argument type'); - - const keys = []; - for (const key of keys_) { - const parsed = parseKey(key); - if (parsed instanceof Error) - throw parsed; - keys.push(parsed); - } - - if (!client.config.strictVendor - || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { - client._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Server failed to prove supplied keys')); - return; - } - - // TODO: move all of this parsing/verifying logic out of the client? - const ret = []; - let keyIdx = 0; - bufferParser.init(data, 0); - while (bufferParser.avail()) { - if (keyIdx === keys.length) - break; - const key = keys[keyIdx++]; - const keyPublic = key.getPublicSSH(); - - const sigEntry = bufferParser.readString(); - sigParser.init(sigEntry, 0); - const type = sigParser.readString(true); - let value = sigParser.readString(); - - let algo; - if (type !== key.type) { - if (key.type === 'ssh-rsa') { - switch (type) { - case 'rsa-sha2-256': - algo = 'sha256'; - break; - case 'rsa-sha2-512': - algo = 'sha512'; - break; - default: - continue; - } - } else { - continue; - } - } - - const sessionID = client._protocol._kex.sessionID; - const verifyData = Buffer.allocUnsafe( - 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length - ); - let p = 0; - writeUInt32BE(verifyData, 29, p); - verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - writeUInt32BE(verifyData, sessionID.length, p += 29); - bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); - writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); - bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); - - if (!(value = sigSSHToASN1(value, type))) - continue; - if (key.verify(verifyData, value, algo) === true) - ret.push(key); - } - sigParser.clear(); - bufferParser.clear(); - - cb(null, ret); - }); - - client._protocol.openssh_hostKeysProve(keys); - return; - } - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); -} - -module.exports = Client; diff --git a/reverse_engineering/node_modules/ssh2/lib/http-agents.js b/reverse_engineering/node_modules/ssh2/lib/http-agents.js deleted file mode 100644 index 770a0e6..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/http-agents.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -const { Agent: HttpAgent } = require('http'); -const { Agent: HttpsAgent } = require('https'); -const { connect: tlsConnect } = require('tls'); - -let Client; - -for (const ctor of [HttpAgent, HttpsAgent]) { - class SSHAgent extends ctor { - constructor(connectCfg, agentOptions) { - super(agentOptions); - - this._connectCfg = connectCfg; - this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; - } - - createConnection(options, cb) { - const srcIP = (options && options.localAddress) || this._defaultSrcIP; - const srcPort = (options && options.localPort) || 0; - const dstIP = options.host; - const dstPort = options.port; - - if (Client === undefined) - Client = require('./client.js'); - - const client = new Client(); - let triedForward = false; - client.on('ready', () => { - client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { - triedForward = true; - if (err) { - client.end(); - return cb(err); - } - stream.once('close', () => client.end()); - cb(null, decorateStream(stream, ctor, options)); - }); - }).on('error', cb).on('close', () => { - if (!triedForward) - cb(new Error('Unexpected connection close')); - }).connect(this._connectCfg); - } - } - - exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; -} - -function noop() {} - -function decorateStream(stream, ctor, options) { - if (ctor === HttpAgent) { - // HTTP - stream.setKeepAlive = noop; - stream.setNoDelay = noop; - stream.setTimeout = noop; - stream.ref = noop; - stream.unref = noop; - stream.destroySoon = stream.destroy; - return stream; - } - - // HTTPS - options.socket = stream; - const wrapped = tlsConnect(options); - - // This is a workaround for a regression in node v12.16.3+ - // https://github.com/nodejs/node/issues/35904 - const onClose = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (stream.isPaused()) - stream.resume(); - }; - })(); - // 'end' listener is needed because 'close' is not emitted in some scenarios - // in node v12.x for some unknown reason - wrapped.on('end', onClose).on('close', onClose); - - return wrapped; -} diff --git a/reverse_engineering/node_modules/ssh2/lib/index.js b/reverse_engineering/node_modules/ssh2/lib/index.js deleted file mode 100644 index 459952e..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/index.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const { - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - OpenSSHAgent, - PageantAgent, -} = require('./agent.js'); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = require('./http-agents.js'); -const { parseKey } = require('./protocol/keyParser.js'); -const { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, -} = require('./protocol/SFTP.js'); - -module.exports = { - AgentProtocol, - BaseAgent, - createAgent, - Client: require('./client.js'), - CygwinAgent, - HTTPAgent, - HTTPSAgent, - OpenSSHAgent, - PageantAgent, - Server: require('./server.js'), - utils: { - parseKey, - sftp: { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, - }, - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/Protocol.js b/reverse_engineering/node_modules/ssh2/lib/protocol/Protocol.js deleted file mode 100644 index e00f1eb..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/Protocol.js +++ /dev/null @@ -1,2076 +0,0 @@ -/* - TODO: - * Replace `buffer._pos` usage in keyParser.js and elsewhere - * Utilize optional "writev" support when writing packets from - cipher.encrypt() - * Built-in support for automatic re-keying, on by default - * Revisit receiving unexpected/unknown packets - * Error (fatal or otherwise) or ignore or pass on to user (in some or all - cases)? - * Including server/client check for single directional packet types? - * Check packets for validity or bail as early as possible? - * Automatic re-key every 2**31 packets after the last key exchange (sent or - received), as suggested by RFC4344. OpenSSH currently does this. - * Automatic re-key every so many blocks depending on cipher. RFC4344: - Because of a birthday property of block ciphers and some modes of - operation, implementations must be careful not to encrypt too many - blocks with the same encryption key. - - Let L be the block length (in bits) of an SSH encryption method's - block cipher (e.g., 128 for AES). If L is at least 128, then, after - rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) - blocks before rekeying again. If L is at least 128, then SSH - implementations should also attempt to force a rekey before receiving - more than 2**(L/4) blocks. If L is less than 128 (which is the case - for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, - although it may be too expensive to rekey every 2**(L/4) blocks, it - is still advisable for SSH implementations to follow the original - recommendation in [RFC4253]: rekey at least once for every gigabyte - of transmitted data. - - Note that if L is less than or equal to 128, then the recommendation - in this subsection supersedes the recommendation in Section 3.1. If - an SSH implementation uses a block cipher with a larger block size - (e.g., Rijndael with 256-bit blocks), then the recommendations in - Section 3.1 may supersede the recommendations in this subsection - (depending on the lengths of the packets). -*/ - -'use strict'; - -const { inspect } = require('util'); - -const { bindingAvailable, NullCipher, NullDecipher } = require('./crypto.js'); -const { - COMPAT_CHECKS, - DISCONNECT_REASON, - MESSAGE, - SIGNALS, - TERMINAL_MODE, -} = require('./constants.js'); -const { - DEFAULT_KEXINIT, - KexInit, - kexinit, - onKEXPayload, -} = require('./kex.js'); -const { - parseKey, -} = require('./keyParser.js'); -const MESSAGE_HANDLERS = require('./handlers.js'); -const { - bufferCopy, - bufferFill, - bufferSlice, - convertSignature, - sendPacket, - writeUInt32BE, -} = require('./utils.js'); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = require('./zlib.js'); - -const MODULE_VER = require('../../package.json').version; - -const VALID_DISCONNECT_REASONS = new Map( - Object.values(DISCONNECT_REASON).map((n) => [n, 1]) -); -const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); -const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); -const MAX_LINE_LEN = 8192; -const MAX_LINES = 1024; -const PING_PAYLOAD = Buffer.from([ - MESSAGE.GLOBAL_REQUEST, - // "keepalive@openssh.com" - 0, 0, 0, 21, - 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, - 115, 104, 46, 99, 111, 109, - // Request a reply - 1, -]); -const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); - -function noop() {} - -/* - Inbound: - * kexinit payload (needed only until exchange hash is generated) - * raw ident - * rekey packet queue - * expected packet (implemented as separate _parse() function?) - Outbound: - * kexinit payload (needed only until exchange hash is generated) - * rekey packet queue - * kex secret (needed only until NEWKEYS) - * exchange hash (needed only until NEWKEYS) - * session ID (set to exchange hash from initial handshake) -*/ -class Protocol { - constructor(config) { - const onWrite = config.onWrite; - if (typeof onWrite !== 'function') - throw new Error('Missing onWrite function'); - this._onWrite = (data) => { onWrite(data); }; - - const onError = config.onError; - if (typeof onError !== 'function') - throw new Error('Missing onError function'); - this._onError = (err) => { onError(err); }; - - const debug = config.debug; - this._debug = (typeof debug === 'function' - ? (msg) => { debug(msg); } - : undefined); - - const onHeader = config.onHeader; - this._onHeader = (typeof onHeader === 'function' - ? (...args) => { onHeader(...args); } - : noop); - - const onPacket = config.onPacket; - this._onPacket = (typeof onPacket === 'function' - ? () => { onPacket(); } - : noop); - - let onHandshakeComplete = config.onHandshakeComplete; - if (typeof onHandshakeComplete !== 'function') - onHandshakeComplete = noop; - this._onHandshakeComplete = (...args) => { - this._debug && this._debug('Handshake completed'); - - // Process packets queued during a rekey where necessary - const oldQueue = this._queue; - if (oldQueue) { - this._queue = undefined; - this._debug && this._debug( - `Draining outbound queue (${oldQueue.length}) ...` - ); - for (let i = 0; i < oldQueue.length; ++i) { - const data = oldQueue[i]; - // data === payload only - - // XXX: hacky - let finalized = this._packetRW.write.finalize(data); - if (finalized === data) { - const packet = this._cipher.allocPacket(data.length); - packet.set(data, 5); - finalized = packet; - } - - sendPacket(this, finalized); - } - this._debug && this._debug('... finished draining outbound queue'); - } - - onHandshakeComplete(...args); - }; - this._queue = undefined; - - const messageHandlers = config.messageHandlers; - if (typeof messageHandlers === 'object' && messageHandlers !== null) - this._handlers = messageHandlers; - else - this._handlers = {}; - - this._onPayload = onPayload.bind(this); - - this._server = !!config.server; - this._banner = undefined; - let greeting; - if (this._server) { - if (typeof config.hostKeys !== 'object' || config.hostKeys === null) - throw new Error('Missing server host key(s)'); - this._hostKeys = config.hostKeys; - - // Greeting displayed before the ssh identification string is sent, this - // is usually ignored by most clients - if (typeof config.greeting === 'string' && config.greeting.length) { - greeting = (config.greeting.slice(-2) === '\r\n' - ? config.greeting - : `${config.greeting}\r\n`); - } - - // Banner shown after the handshake completes, but before user - // authentication begins - if (typeof config.banner === 'string' && config.banner.length) { - this._banner = (config.banner.slice(-2) === '\r\n' - ? config.banner - : `${config.banner}\r\n`); - } - } else { - this._hostKeys = undefined; - } - - let offer = config.offer; - if (typeof offer !== 'object' || offer === null) - offer = DEFAULT_KEXINIT; - else if (offer.constructor !== KexInit) - offer = new KexInit(offer); - this._kex = undefined; - this._kexinit = undefined; - this._offer = offer; - this._cipher = new NullCipher(0, this._onWrite); - this._decipher = undefined; - this._skipNextInboundPacket = false; - this._packetRW = { - read: new PacketReader(), - write: new PacketWriter(this), - }; - this._hostVerifier = (!this._server - && typeof config.hostVerifier === 'function' - ? config.hostVerifier - : undefined); - - this._parse = parseHeader; - this._buffer = undefined; - this._authsQueue = []; - this._authenticated = false; - this._remoteIdentRaw = undefined; - let sentIdent; - if (typeof config.ident === 'string') { - this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); - - sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); - sentIdent.set(this._identRaw, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else if (Buffer.isBuffer(config.ident)) { - const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); - fullIdent.latin1Write('SSH-2.0-', 0, 8); - fullIdent.set(config.ident, 8); - this._identRaw = fullIdent; - - sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); - sentIdent.set(fullIdent, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else { - this._identRaw = IDENT_RAW; - sentIdent = IDENT; - } - this._compatFlags = 0; - - if (this._debug) { - if (bindingAvailable) - this._debug('Custom crypto binding available'); - else - this._debug('Custom crypto binding not available'); - } - - process.nextTick(() => { - this._debug && this._debug( - `Local ident: ${inspect(this._identRaw.toString())}` - ); - if (greeting) - this._onWrite(greeting); - this._onWrite(sentIdent); - }); - } - _destruct(reason) { - this._packetRW.read.cleanup(); - this._packetRW.write.cleanup(); - this._cipher && this._cipher.free(); - this._decipher && this._decipher.free(); - if (typeof reason !== 'string' || reason.length === 0) - reason = 'fatal error'; - this.parse = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._onWrite = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._destruct = undefined; - } - cleanup() { - this._destruct && this._destruct(); - } - parse(chunk, i, len) { - while (i < len) - i = this._parse(chunk, i, len); - } - - // Protocol message API - - // =========================================================================== - // Common/Shared ============================================================= - // =========================================================================== - - // Global - // ------ - disconnect(reason) { - const pktLen = 1 + 4 + 4 + 4; - // We don't use _packetRW.write.* here because we need to make sure that - // we always get a full packet allocated because this message can be sent - // at any time -- even during a key exchange - let p = this._packetRW.write.allocStartKEX; - const packet = this._packetRW.write.alloc(pktLen, true); - const end = p + pktLen; - - if (!VALID_DISCONNECT_REASONS.has(reason)) - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - - packet[p] = MESSAGE.DISCONNECT; - writeUInt32BE(packet, reason, ++p); - packet.fill(0, p += 4, end); - - this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); - sendPacket(this, this._packetRW.write.finalize(packet, true), true); - } - ping() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); - - packet.set(PING_PAYLOAD, p); - - this._debug && this._debug( - 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - rekey() { - if (this._kexinit === undefined) { - this._debug && this._debug('Outbound: Initiated explicit rekey'); - this._queue = []; - kexinit(this); - } else { - this._debug && this._debug('Outbound: Ignoring rekey during handshake'); - } - } - - // 'ssh-connection' service-specific - // --------------------------------- - requestSuccess(data) { - let p = this._packetRW.write.allocStart; - let packet; - if (Buffer.isBuffer(data)) { - packet = this._packetRW.write.alloc(1 + data.length); - - packet[p] = MESSAGE.REQUEST_SUCCESS; - - packet.set(data, ++p); - } else { - packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_SUCCESS; - } - - this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - requestFailure() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_FAILURE; - - this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelSuccess(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_SUCCESS; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelFailure(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_FAILURE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelEOF(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_EOF; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelClose(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_CLOSE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelWindowAdjust(chan, amount) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, amount, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelData(chan, data) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelExtData(chan, data, type) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, type, p += 4); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenConfirm(remote, local, initWindow, maxPacket) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, local, p += 4); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenFail(remote, reason, desc) { - if (typeof desc !== 'string') - desc = ''; - - const descLen = Buffer.byteLength(desc); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, reason, p += 4); - - writeUInt32BE(packet, descLen, p += 4); - - p += 4; - if (descLen) { - packet.utf8Write(desc, p, descLen); - p += descLen; - } - - writeUInt32BE(packet, 0, p); // Empty language tag - - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - - // Global - // ------ - service(name) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + nameLen); - - packet[p] = MESSAGE.SERVICE_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-userauth' service-specific - // ------------------------------- - authPassword(username, password, newPassword) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - const passLen = Buffer.byteLength(password); - const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen - + (newPassword ? 4 + newPassLen : 0) - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 8, p += 14); - packet.utf8Write('password', p += 4, 8); - - packet[p += 8] = (newPassword ? 1 : 0); - - writeUInt32BE(packet, passLen, ++p); - if (Buffer.isBuffer(password)) - bufferCopy(password, packet, 0, passLen, p += 4); - else - packet.utf8Write(password, p += 4, passLen); - - if (newPassword) { - writeUInt32BE(packet, newPassLen, p += passLen); - if (Buffer.isBuffer(newPassword)) - bufferCopy(newPassword, packet, 0, newPassLen, p += 4); - else - packet.utf8Write(newPassword, p += 4, newPassLen); - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (changed password)' - ); - } else { - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (password)' - ); - } - - this._authsQueue.push('password'); - - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPK(username, pubKey, cbSign) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const payloadLen = - (cbSign ? 4 + sesLen : 0) - + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; - let packet; - let p; - if (cbSign) { - packet = Buffer.allocUnsafe(payloadLen); - p = 0; - writeUInt32BE(packet, sesLen, p); - packet.set(sessionID, p += 4); - p += sesLen; - } else { - packet = this._packetRW.write.alloc(payloadLen); - p = this._packetRW.write.allocStart; - } - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = (cbSign ? 1 : 0); - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - if (!cbSign) { - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - return; - } - - cbSign(packet, (signature) => { - signature = convertSignature(signature, keyType); - if (signature === false) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - p = this._packetRW.write.allocStart; - packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 - + 4 + algoLen + 4 + sigLen - ); - - // TODO: simply copy from original "packet" to new `packet` to avoid - // having to write each individual field a second time? - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = 1; - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); - - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - // Servers shouldn't send packet type 60 in response to signed publickey - // attempts, but if they do, interpret as type 60. - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authHostbased(username, pubKey, hostname, userlocal, cbSign) { - // TODO: Make DRY by sharing similar code with authPK() - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const hostnameLen = Buffer.byteLength(hostname); - const userlocalLen = Buffer.byteLength(userlocal); - const data = Buffer.allocUnsafe( - 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen - + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen - ); - let p = 0; - - writeUInt32BE(data, sesLen, p); - data.set(sessionID, p += 4); - - data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(data, userLen, ++p); - data.utf8Write(username, p += 4, userLen); - - writeUInt32BE(data, 14, p += userLen); - data.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(data, 9, p += 14); - data.utf8Write('hostbased', p += 4, 9); - - writeUInt32BE(data, algoLen, p += 9); - data.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(data, pubKeyLen, p += algoLen); - data.set(pubKey, p += 4); - - writeUInt32BE(data, hostnameLen, p += pubKeyLen); - data.utf8Write(hostname, p += 4, hostnameLen); - - writeUInt32BE(data, userlocalLen, p += hostnameLen); - data.utf8Write(userlocal, p += 4, userlocalLen); - - cbSign(data, (signature) => { - signature = convertSignature(signature, keyType); - if (!signature) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - const reqDataLen = (data.length - sesLen - 4); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - reqDataLen + 4 + 4 + algoLen + 4 + sigLen - ); - - bufferCopy(data, packet, 4 + sesLen, data.length, p); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - this._authsQueue.push('hostbased'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (hostbased)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authKeyboard(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 20, p += 14); - packet.utf8Write('keyboard-interactive', p += 4, 20); - - writeUInt32BE(packet, 0, p += 20); - - writeUInt32BE(packet, 0, p += 4); - - this._authsQueue.push('keyboard-interactive'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authNone(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 4, p += 14); - packet.utf8Write('none', p += 4, 4); - - this._authsQueue.push('none'); - - this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoRes(responses) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let responsesTotalLen = 0; - let responseLens; - - if (responses) { - responseLens = new Array(responses.length); - for (let i = 0; i < responses.length; ++i) { - const len = Buffer.byteLength(responses[i]); - responseLens[i] = len; - responsesTotalLen += 4 + len; - } - } - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); - - packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; - - if (responses) { - writeUInt32BE(packet, responses.length, ++p); - p += 4; - for (let i = 0; i < responses.length; ++i) { - const len = responseLens[i]; - writeUInt32BE(packet, len, p); - p += 4; - if (len) { - packet.utf8Write(responses[i], p, len); - p += len; - } - } - } else { - writeUInt32BE(packet, 0, ++p); - } - - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-connection' service-specific - // --------------------------------- - tcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 13, ++p); - packet.utf8Write('tcpip-forward', p += 4, 13); - - packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - cancelTcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 20, ++p); - packet.utf8Write('cancel-tcpip-forward', p += 4, 20); - - packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_streamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 31 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 31, ++p); - packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); - - packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_cancelStreamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 38 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 38, ++p); - packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); - - packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST ' - + '(cancel-streamlocal-forward@openssh.com)' - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - directTcpip(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const srcLen = Buffer.byteLength(cfg.srcIP); - const dstLen = Buffer.byteLength(cfg.dstIP); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 12, ++p); - packet.utf8Write('direct-tcpip', p += 4, 12); - - writeUInt32BE(packet, chan, p += 12); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, dstLen, p += 4); - packet.utf8Write(cfg.dstIP, p += 4, dstLen); - - writeUInt32BE(packet, cfg.dstPort, p += dstLen); - - writeUInt32BE(packet, srcLen, p += 4); - packet.utf8Write(cfg.srcIP, p += 4, srcLen); - - writeUInt32BE(packet, cfg.srcPort, p += srcLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 30, ++p); - packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); - - writeUInt32BE(packet, chan, p += 30); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - // zero-fill reserved fields (string and uint32) - bufferFill(packet, 0, p += pathLen, p + 8); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, direct-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_noMoreSessions(wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 28, ++p); - packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); - - packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - session(chan, initWindow, maxPacket) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 7, ++p); - packet.utf8Write('session', p += 4, 7); - - writeUInt32BE(packet, chan, p += 7); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - windowChange(chan, rows, cols, height, width) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 13, p += 4); - packet.utf8Write('window-change', p += 4, 13); - - packet[p += 13] = 0; - - writeUInt32BE(packet, cols, ++p); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - pty(chan, rows, cols, height, width, term, modes, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - if (!term || !term.length) - term = 'vt100'; - if (modes - && !Buffer.isBuffer(modes) - && !Array.isArray(modes) - && typeof modes === 'object' - && modes !== null) { - modes = modesToBytes(modes); - } - if (!modes || !modes.length) - modes = NO_TERMINAL_MODES_BUFFER; - - const termLen = term.length; - const modesLen = modes.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('pty-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, termLen, ++p); - packet.utf8Write(term, p += 4, termLen); - - writeUInt32BE(packet, cols, p += termLen); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); - - writeUInt32BE(packet, modesLen, p += 4); - p += 4; - if (Array.isArray(modes)) { - for (let i = 0; i < modesLen; ++i) - packet[p++] = modes[i]; - } else if (Buffer.isBuffer(modes)) { - packet.set(modes, p); - } - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - shell(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 5, p += 4); - packet.utf8Write('shell', p += 4, 5); - - packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exec(chan, cmd, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const isBuf = Buffer.isBuffer(cmd); - const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 4, p += 4); - packet.utf8Write('exec', p += 4, 4); - - packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, cmdLen, ++p); - if (isBuf) - packet.set(cmd, p += 4); - else - packet.utf8Write(cmd, p += 4, cmdLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - signal(chan, signal) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const origSignal = signal; - - signal = signal.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - - const signalLen = signal.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 6 + 1 + 4 + signalLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 6, p += 4); - packet.utf8Write('signal', p += 4, 6); - - packet[p += 6] = 0; - - writeUInt32BE(packet, signalLen, ++p); - packet.utf8Write(signal, p += 4, signalLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - env(chan, key, val, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const keyLen = Buffer.byteLength(key); - const isBuf = Buffer.isBuffer(val); - const valLen = (isBuf ? val.length : Buffer.byteLength(val)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 3, p += 4); - packet.utf8Write('env', p += 4, 3); - - packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, keyLen, ++p); - packet.utf8Write(key, p += 4, keyLen); - - writeUInt32BE(packet, valLen, p += keyLen); - if (isBuf) - packet.set(val, p += 4); - else - packet.utf8Write(val, p += 4, valLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11Forward(chan, cfg, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const protocol = cfg.protocol; - const cookie = cfg.cookie; - const isBufProto = Buffer.isBuffer(protocol); - const protoLen = (isBufProto - ? protocol.length - : Buffer.byteLength(protocol)); - const isBufCookie = Buffer.isBuffer(cookie); - const cookieLen = (isBufCookie - ? cookie.length - : Buffer.byteLength(cookie)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('x11-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - packet[++p] = (cfg.single ? 1 : 0); - - writeUInt32BE(packet, protoLen, ++p); - if (isBufProto) - packet.set(protocol, p += 4); - else - packet.utf8Write(protocol, p += 4, protoLen); - - writeUInt32BE(packet, cookieLen, p += protoLen); - if (isBufCookie) - packet.set(cookie, p += 4); - else - packet.latin1Write(cookie, p += 4, cookieLen); - - writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - subsystem(chan, name, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 9, p += 4); - packet.utf8Write('subsystem', p += 4, 9); - - packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_agentForward(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 26, p += 4); - packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); - - packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_REQUEST ' - + `(r:${chan}, auth-agent-req@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_hostKeysProve(keys) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let keysTotal = 0; - const publicKeys = []; - for (const key of keys) { - const publicKey = key.getPublicSSH(); - keysTotal += 4 + publicKey.length; - publicKeys.push(publicKey); - } - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 29, ++p); - packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - - packet[p += 29] = 1; // want reply - - ++p; - for (const buf of publicKeys) { - writeUInt32BE(packet, buf.length, p); - bufferCopy(buf, packet, 0, buf.length, p += 4); - p += buf.length; - } - - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - - // Global - // ------ - serviceAccept(svcName) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const svcNameLen = Buffer.byteLength(svcName); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); - - packet[p] = MESSAGE.SERVICE_ACCEPT; - - writeUInt32BE(packet, svcNameLen, ++p); - packet.utf8Write(svcName, p += 4, svcNameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._server && this._banner && svcName === 'ssh-userauth') { - const banner = this._banner; - this._banner = undefined; // Prevent banner from being displayed again - const bannerLen = Buffer.byteLength(banner); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); - - packet[p] = MESSAGE.USERAUTH_BANNER; - - writeUInt32BE(packet, bannerLen, ++p); - packet.utf8Write(banner, p += 4, bannerLen); - - writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - } - // 'ssh-connection' service-specific - forwardedTcpip(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const boundAddrLen = Buffer.byteLength(cfg.boundAddr); - const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 15, ++p); - packet.utf8Write('forwarded-tcpip', p += 4, 15); - - writeUInt32BE(packet, chan, p += 15); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, boundAddrLen, p += 4); - packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); - - writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); - - writeUInt32BE(packet, remoteAddrLen, p += 4); - packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); - - writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const addrLen = Buffer.byteLength(cfg.originAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 3, ++p); - packet.utf8Write('x11', p += 4, 3); - - writeUInt32BE(packet, chan, p += 3); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, addrLen, p += 4); - packet.utf8Write(cfg.originAddr, p += 4, addrLen); - - writeUInt32BE(packet, cfg.originPort, p += addrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_authAgent(chan, initWindow, maxPacket) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 22, ++p); - packet.utf8Write('auth-agent@openssh.com', p += 4, 22); - - writeUInt32BE(packet, chan, p += 22); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 33, ++p); - packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); - - writeUInt32BE(packet, chan, p += 33); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - writeUInt32BE(packet, 0, p += pathLen); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, forwarded-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitStatus(chan, status) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-status', p += 4, 11); - - packet[p += 11] = 0; - - writeUInt32BE(packet, status, ++p); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitSignal(chan, name, coreDumped, msg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - - const origSignal = name; - - if (typeof origSignal !== 'string' || !origSignal) - throw new Error(`Invalid signal: ${origSignal}`); - - let signal = name.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - - const nameLen = Buffer.byteLength(signal); - const msgLen = (msg ? Buffer.byteLength(msg) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-signal', p += 4, 11); - - packet[p += 11] = 0; - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(signal, p += 4, nameLen); - - packet[p += nameLen] = (coreDumped ? 1 : 0); - - writeUInt32BE(packet, msgLen, ++p); - - p += 4; - if (msgLen) { - packet.utf8Write(msg, p, msgLen); - p += msgLen; - } - - writeUInt32BE(packet, 0, p); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // 'ssh-userauth' service-specific - authFailure(authMethods, isPartial) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); - - let methods; - - if (typeof authMethods === 'boolean') { - isPartial = authMethods; - authMethods = undefined; - } - - if (authMethods) { - methods = []; - for (let i = 0; i < authMethods.length; ++i) { - if (authMethods[i].toLowerCase() === 'none') - continue; - methods.push(authMethods[i]); - } - methods = methods.join(','); - } else { - methods = ''; - } - - const methodsLen = methods.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); - - packet[p] = MESSAGE.USERAUTH_FAILURE; - - writeUInt32BE(packet, methodsLen, ++p); - packet.utf8Write(methods, p += 4, methodsLen); - - packet[p += methodsLen] = (isPartial === true ? 1 : 0); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authSuccess() { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); - - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.USERAUTH_SUCCESS; - - this._authsQueue.shift(); - this._authenticated = true; - - this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - } - authPKOK(keyAlgo, key) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') - throw new Error('"publickey" auth not in progress'); - - // TODO: support parsed key for `key` - - const keyAlgoLen = Buffer.byteLength(keyAlgo); - const keyLen = key.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); - - packet[p] = MESSAGE.USERAUTH_PK_OK; - - writeUInt32BE(packet, keyAlgoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); - - writeUInt32BE(packet, keyLen, p += keyAlgoLen); - packet.set(key, p += 4); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPasswdChg(prompt) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const promptLen = Buffer.byteLength(prompt); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - - packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; - - writeUInt32BE(packet, promptLen, ++p); - packet.utf8Write(prompt, p += 4, promptLen); - - writeUInt32BE(packet, 0, p += promptLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoReq(name, instructions, prompts) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let promptsLen = 0; - const nameLen = name ? Buffer.byteLength(name) : 0; - const instrLen = instructions ? Buffer.byteLength(instructions) : 0; - - for (let i = 0; i < prompts.length; ++i) - promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen - ); - - packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - p += 4; - if (name) { - packet.utf8Write(name, p, nameLen); - p += nameLen; - } - - writeUInt32BE(packet, instrLen, p); - p += 4; - if (instructions) { - packet.utf8Write(instructions, p, instrLen); - p += instrLen; - } - - writeUInt32BE(packet, 0, p); - - writeUInt32BE(packet, prompts.length, p += 4); - p += 4; - for (let i = 0; i < prompts.length; ++i) { - const prompt = prompts[i]; - const promptLen = Buffer.byteLength(prompt.prompt); - - writeUInt32BE(packet, promptLen, p); - p += 4; - if (promptLen) { - packet.utf8Write(prompt.prompt, p, promptLen); - p += promptLen; - } - packet[p++] = (prompt.echo ? 1 : 0); - } - - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } -} - -// SSH-protoversion-softwareversion (SP comments) CR LF -const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; - -// TODO: optimize this by starting n bytes from the end of this._buffer instead -// of the beginning -function parseHeader(chunk, p, len) { - let data; - let chunkOffset; - if (this._buffer) { - data = Buffer.allocUnsafe(this._buffer.length + (len - p)); - data.set(this._buffer, 0); - if (p === 0) { - data.set(chunk, this._buffer.length); - } else { - data.set(new Uint8Array(chunk.buffer, - chunk.byteOffset + p, - (len - p)), - this._buffer.length); - } - chunkOffset = this._buffer.length; - p = 0; - } else { - data = chunk; - chunkOffset = 0; - } - const op = p; - let start = p; - let end = p; - let needNL = false; - let lineLen = 0; - let lines = 0; - for (; p < data.length; ++p) { - const ch = data[p]; - - if (ch === 13 /* '\r' */) { - needNL = true; - continue; - } - - if (ch === 10 /* '\n' */) { - if (end > start - && end - start > 4 - && data[start] === 83 /* 'S' */ - && data[start + 1] === 83 /* 'S' */ - && data[start + 2] === 72 /* 'H' */ - && data[start + 3] === 45 /* '-' */) { - - const full = data.latin1Slice(op, end + 1); - const identRaw = (start === op ? full : full.slice(start - op)); - const m = RE_IDENT.exec(identRaw); - if (!m) - throw new Error('Invalid identification string'); - - const header = { - greeting: (start === op ? '' : full.slice(0, start - op)), - identRaw, - versions: { - protocol: m[1], - software: m[2], - }, - comments: m[3] - }; - - // Needed during handshake - this._remoteIdentRaw = Buffer.from(identRaw); - - this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); - this._compatFlags = getCompatFlags(header); - - this._buffer = undefined; - this._decipher = - new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); - this._parse = parsePacket; - - this._onHeader(header); - if (!this._destruct) { - // We disconnected inside _onHeader - return len; - } - - kexinit(this); - - return p + 1 - chunkOffset; - } - - // Only allow pre-ident greetings when we're a client - if (this._server) - throw new Error('Greetings from clients not permitted'); - - if (++lines > MAX_LINES) - throw new Error('Max greeting lines exceeded'); - - needNL = false; - start = p + 1; - lineLen = 0; - } else if (needNL) { - throw new Error('Invalid header: expected newline'); - } else if (++lineLen >= MAX_LINE_LEN) { - throw new Error('Header line too long'); - } - - end = p; - } - if (!this._buffer) - this._buffer = bufferSlice(data, op); - - return p - chunkOffset; -} - -function parsePacket(chunk, p, len) { - return this._decipher.decrypt(chunk, p, len); -} - -function onPayload(payload) { - // XXX: move this to the Decipher implementations? - - this._onPacket(); - - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - payload = this._packetRW.read.read(payload); - - const type = payload[0]; - if (type === MESSAGE.USERAUTH_SUCCESS - && !this._server - && !this._authenticated) { - this._authenticated = true; - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - } - const handler = MESSAGE_HANDLERS[type]; - if (handler === undefined) { - this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); - return; - } - - return handler(this, payload); -} - -function getCompatFlags(header) { - const software = header.versions.software; - - let flags = 0; - - for (const rule of COMPAT_CHECKS) { - if (typeof rule[0] === 'string') { - if (software === rule[0]) - flags |= rule[1]; - } else if (rule[0].test(software)) { - flags |= rule[1]; - } - } - - return flags; -} - -function modesToBytes(modes) { - const keys = Object.keys(modes); - const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); - let b = 0; - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === 'TTY_OP_END') - continue; - - const opcode = TERMINAL_MODE[key]; - if (opcode === undefined) - continue; - - const val = modes[key]; - if (typeof val === 'number' && isFinite(val)) { - bytes[b++] = opcode; - bytes[b++] = val >>> 24; - bytes[b++] = val >>> 16; - bytes[b++] = val >>> 8; - bytes[b++] = val; - } - } - - bytes[b++] = TERMINAL_MODE.TTY_OP_END; - - if (b < bytes.length) - return bufferSlice(bytes, 0, b); - - return bytes; -} - -module.exports = Protocol; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/SFTP.js b/reverse_engineering/node_modules/ssh2/lib/protocol/SFTP.js deleted file mode 100644 index b10d9e5..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/SFTP.js +++ /dev/null @@ -1,3778 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const fs = require('fs'); -const { constants } = fs; -const { - Readable: ReadableStream, - Writable: WritableStream -} = require('stream'); -const { inherits, isDate } = require('util'); - -const FastBuffer = Buffer[Symbol.species]; - -const { - bufferCopy, - bufferSlice, - makeBufferParser, - writeUInt32BE, -} = require('./utils.js'); - -const ATTR = { - SIZE: 0x00000001, - UIDGID: 0x00000002, - PERMISSIONS: 0x00000004, - ACMODTIME: 0x00000008, - EXTENDED: 0x80000000, -}; - -// Large enough to store all possible attributes -const ATTRS_BUF = Buffer.alloc(28); - -const STATUS_CODE = { - OK: 0, - EOF: 1, - NO_SUCH_FILE: 2, - PERMISSION_DENIED: 3, - FAILURE: 4, - BAD_MESSAGE: 5, - NO_CONNECTION: 6, - CONNECTION_LOST: 7, - OP_UNSUPPORTED: 8 -}; - -const VALID_STATUS_CODES = new Map( - Object.values(STATUS_CODE).map((n) => [n, 1]) -); - -const STATUS_CODE_STR = { - [STATUS_CODE.OK]: 'No error', - [STATUS_CODE.EOF]: 'End of file', - [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', - [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', - [STATUS_CODE.FAILURE]: 'Failure', - [STATUS_CODE.BAD_MESSAGE]: 'Bad message', - [STATUS_CODE.NO_CONNECTION]: 'No connection', - [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', - [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', -}; - -const REQUEST = { - INIT: 1, - OPEN: 3, - CLOSE: 4, - READ: 5, - WRITE: 6, - LSTAT: 7, - FSTAT: 8, - SETSTAT: 9, - FSETSTAT: 10, - OPENDIR: 11, - READDIR: 12, - REMOVE: 13, - MKDIR: 14, - RMDIR: 15, - REALPATH: 16, - STAT: 17, - RENAME: 18, - READLINK: 19, - SYMLINK: 20, - EXTENDED: 200 -}; - -const RESPONSE = { - VERSION: 2, - STATUS: 101, - HANDLE: 102, - DATA: 103, - NAME: 104, - ATTRS: 105, - EXTENDED: 201 -}; - -const OPEN_MODE = { - READ: 0x00000001, - WRITE: 0x00000002, - APPEND: 0x00000004, - CREAT: 0x00000008, - TRUNC: 0x00000010, - EXCL: 0x00000020 -}; - -const PKT_RW_OVERHEAD = 2 * 1024; -const MAX_REQID = 2 ** 32 - 1; -const CLIENT_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - REQUEST.INIT, - 0, 0, 0, 3 /* version */ -]); -const SERVER_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - RESPONSE.VERSION, - 0, 0, 0, 3 /* version */ -]); - -const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; -const OPENSSH_MAX_PKT_LEN = 256 * 1024; - -const bufferParser = makeBufferParser(); - -const fakeStderr = { - readable: false, - writable: false, - push: (data) => {}, - once: () => {}, - on: () => {}, - emit: () => {}, - end: () => {}, -}; - -function noop() {} - -// Emulates enough of `Channel` to be able to be used as a drop-in replacement -// in order to process incoming data with as little overhead as possible -class SFTP extends EventEmitter { - constructor(client, chanInfo, cfg) { - super(); - - if (typeof cfg !== 'object' || !cfg) - cfg = {}; - - const remoteIdentRaw = client._protocol._remoteIdentRaw; - - this.server = !!cfg.server; - this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); - - this._version = -1; - this._extensions = {}; - this._biOpt = cfg.biOpt; - this._pktLenBytes = 0; - this._pktLen = 0; - this._pktPos = 0; - this._pktType = 0; - this._pktData = undefined; - this._writeReqid = -1; - this._requests = {}; - this._maxInPktLen = OPENSSH_MAX_PKT_LEN; - this._maxOutPktLen = 34000; - this._maxReadLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - this._maxWriteLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - - this.maxOpenHandles = undefined; - - // Channel compatibility - this._client = client; - this._protocol = client._protocol; - this._callbacks = []; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - this._waitWindow = false; // SSH-level backpressure - this._chunkcb = undefined; - this._buffer = []; - this.type = chanInfo.type; - this.subtype = undefined; - this.incoming = chanInfo.incoming; - this.outgoing = chanInfo.outgoing; - this.stderr = fakeStderr; - this.readable = true; - } - - // This handles incoming data to parse - push(data) { - if (data === null) { - cleanupRequests(this); - if (!this.readable) - return; - // No more incoming data from the remote side - this.readable = false; - this.emit('end'); - return; - } - /* - uint32 length - byte type - byte[length - 1] data payload - */ - let p = 0; - - while (p < data.length) { - if (this._pktLenBytes < 4) { - let nb = Math.min(4 - this._pktLenBytes, data.length - p); - this._pktLenBytes += nb; - - while (nb--) - this._pktLen = (this._pktLen << 8) + data[p++]; - - if (this._pktLenBytes < 4) - return; - if (this._pktLen === 0) - return doFatalSFTPError(this, 'Invalid packet length'); - if (this._pktLen > this._maxInPktLen) { - const max = this._maxInPktLen; - return doFatalSFTPError( - this, - `Packet length ${this._pktLen} exceeds max length of ${max}` - ); - } - if (p >= data.length) - return; - } - if (this._pktPos < this._pktLen) { - const nb = Math.min(this._pktLen - this._pktPos, data.length - p); - if (p !== 0 || nb !== data.length) { - if (nb === this._pktLen) { - this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._pktPos - ); - } - } else if (nb === this._pktLen) { - this._pkt = data; - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set(data, this._pktPos); - } - p += nb; - this._pktPos += nb; - if (this._pktPos < this._pktLen) - return; - } - - const type = this._pkt[0]; - const payload = this._pkt; - - // Prepare for next packet - this._pktLen = 0; - this._pktLenBytes = 0; - this._pkt = undefined; - this._pktPos = 0; - - const handler = (this.server - ? SERVER_HANDLERS[type] - : CLIENT_HANDLERS[type]); - if (!handler) - return doFatalSFTPError(this, `Unknown packet type ${type}`); - - if (this._version === -1) { - if (this.server) { - if (type !== REQUEST.INIT) - return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); - } else if (type !== RESPONSE.VERSION) { - return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); - } - } - - if (handler(this, payload) === false) - return; - } - } - - end() { - this.destroy(); - } - destroy() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._protocol.channelClose(this.outgoing.id); - } - } - _init() { - this._init = noop; - if (!this.server) - sendOrBuffer(this, CLIENT_VERSION_BUFFER); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - createReadStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new ReadStream(this, path, options); - } - createWriteStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new WriteStream(this, path, options); - } - open(path, flags_, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; - } - - const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); - if (flags === null) - throw new Error(`Unknown flags string: ${flags_}`); - - let attrsFlags = 0; - let attrsLen = 0; - if (typeof attrs === 'string' || typeof attrs === 'number') - attrs = { mode: attrs }; - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - attrsFlags = attrs.flags; - attrsLen = attrs.nb; - } - - /* - uint32 id - string filename - uint32 pflags - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPEN; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - writeUInt32BE(buf, attrsFlags, p += 4); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` - ); - } - close(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.CLOSE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` - ); - } - read(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off >= buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - - read_(this, handle, buf, off, len, position, cb); - } - readData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.read(handle, buf, off, len, position, cb); - } - write(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off > buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - - if (!len) { - cb && process.nextTick(cb, undefined, 0); - return; - } - - const maxDataLen = this._maxWriteLen; - const overflow = Math.max(len - maxDataLen, 0); - const origPosition = position; - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - string data - */ - const handleLen = handle.length; - let p = 9; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.WRITE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = position & 0xFF; - position /= 256; - } - writeUInt32BE(out, len, p += 8); - bufferCopy(buf, out, off, off + len, p += 4); - - this._requests[reqid] = { - cb: (err) => { - if (err) { - if (typeof cb === 'function') - cb(err); - } else if (overflow) { - this.write(handle, - buf, - off + len, - overflow, - origPosition + len, - cb); - } else if (typeof cb === 'function') { - cb(undefined, off + len); - } - } - }; - - const isSent = sendOrBuffer(this, out); - if (this._debug) { - const how = (isSent ? 'Sent' : 'Buffered'); - this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); - } - } - writeData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.write(handle, buf, off, len, position, cb); - } - fastGet(remotePath, localPath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(this, fs, remotePath, localPath, opts, cb); - } - fastPut(localPath, remotePath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(fs, this, localPath, remotePath, opts, cb); - } - readFile(path, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'string') - options = { encoding: options, flag: 'r' }; - else if (!options) - options = { encoding: null, flag: 'r' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - const encoding = options.encoding; - if (encoding && !Buffer.isEncoding(encoding)) - throw new Error(`Unknown encoding: ${encoding}`); - - // First stat the file, so we know the size. - let size; - let buffer; // Single buffer with file data - let buffers; // List for when size is unknown - let pos = 0; - let handle; - - // SFTPv3 does not support using -1 for read position, so we have to track - // read position manually - let bytesRead = 0; - - const flag = options.flag || 'r'; - - const read = () => { - if (size === 0) { - buffer = Buffer.allocUnsafe(8192); - this.read(handle, buffer, 0, 8192, bytesRead, afterRead); - } else { - this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); - } - }; - - const afterRead = (er, nbytes) => { - let eof; - if (er) { - eof = (er.code === STATUS_CODE.EOF); - if (!eof) { - return this.close(handle, () => { - return callback && callback(er); - }); - } - } else { - eof = false; - } - - if (eof || (size === 0 && nbytes === 0)) - return close(); - - bytesRead += nbytes; - pos += nbytes; - if (size !== 0) { - if (pos === size) - close(); - else - read(); - } else { - // Unknown size, just read until we don't get bytes. - buffers.push(bufferSlice(buffer, 0, nbytes)); - read(); - } - }; - afterRead._wantEOFError = true; - - const close = () => { - this.close(handle, (er) => { - if (size === 0) { - // Collect the data into the buffers list. - buffer = Buffer.concat(buffers, pos); - } else if (pos < size) { - buffer = bufferSlice(buffer, 0, pos); - } - - if (encoding) - buffer = buffer.toString(encoding); - return callback && callback(er, buffer); - }); - }; - - this.open(path, flag, 0o666, (er, handle_) => { - if (er) - return callback && callback(er); - handle = handle_; - - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - - size = st.size || 0; - if (size === 0) { - // The kernel lies about many files. - // Go ahead and try to read some bytes. - buffers = []; - return read(); - } - - buffer = Buffer.allocUnsafe(size); - read(); - }; - this.fstat(handle, tryStat); - }); - } - writeFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'w' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (options.encoding && !Buffer.isEncoding(options.encoding)) - throw new Error(`Unknown encoding: ${options.encoding}`); - - const flag = options.flag || 'w'; - this.open(path, flag, options.mode, (openErr, handle) => { - if (openErr) { - callback && callback(openErr); - } else { - const buffer = (Buffer.isBuffer(data) - ? data - : Buffer.from('' + data, options.encoding || 'utf8')); - const position = (/a/.test(flag) ? null : 0); - - // SFTPv3 does not support the notion of 'current position' - // (null position), so we just attempt to append to the end of the file - // instead - if (position === null) { - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); - }; - this.fstat(handle, tryStat); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, position, callback); - } - }); - } - appendFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'a' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (!options.flag) - options = Object.assign({ flag: 'a' }, options); - this.writeFile(path, data, options, callback); - } - exists(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - this.stat(path, (err) => { - cb && cb(err ? false : true); - }); - } - unlink(filename, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string filename - */ - const fnameLen = Buffer.byteLength(filename); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REMOVE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, fnameLen, p); - buf.utf8Write(filename, p += 4, fnameLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` - ); - } - rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RENAME; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, oldLen, p); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` - ); - } - mkdir(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; - } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.MKDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` - ); - } - rmdir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RMDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` - ); - } - readdir(where, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - if (typeof opts !== 'object' || opts === null) - opts = {}; - - const doFilter = (opts && opts.full ? false : true); - - if (!Buffer.isBuffer(where) && typeof where !== 'string') - throw new Error('missing directory handle or path'); - - if (typeof where === 'string') { - const entries = []; - let e = 0; - - const reread = (err, handle) => { - if (err) - return cb(err); - - this.readdir(handle, opts, (err, list) => { - const eof = (err && err.code === STATUS_CODE.EOF); - - if (err && !eof) - return this.close(handle, () => cb(err)); - - if (eof) { - return this.close(handle, (err) => { - if (err) - return cb(err); - cb(undefined, entries); - }); - } - - for (let i = 0; i < list.length; ++i, ++e) - entries[e] = list[i]; - - reread(undefined, handle); - }); - }; - return this.opendir(where, reread); - } - - /* - uint32 id - string handle - */ - const handleLen = where.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(where, p += 4); - - this._requests[reqid] = { - cb: (doFilter - ? (err, list) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - - for (let i = list.length - 1; i >= 0; --i) { - if (list[i].filename === '.' || list[i].filename === '..') - list.splice(i, 1); - } - - cb(undefined, list); - } - : cb) - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` - ); - } - fstat(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` - ); - } - stat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.STAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` - ); - } - lstat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.LSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` - ); - } - opendir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPENDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` - ); - } - setstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` - ); - } - fsetstat(handle, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string handle - ATTRS attrs - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - writeUInt32BE(buf, flags, p += handleLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` - ); - } - futimes(handle, atime, mtime, cb) { - return this.fsetstat(handle, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - utimes(path, atime, mtime, cb) { - return this.setstat(path, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - fchown(handle, uid, gid, cb) { - return this.fsetstat(handle, { - uid: uid, - gid: gid - }, cb); - } - chown(path, uid, gid, cb) { - return this.setstat(path, { - uid: uid, - gid: gid - }, cb); - } - fchmod(handle, mode, cb) { - return this.fsetstat(handle, { - mode: mode - }, cb); - } - chmod(path, mode, cb) { - return this.setstat(path, { - mode: mode - }, cb); - } - readlink(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing link info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` - ); - } - symlink(targetPath, linkPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string linkpath - string targetpath - */ - const linkLen = Buffer.byteLength(linkPath); - const targetLen = Buffer.byteLength(targetPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SYMLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - if (this._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - writeUInt32BE(buf, targetLen, p); - buf.utf8Write(targetPath, p += 4, targetLen); - writeUInt32BE(buf, linkLen, p += targetLen); - buf.utf8Write(linkPath, p += 4, linkLen); - } else { - writeUInt32BE(buf, linkLen, p); - buf.utf8Write(linkPath, p += 4, linkLen); - writeUInt32BE(buf, targetLen, p += linkLen); - buf.utf8Write(targetPath, p += 4, targetLen); - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` - ); - } - realpath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REALPATH; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing path info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` - ); - } - // extended requests - ext_openssh_rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['posix-rename@openssh.com']; - if (!ext || ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "posix-rename@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 24, p); - buf.utf8Write('posix-rename@openssh.com', p += 4, 24); - writeUInt32BE(buf, oldLen, p += 24); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); - } - } - ext_openssh_statvfs(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['statvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "statvfs@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 19, p); - buf.utf8Write('statvfs@openssh.com', p += 4, 19); - writeUInt32BE(buf, pathLen, p += 19); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); - } - } - ext_openssh_fstatvfs(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fstatvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fstatvfs@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); - writeUInt32BE(buf, handleLen, p += 20); - buf.set(handle, p += 4); - - this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); - } - } - ext_openssh_hardlink(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['hardlink@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "hardlink@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('hardlink@openssh.com', p += 4, 20); - writeUInt32BE(buf, oldLen, p += 20); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); - } - } - ext_openssh_fsync(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fsync@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fsync@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 17, p); - buf.utf8Write('fsync@openssh.com', p += 4, 17); - writeUInt32BE(buf, handleLen, p += 17); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` - ); - } - ext_openssh_lsetstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['lsetstat@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string "lsetstat@openssh.com" - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('lsetstat@openssh.com', p += 4, 20); - - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); - } - } - ext_openssh_expandPath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['expand-path@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "expand-path@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 23, p); - buf.utf8Write('expand-path@openssh.com', p += 4, 23); - - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); - } - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - handle(reqid, handle) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - const handleLen = handle.length; - - if (handleLen > 256) - throw new Error('handle too large (> 256 bytes)'); - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.HANDLE; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - if (handleLen) - buf.set(handle, p += 4); - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` - ); - } - status(reqid, code, message) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!VALID_STATUS_CODES.has(code)) - throw new Error(`Bad status code: ${code}`); - - message || (message = ''); - - const msgLen = Buffer.byteLength(message); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.STATUS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, code, p); - - writeUInt32BE(buf, msgLen, p += 4); - p += 4; - if (msgLen) { - buf.utf8Write(message, p, msgLen); - p += msgLen; - } - - writeUInt32BE(buf, 0, p); // Empty language tag - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` - ); - } - data(reqid, data, encoding) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - const isBuffer = Buffer.isBuffer(data); - - if (!isBuffer && typeof data !== 'string') - throw new Error('data is not a Buffer or string'); - - let isUTF8; - if (!isBuffer && !encoding) { - encoding = undefined; - isUTF8 = true; - } - - const dataLen = ( - isBuffer - ? data.length - : Buffer.byteLength(data, encoding) - ); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.DATA; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, dataLen, p); - if (dataLen) { - if (isBuffer) - buf.set(data, p += 4); - else if (isUTF8) - buf.utf8Write(data, p += 4, dataLen); - else - buf.write(data, p += 4, dataLen, encoding); - } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` - ); - } - name(reqid, names) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Array.isArray(names)) { - if (typeof names !== 'object' || names === null) - throw new Error('names is not an object or array'); - names = [ names ]; - } - - const count = names.length; - let namesLen = 0; - let nameAttrs; - const attrs = []; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - namesLen += 4 + Buffer.byteLength(filename); - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - namesLen += 4 + Buffer.byteLength(longname); - - if (typeof name.attrs === 'object' && name.attrs !== null) { - nameAttrs = attrsToBytes(name.attrs); - namesLen += 4 + nameAttrs.nb; - - if (nameAttrs.nb) { - let bytes; - - if (nameAttrs.nb === ATTRS_BUF.length) { - bytes = new Uint8Array(ATTRS_BUF); - } else { - bytes = new Uint8Array(nameAttrs.nb); - bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); - } - - nameAttrs.bytes = bytes; - } - - attrs.push(nameAttrs); - } else { - namesLen += 4; - attrs.push(null); - } - } - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.NAME; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, count, p); - - p += 4; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - - { - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - const len = Buffer.byteLength(filename); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(filename, p, len); - p += len; - } - } - - { - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - const len = Buffer.byteLength(longname); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(longname, p, len); - p += len; - } - } - - const attr = attrs[i]; - if (attr) { - writeUInt32BE(buf, attr.flags, p); - p += 4; - if (attr.flags && attr.bytes) { - buf.set(attr.bytes, p); - p += attr.nb; - } - } else { - writeUInt32BE(buf, 0, p); - p += 4; - } - } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` - ); - } - attrs(reqid, attrs) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (typeof attrs !== 'object' || attrs === null) - throw new Error('attrs is not an object'); - - attrs = attrsToBytes(attrs); - const flags = attrs.flags; - const attrsLen = attrs.nb; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.ATTRS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, flags, p); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` - ); - } -} - -function tryCreateBuffer(size) { - try { - return Buffer.allocUnsafe(size); - } catch (ex) { - return ex; - } -} - -function read_(self, handle, buf, off, len, position, cb, req_) { - const maxDataLen = self._maxReadLen; - const overflow = Math.max(len - maxDataLen, 0); - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - uint32 len - */ - const handleLen = handle.length; - let p = 9; - let pos = position; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.READ; - const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = pos & 0xFF; - pos /= 256; - } - writeUInt32BE(out, len, p += 8); - - if (typeof cb !== 'function') - cb = noop; - - const req = (req_ || { - nb: 0, - position, - off, - origOff: off, - len: undefined, - overflow: undefined, - cb: (err, data, nb) => { - const len = req.len; - const overflow = req.overflow; - - if (err) { - if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) - return cb(err); - } else if (nb > len) { - return cb(new Error('Received more data than requested')); - } else if (nb === len && overflow) { - req.nb += nb; - req.position += nb; - req.off += nb; - read_(self, handle, buf, req.off, overflow, req.position, cb, req); - return; - } - - if (req.origOff === 0 && buf.length === req.nb) - data = buf; - else - data = bufferSlice(buf, req.origOff, req.origOff + req.nb); - cb(undefined, req.nb + (nb || 0), data, req.position); - }, - buffer: undefined, - }); - - req.len = len; - req.overflow = overflow; - - // TODO: avoid creating multiple buffer slices when we need to re-call read_() - // because of overflow - req.buffer = bufferSlice(buf, off, off + len); - - self._requests[reqid] = req; - - const isBuffered = sendOrBuffer(self, out); - self._debug && self._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` - ); -} - -function fastXfer(src, dst, srcPath, dstPath, opts, cb) { - let concurrency = 64; - let chunkSize = 32768; - let onstep; - let mode; - let fileSize; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.concurrency === 'number' - && opts.concurrency > 0 - && !isNaN(opts.concurrency)) { - concurrency = opts.concurrency; - } - if (typeof opts.chunkSize === 'number' - && opts.chunkSize > 0 - && !isNaN(opts.chunkSize)) { - chunkSize = opts.chunkSize; - } - if (typeof opts.fileSize === 'number' - && opts.fileSize > 0 - && !isNaN(opts.fileSize)) { - fileSize = opts.fileSize; - } - if (typeof opts.step === 'function') - onstep = opts.step; - - if (typeof opts.mode === 'string' || typeof opts.mode === 'number') - mode = modeNum(opts.mode); - } - - // Internal state variables - let fsize; - let pdst = 0; - let total = 0; - let hadError = false; - let srcHandle; - let dstHandle; - let readbuf; - let bufsize = chunkSize * concurrency; - - function onerror(err) { - if (hadError) - return; - - hadError = true; - - let left = 0; - let cbfinal; - - if (srcHandle || dstHandle) { - cbfinal = () => { - if (--left === 0) - cb(err); - }; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - ++left; - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - ++left; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - dst.close(dstHandle, cbfinal); - } else { - cb(err); - } - } - - src.open(srcPath, 'r', (err, sourceHandle) => { - if (err) - return onerror(err); - - srcHandle = sourceHandle; - - if (fileSize === undefined) - src.fstat(srcHandle, tryStat); - else - tryStat(null, { size: fileSize }); - - function tryStat(err, attrs) { - if (err) { - if (src !== fs) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - src.stat(srcPath, (err_, attrs_) => { - if (err_) - return onerror(err); - tryStat(null, attrs_); - }); - return; - } - return onerror(err); - } - fsize = attrs.size; - - dst.open(dstPath, 'w', (err, destHandle) => { - if (err) - return onerror(err); - - dstHandle = destHandle; - - if (fsize <= 0) - return onerror(); - - // Use less memory where possible - while (bufsize > fsize) { - if (concurrency === 1) { - bufsize = fsize; - break; - } - bufsize -= chunkSize; - --concurrency; - } - - readbuf = tryCreateBuffer(bufsize); - if (readbuf instanceof Error) - return onerror(readbuf); - - if (mode !== undefined) { - dst.fchmod(dstHandle, mode, function tryAgain(err) { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() - // for whatever reason - dst.chmod(dstPath, mode, (err_) => tryAgain()); - return; - } - startReads(); - }); - } else { - startReads(); - } - - function onread(err, nb, data, dstpos, datapos, origChunkLen) { - if (err) - return onerror(err); - - datapos = datapos || 0; - - dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); - - function writeCb(err) { - if (err) - return onerror(err); - - total += nb; - onstep && onstep(total, nb, fsize); - - if (nb < origChunkLen) - return singleRead(datapos, dstpos + nb, origChunkLen - nb); - - if (total === fsize) { - dst.close(dstHandle, (err) => { - dstHandle = undefined; - if (err) - return onerror(err); - src.close(srcHandle, (err) => { - srcHandle = undefined; - if (err) - return onerror(err); - cb(); - }); - }); - return; - } - - if (pdst >= fsize) - return; - - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(datapos, pdst, chunk); - pdst += chunk; - } - } - - function makeCb(psrc, pdst, chunk) { - return (err, nb, data) => { - onread(err, nb, data, pdst, psrc, chunk); - }; - } - - function singleRead(psrc, pdst, chunk) { - src.read(srcHandle, - readbuf, - psrc, - chunk, - pdst, - makeCb(psrc, pdst, chunk)); - } - - function startReads() { - let reads = 0; - let psrc = 0; - while (pdst < fsize && reads < concurrency) { - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(psrc, pdst, chunk); - psrc += chunk; - pdst += chunk; - ++reads; - } - } - }); - } - }); -} - -function writeAll(sftp, handle, buffer, offset, length, position, callback_) { - const callback = (typeof callback_ === 'function' ? callback_ : undefined); - - sftp.write(handle, - buffer, - offset, - length, - position, - (writeErr, written) => { - if (writeErr) { - return sftp.close(handle, () => { - callback && callback(writeErr); - }); - } - if (written === length) { - sftp.close(handle, callback); - } else { - offset += written; - length -= written; - position += written; - writeAll(sftp, handle, buffer, offset, length, position, callback); - } - }); -} - -class Stats { - constructor(initial) { - this.mode = (initial && initial.mode); - this.uid = (initial && initial.uid); - this.gid = (initial && initial.gid); - this.size = (initial && initial.size); - this.atime = (initial && initial.atime); - this.mtime = (initial && initial.mtime); - this.extended = (initial && initial.extended); - } - isDirectory() { - return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); - } - isFile() { - return ((this.mode & constants.S_IFMT) === constants.S_IFREG); - } - isBlockDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); - } - isCharacterDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); - } - isSymbolicLink() { - return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); - } - isFIFO() { - return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); - } - isSocket() { - return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); - } -} - -function attrsToBytes(attrs) { - let flags = 0; - let nb = 0; - - if (typeof attrs === 'object' && attrs !== null) { - if (typeof attrs.size === 'number') { - flags |= ATTR.SIZE; - const val = attrs.size; - // Big Endian - ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 - ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 - ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 - ATTRS_BUF[nb++] = val / 4294967296; // 2**32 - ATTRS_BUF[nb++] = val / 16777216; // 2**24 - ATTRS_BUF[nb++] = val / 65536; // 2**16 - ATTRS_BUF[nb++] = val / 256; // 2**8 - ATTRS_BUF[nb++] = val; - } - if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { - flags |= ATTR.UIDGID; - const uid = attrs.uid; - const gid = attrs.gid; - // Big Endian - ATTRS_BUF[nb++] = uid >>> 24; - ATTRS_BUF[nb++] = uid >>> 16; - ATTRS_BUF[nb++] = uid >>> 8; - ATTRS_BUF[nb++] = uid; - ATTRS_BUF[nb++] = gid >>> 24; - ATTRS_BUF[nb++] = gid >>> 16; - ATTRS_BUF[nb++] = gid >>> 8; - ATTRS_BUF[nb++] = gid; - } - if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { - const mode = modeNum(attrs.mode); - flags |= ATTR.PERMISSIONS; - // Big Endian - ATTRS_BUF[nb++] = mode >>> 24; - ATTRS_BUF[nb++] = mode >>> 16; - ATTRS_BUF[nb++] = mode >>> 8; - ATTRS_BUF[nb++] = mode; - } - if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) - && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { - const atime = toUnixTimestamp(attrs.atime); - const mtime = toUnixTimestamp(attrs.mtime); - - flags |= ATTR.ACMODTIME; - // Big Endian - ATTRS_BUF[nb++] = atime >>> 24; - ATTRS_BUF[nb++] = atime >>> 16; - ATTRS_BUF[nb++] = atime >>> 8; - ATTRS_BUF[nb++] = atime; - ATTRS_BUF[nb++] = mtime >>> 24; - ATTRS_BUF[nb++] = mtime >>> 16; - ATTRS_BUF[nb++] = mtime >>> 8; - ATTRS_BUF[nb++] = mtime; - } - // TODO: extended attributes - } - - return { flags, nb }; -} - -function toUnixTimestamp(time) { - // eslint-disable-next-line no-self-compare - if (typeof time === 'number' && time === time) // Valid, non-NaN number - return time; - if (isDate(time)) - return parseInt(time.getTime() / 1000, 10); - throw new Error(`Cannot parse time: ${time}`); -} - -function modeNum(mode) { - // eslint-disable-next-line no-self-compare - if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number - return mode; - if (typeof mode === 'string') - return modeNum(parseInt(mode, 8)); - throw new Error(`Cannot parse mode: ${mode}`); -} - -const stringFlagMap = { - 'r': OPEN_MODE.READ, - 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, - 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL -}; - -function stringToFlags(str) { - const flags = stringFlagMap[str]; - return (flags !== undefined ? flags : null); -} - -const flagsToString = (() => { - const stringFlagMapKeys = Object.keys(stringFlagMap); - return (flags) => { - for (let i = 0; i < stringFlagMapKeys.length; ++i) { - const key = stringFlagMapKeys[i]; - if (stringFlagMap[key] === flags) - return key; - } - return null; - }; -})(); - -function readAttrs(biOpt) { - /* - uint32 flags - uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - string extended_type - string extended_data - ... more extended data (extended_type - extended_data pairs), - so that number of pairs equals extended_count - */ - const flags = bufferParser.readUInt32BE(); - if (flags === undefined) - return; - - const attrs = new Stats(); - if (flags & ATTR.SIZE) { - const size = bufferParser.readUInt64BE(biOpt); - if (size === undefined) - return; - attrs.size = size; - } - - if (flags & ATTR.UIDGID) { - const uid = bufferParser.readUInt32BE(); - const gid = bufferParser.readUInt32BE(); - if (gid === undefined) - return; - attrs.uid = uid; - attrs.gid = gid; - } - - if (flags & ATTR.PERMISSIONS) { - const mode = bufferParser.readUInt32BE(); - if (mode === undefined) - return; - attrs.mode = mode; - } - - if (flags & ATTR.ACMODTIME) { - const atime = bufferParser.readUInt32BE(); - const mtime = bufferParser.readUInt32BE(); - if (mtime === undefined) - return; - attrs.atime = atime; - attrs.mtime = mtime; - } - - if (flags & ATTR.EXTENDED) { - const count = bufferParser.readUInt32BE(); - if (count === undefined) - return; - const extended = {}; - for (let i = 0; i < count; ++i) { - const type = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data === undefined) - return; - extended[type] = data; - } - attrs.extended = extended; - } - - return attrs; -} - -function sendOrBuffer(sftp, payload) { - const ret = tryWritePayload(sftp, payload); - if (ret !== undefined) { - sftp._buffer.push(ret); - return false; - } - return true; -} - -function tryWritePayload(sftp, payload) { - const outgoing = sftp.outgoing; - if (outgoing.state !== 'open') - return; - - if (outgoing.window === 0) { - sftp._waitWindow = true; // XXX: Unnecessary? - return payload; - } - - let ret; - const len = payload.length; - let p = 0; - - while (len - p > 0 && outgoing.window > 0) { - const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); - outgoing.window -= actualLen; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - } - - if (p === 0 && actualLen === len) { - sftp._protocol.channelData(sftp.outgoing.id, payload); - } else { - sftp._protocol.channelData(sftp.outgoing.id, - bufferSlice(payload, p, p + actualLen)); - } - - p += actualLen; - } - - if (len - p > 0) { - if (p > 0) - ret = bufferSlice(payload, p, len); - else - ret = payload; // XXX: should never get here? - } - - return ret; -} - -function drainBuffer() { - this._chunkcb = undefined; - const buffer = this._buffer; - let i = 0; - while (i < buffer.length) { - const payload = buffer[i]; - const ret = tryWritePayload(this, payload); - if (ret !== undefined) { - if (ret !== payload) - buffer[i] = ret; - if (i > 0) - this._buffer = buffer.slice(i); - return; - } - ++i; - } - if (i > 0) - this._buffer = []; -} - -function doFatalSFTPError(sftp, msg, noDebug) { - const err = new Error(msg); - err.level = 'sftp-protocol'; - if (!noDebug && sftp._debug) - sftp._debug(`SFTP: Inbound: ${msg}`); - sftp.emit('error', err); - sftp.destroy(); - cleanupRequests(sftp); - return false; -} - -function cleanupRequests(sftp) { - const keys = Object.keys(sftp._requests); - if (keys.length === 0) - return; - - const reqs = sftp._requests; - sftp._requests = {}; - const err = new Error('No response from server'); - for (let i = 0; i < keys.length; ++i) { - const req = reqs[keys[i]]; - if (typeof req.cb === 'function') - req.cb(err); - } -} - -function requestLimits(sftp, cb) { - /* - uint32 id - string "limits@openssh.com" - */ - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 18, p); - buf.utf8Write('limits@openssh.com', p += 4, 18); - - sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; - - const isBuffered = sendOrBuffer(sftp, buf); - if (sftp._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); - } -} - -const CLIENT_HANDLERS = { - [RESPONSE.VERSION]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); - - const extensions = {}; - - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed VERSION packet'); - - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); - } - } - - sftp._version = version; - sftp._extensions = extensions; - - if (extensions['limits@openssh.com'] === '1') { - return requestLimits(sftp, (err, limits) => { - if (!err) { - if (limits.maxPktLen > 0) - sftp._maxOutPktLen = limits.maxPktLen; - if (limits.maxReadLen > 0) - sftp._maxReadLen = limits.maxReadLen; - if (limits.maxWriteLen > 0) - sftp._maxWriteLen = limits.maxWriteLen; - sftp.maxOpenHandles = ( - limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity - ); - } - sftp.emit('ready'); - }); - } - - sftp.emit('ready'); - }, - [RESPONSE.STATUS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - uint32 error/status code - string error message (ISO-10646 UTF-8) - string language tag - */ - const errorCode = bufferParser.readUInt32BE(); - const errorMsg = bufferParser.readString(true); - const lang = bufferParser.skipString(); - bufferParser.clear(); - - if (lang === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed STATUS packet'); - } - - if (sftp._debug) { - const jsonMsg = JSON.stringify(errorMsg); - sftp._debug( - `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` - ); - } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') { - if (errorCode === STATUS_CODE.OK) { - req.cb(); - return; - } - const err = new Error(errorMsg - || STATUS_CODE_STR[errorCode] - || 'Unknown status'); - err.code = errorCode; - req.cb(err); - } - }, - [RESPONSE.HANDLE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); - } - - sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); - - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') - req.cb(undefined, handle); - }, - [RESPONSE.DATA]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - string data - */ - if (req && typeof req.cb === 'function') { - if (req.buffer) { - // We have already pre-allocated space to store the data - - const nb = bufferParser.readString(req.buffer); - bufferParser.clear(); - - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - req.cb(undefined, req.buffer, nb); - return; - } - } else { - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` - ); - req.cb(undefined, data); - return; - } - } - } else { - const nb = bufferParser.skipString(); - bufferParser.clear(); - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - return; - } - } - - return doFatalSFTPError(sftp, 'Malformed DATA packet'); - }, - [RESPONSE.NAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - uint32 count - repeats count times: - string filename - string longname - ATTRS attrs - */ - const count = bufferParser.readUInt32BE(); - if (count !== undefined) { - let names = []; - for (let i = 0; i < count; ++i) { - // We are going to assume UTF-8 for filenames despite the SFTPv3 - // spec not specifying an encoding because the specs for newer - // versions of the protocol all explicitly specify UTF-8 for - // filenames - const filename = bufferParser.readString(true); - - // `longname` only exists in SFTPv3 and since it typically will - // contain the filename, we assume it is also UTF-8 - const longname = bufferParser.readString(true); - - const attrs = readAttrs(sftp._biOpt); - if (attrs === undefined) { - names = undefined; - break; - } - names.push({ filename, longname, attrs }); - } - if (names !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` - ); - bufferParser.clear(); - if (req && typeof req.cb === 'function') - req.cb(undefined, names); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed NAME packet'); - }, - [RESPONSE.ATTRS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - ATTRS attrs - */ - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs !== undefined) { - sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); - if (req && typeof req.cb === 'function') - req.cb(undefined, attrs); - return; - } - - return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); - }, - [RESPONSE.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - if (reqID !== undefined) { - const req = sftp._requests[reqID]; - if (req) { - delete sftp._requests[reqID]; - switch (req.extended) { - case 'statvfs@openssh.com': - case 'fstatvfs@openssh.com': { - /* - uint64 f_bsize // file system block size - uint64 f_frsize // fundamental fs block size - uint64 f_blocks // number of blocks (unit f_frsize) - uint64 f_bfree // free blocks in file system - uint64 f_bavail // free blocks for non-root - uint64 f_files // total file inodes - uint64 f_ffree // free file inodes - uint64 f_favail // free file inodes for to non-root - uint64 f_fsid // file system id - uint64 f_flag // bit mask of f_flag values - uint64 f_namemax // maximum filename length - */ - const biOpt = sftp._biOpt; - const stats = { - f_bsize: bufferParser.readUInt64BE(biOpt), - f_frsize: bufferParser.readUInt64BE(biOpt), - f_blocks: bufferParser.readUInt64BE(biOpt), - f_bfree: bufferParser.readUInt64BE(biOpt), - f_bavail: bufferParser.readUInt64BE(biOpt), - f_files: bufferParser.readUInt64BE(biOpt), - f_ffree: bufferParser.readUInt64BE(biOpt), - f_favail: bufferParser.readUInt64BE(biOpt), - f_sid: bufferParser.readUInt64BE(biOpt), - f_flag: bufferParser.readUInt64BE(biOpt), - f_namemax: bufferParser.readUInt64BE(biOpt), - }; - if (stats.f_namemax === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, stats); - return; - } - case 'limits@openssh.com': { - /* - uint64 max-packet-length - uint64 max-read-length - uint64 max-write-length - uint64 max-open-handles - */ - const limits = { - maxPktLen: bufferParser.readUInt64BE(), - maxReadLen: bufferParser.readUInt64BE(), - maxWriteLen: bufferParser.readUInt64BE(), - maxOpenHandles: bufferParser.readUInt64BE(), - }; - if (limits.maxOpenHandles === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, limits); - return; - } - default: - // Unknown extended request - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(); - return; - } - } else { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); - }, -}; -const SERVER_HANDLERS = { - [REQUEST.INIT]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate INIT packet'); - - const extensions = {}; - - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed INIT packet'); - - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received INIT (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); - } - } - - sendOrBuffer(sftp, SERVER_VERSION_BUFFER); - - sftp._version = version; - sftp._extensions = extensions; - sftp.emit('ready'); - }, - [REQUEST.OPEN]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string filename - uint32 pflags - ATTRS attrs - */ - const filename = bufferParser.readString(true); - const pflags = bufferParser.readUInt32BE(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed OPEN packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); - - if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.CLOSE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); - - if (!sftp.emit('CLOSE', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READ]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - uint32 len - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const len = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (len === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READ packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); - - if (!sftp.emit('READ', reqID, handle, offset, len)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.WRITE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - string data - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed WRITE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); - - if (!sftp.emit('WRITE', reqID, handle, offset, data)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.LSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); - - if (!sftp.emit('LSTAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); - - if (!sftp.emit('FSTAT', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); - - if (!sftp.emit('SETSTAT', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - ATTRS attrs - */ - const handle = bufferParser.readString(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received FSETSTAT (id:${reqID})` - ); - - if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.OPENDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); - - if (!sftp.emit('OPENDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); - - if (!sftp.emit('READDIR', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REMOVE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); - - if (!sftp.emit('REMOVE', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.MKDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); - - if (!sftp.emit('MKDIR', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RMDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); - - if (!sftp.emit('RMDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REALPATH]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received REALPATH (id:${reqID})` - ); - - if (!sftp.emit('REALPATH', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.STAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed STAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); - - if (!sftp.emit('STAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RENAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string oldpath - string newpath - */ - const oldPath = bufferParser.readString(true); - const newPath = bufferParser.readString(true); - bufferParser.clear(); - - if (newPath === undefined) - return doFatalSFTPError(sftp, 'Malformed RENAME packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); - - if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed READLINK packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received READLINK (id:${reqID})` - ); - - if (!sftp.emit('READLINK', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SYMLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string linkpath - string targetpath - */ - const linkPath = bufferParser.readString(true); - const targetPath = bufferParser.readString(true); - bufferParser.clear(); - - if (targetPath === undefined) - return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); - - let handled; - if (sftp._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); - } else { - handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); - } - if (!handled) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string extended-request - ... any request-specific data ... - */ - const extName = bufferParser.readString(true); - if (extName === undefined) { - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); - } - - let extData; - if (bufferParser.avail()) - extData = bufferParser.readRaw(); - bufferParser.clear(); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED (id:${reqID})` - ); - - if (!sftp.emit('EXTENDED', reqID, extName, extData)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, -}; - -// ============================================================================= -// ReadStream/WriteStream-related ============================================== -// ============================================================================= -const { - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - validateNumber -} = require('./node-fs-compat'); - -const kMinPoolSpace = 128; - -let pool; -// It can happen that we expect to read a large chunk of data, and reserve -// a large chunk of the pool accordingly, but the read() call only filled -// a portion of it. If a concurrently executing read() then uses the same pool, -// the "reserved" portion cannot be used, so we allow it to be re-used as a -// new pool later. -const poolFragments = []; - -function allocNewPool(poolSize) { - if (poolFragments.length > 0) - pool = poolFragments.pop(); - else - pool = Buffer.allocUnsafe(poolSize); - pool.used = 0; -} - -// Check the `this.start` and `this.end` of stream. -function checkPosition(pos, name) { - if (!Number.isSafeInteger(pos)) { - validateNumber(pos, name); - if (!Number.isInteger(pos)) - throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); - } - if (pos < 0) - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); -} - -function roundUpToMultipleOf8(n) { - return (n + 7) & ~7; // Align to 8 byte boundary. -} - -function ReadStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // A little bit bigger buffer and water marks by default - if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - ReadableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'r' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.end = options.end; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesRead = 0; - this.closed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (this.end === undefined) { - this.end = Infinity; - } else if (this.end !== Infinity) { - checkPosition(this.end, 'end'); - - if (this.start !== undefined && this.start > this.end) { - throw new ERR_OUT_OF_RANGE( - 'start', - `<= "end" (here: ${this.end})`, - this.start - ); - } - } - - this.on('end', function() { - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(ReadStream, ReadableStream); - -ReadStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } - - this.handle = handle; - this.emit('open', handle); - this.emit('ready'); - // Start the flow of data. - this.read(); - }); -}; - -ReadStream.prototype._read = function(n) { - if (!Buffer.isBuffer(this.handle)) - return this.once('open', () => this._read(n)); - - // XXX: safe to remove this? - if (this.destroyed) - return; - - if (!pool || pool.length - pool.used < kMinPoolSpace) { - // Discard the old pool. - allocNewPool(this.readableHighWaterMark - || this._readableState.highWaterMark); - } - - // Grab another reference to the pool in the case that while we're - // in the thread pool another read() finishes up the pool, and - // allocates a new one. - const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); - const start = pool.used; - - if (this.end !== undefined) - toRead = Math.min(this.end - this.pos + 1, toRead); - - // Already read everything we were supposed to read! - // treat as EOF. - if (toRead <= 0) - return this.push(null); - - // the actual read. - this.sftp.read(this.handle, - pool, - pool.used, - toRead, - this.pos, - (er, bytesRead) => { - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } - let b = null; - - // Now that we know how much data we have actually read, re-wind the - // 'used' field if we can, and otherwise allow the remainder of our - // reservation to be used as a new pool later. - if (start + toRead === thisPool.used && thisPool === pool) { - thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); - } else { - // Round down to the next lowest multiple of 8 to ensure the new pool - // fragment start and end positions are aligned to an 8 byte boundary. - const alignedEnd = (start + toRead) & ~7; - const alignedStart = roundUpToMultipleOf8(start + bytesRead); - if (alignedEnd - alignedStart >= kMinPoolSpace) - poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); - } - - if (bytesRead > 0) { - this.bytesRead += bytesRead; - b = thisPool.slice(start, start + bytesRead); - } - - // Move the pool positions, and internal position for reading. - this.pos += bytesRead; - - this.push(b); - }); - - pool.used = roundUpToMultipleOf8(pool.used + toRead); -}; - -ReadStream.prototype._destroy = function(err, cb) { - if (this._opening && !Buffer.isBuffer(this.handle)) { - this.once('open', closeStream.bind(null, this, cb, err)); - return; - } - - closeStream(this, cb, err); - this.handle = null; - this._opening = false; -}; - -function closeStream(stream, cb, err) { - if (!stream.handle) - return onclose(); - - stream.sftp.close(stream.handle, onclose); - - function onclose(er) { - er = er || err; - cb(er); - stream.closed = true; - if (!er) - stream.emit('close'); - } -} - -ReadStream.prototype.close = function(cb) { - this.destroy(null, cb); -}; - -Object.defineProperty(ReadStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); - -// TODO: add `concurrency` setting to allow more than one in-flight WRITE -// request to server to improve throughput -function WriteStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - WritableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'w' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesWritten = 0; - this.closed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (options.encoding) - this.setDefaultEncoding(options.encoding); - - // Node v6.x only - this.on('finish', function() { - if (this._writableState.finalCalled) - return; - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(WriteStream, WritableStream); - -WriteStream.prototype._final = function(cb) { - if (this.autoClose) - this.destroy(); - cb(); -}; - -WriteStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } - - this.handle = handle; - - const tryAgain = (err) => { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() for - // whatever reason - this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); - return; - } - - // SFTPv3 requires absolute offsets, no matter the open flag used - if (this.flags[0] === 'a') { - const tryStat = (err, st) => { - if (err) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.sftp.stat(this.path, (err_, st_) => { - if (err_) { - this.destroy(); - this.emit('error', err); - return; - } - tryStat(null, st_); - }); - return; - } - - this.pos = st.size; - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fstat(handle, tryStat); - return; - } - - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fchmod(handle, this.mode, tryAgain); - }); -}; - -WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) { - const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); - return this.emit('error', err); - } - - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._write(data, encoding, cb); - }); - } - - this.sftp.write(this.handle, - data, - 0, - data.length, - this.pos, - (er, bytes) => { - if (er) { - if (this.autoClose) - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - cb(); - }); - - this.pos += data.length; -}; - -WriteStream.prototype._writev = function(data, cb) { - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._writev(data, cb); - }); - } - - const sftp = this.sftp; - const handle = this.handle; - let writesLeft = data.length; - - const onwrite = (er, bytes) => { - if (er) { - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - if (--writesLeft === 0) - cb(); - }; - - // TODO: try to combine chunks to reduce number of requests to the server? - for (let i = 0; i < data.length; ++i) { - const chunk = data[i].chunk; - - sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); - this.pos += chunk.length; - } -}; - -if (typeof WritableStream.prototype.destroy !== 'function') - WriteStream.prototype.destroy = ReadStream.prototype.destroy; - -WriteStream.prototype._destroy = ReadStream.prototype._destroy; -WriteStream.prototype.close = function(cb) { - if (cb) { - if (this.closed) { - process.nextTick(cb); - return; - } - this.on('close', cb); - } - - // If we are not autoClosing, we should call - // destroy on 'finish'. - if (!this.autoClose) - this.on('finish', this.destroy.bind(this)); - - this.end(); -}; - -// There is no shutdown() for files. -WriteStream.prototype.destroySoon = WriteStream.prototype.end; - -Object.defineProperty(WriteStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); -// ============================================================================= - -module.exports = { - flagsToString, - OPEN_MODE, - SFTP, - Stats, - STATUS_CODE, - stringToFlags, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/constants.js b/reverse_engineering/node_modules/ssh2/lib/protocol/constants.js deleted file mode 100644 index 632b7aa..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/constants.js +++ /dev/null @@ -1,344 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); - -let cpuInfo; -try { - cpuInfo = require('cpu-features')(); -} catch {} - -const { bindingAvailable } = require('./crypto.js'); - -const eddsaSupported = (() => { - if (typeof crypto.sign === 'function' - && typeof crypto.verify === 'function') { - const key = - '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' - + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; - const data = Buffer.from('a'); - let sig; - let verified; - try { - sig = crypto.sign(null, data, key); - verified = crypto.verify(null, data, key, sig); - } catch {} - return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); - } - - return false; -})(); - -const curve25519Supported = (typeof crypto.diffieHellman === 'function' - && typeof crypto.generateKeyPairSync === 'function' - && typeof crypto.createPublicKey === 'function'); - -const DEFAULT_KEX = [ - // https://tools.ietf.org/html/rfc5656#section-10.1 - 'ecdh-sha2-nistp256', - 'ecdh-sha2-nistp384', - 'ecdh-sha2-nistp521', - - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha256', - - // https://tools.ietf.org/html/rfc8268 - 'diffie-hellman-group14-sha256', - 'diffie-hellman-group15-sha512', - 'diffie-hellman-group16-sha512', - 'diffie-hellman-group17-sha512', - 'diffie-hellman-group18-sha512', -]; -if (curve25519Supported) { - DEFAULT_KEX.unshift('curve25519-sha256'); - DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); -} -const SUPPORTED_KEX = DEFAULT_KEX.concat([ - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha1', - - 'diffie-hellman-group14-sha1', // REQUIRED - 'diffie-hellman-group1-sha1', // REQUIRED -]); - - -const DEFAULT_SERVER_HOST_KEY = [ - 'ecdsa-sha2-nistp256', - 'ecdsa-sha2-nistp384', - 'ecdsa-sha2-nistp521', - 'rsa-sha2-512', // RFC 8332 - 'rsa-sha2-256', // RFC 8332 - 'ssh-rsa', -]; -if (eddsaSupported) - DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); -const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ - 'ssh-dss', -]); - - -const DEFAULT_CIPHER = [ - // http://tools.ietf.org/html/rfc5647 - 'aes128-gcm', - 'aes128-gcm@openssh.com', - 'aes256-gcm', - 'aes256-gcm@openssh.com', - - // http://tools.ietf.org/html/rfc4344#section-4 - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', -]; -if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { - // We know for sure the CPU does not support AES acceleration - if (bindingAvailable) - DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); - else - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { - // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers - // seem to outperform it on x86, but it seems to be faster than CTR ciphers - DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); -} else { - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} -const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ - 'aes256-cbc', - 'aes192-cbc', - 'aes128-cbc', - 'blowfish-cbc', - '3des-cbc', - - // http://tools.ietf.org/html/rfc4345#section-4: - 'arcfour256', - 'arcfour128', - - 'cast128-cbc', - 'arcfour', -]); - - -const DEFAULT_MAC = [ - 'hmac-sha2-256-etm@openssh.com', - 'hmac-sha2-512-etm@openssh.com', - 'hmac-sha1-etm@openssh.com', - 'hmac-sha2-256', - 'hmac-sha2-512', - 'hmac-sha1', -]; -const SUPPORTED_MAC = DEFAULT_MAC.concat([ - 'hmac-md5', - 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 - 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 - 'hmac-ripemd160', - 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 - 'hmac-md5-96', // first 96 bits of HMAC-MD5 -]); - -const DEFAULT_COMPRESSION = [ - 'none', - 'zlib@openssh.com', // ZLIB (LZ77) compression, except - // compression/decompression does not start until after - // successful user authentication - 'zlib', // ZLIB (LZ77) compression -]; -const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ -]); - - -const COMPAT = { - BAD_DHGEX: 1 << 0, - OLD_EXIT: 1 << 1, - DYN_RPORT_BUG: 1 << 2, - BUG_DHGEX_LARGE: 1 << 3, -}; - -module.exports = { - MESSAGE: { - // Transport layer protocol -- generic (1-19) - DISCONNECT: 1, - IGNORE: 2, - UNIMPLEMENTED: 3, - DEBUG: 4, - SERVICE_REQUEST: 5, - SERVICE_ACCEPT: 6, - - // Transport layer protocol -- algorithm negotiation (20-29) - KEXINIT: 20, - NEWKEYS: 21, - - // Transport layer protocol -- key exchange method-specific (30-49) - KEXDH_INIT: 30, - KEXDH_REPLY: 31, - - KEXDH_GEX_GROUP: 31, - KEXDH_GEX_INIT: 32, - KEXDH_GEX_REPLY: 33, - KEXDH_GEX_REQUEST: 34, - - KEXECDH_INIT: 30, - KEXECDH_REPLY: 31, - - // User auth protocol -- generic (50-59) - USERAUTH_REQUEST: 50, - USERAUTH_FAILURE: 51, - USERAUTH_SUCCESS: 52, - USERAUTH_BANNER: 53, - - // User auth protocol -- user auth method-specific (60-79) - USERAUTH_PASSWD_CHANGEREQ: 60, - - USERAUTH_PK_OK: 60, - - USERAUTH_INFO_REQUEST: 60, - USERAUTH_INFO_RESPONSE: 61, - - // Connection protocol -- generic (80-89) - GLOBAL_REQUEST: 80, - REQUEST_SUCCESS: 81, - REQUEST_FAILURE: 82, - - // Connection protocol -- channel-related (90-127) - CHANNEL_OPEN: 90, - CHANNEL_OPEN_CONFIRMATION: 91, - CHANNEL_OPEN_FAILURE: 92, - CHANNEL_WINDOW_ADJUST: 93, - CHANNEL_DATA: 94, - CHANNEL_EXTENDED_DATA: 95, - CHANNEL_EOF: 96, - CHANNEL_CLOSE: 97, - CHANNEL_REQUEST: 98, - CHANNEL_SUCCESS: 99, - CHANNEL_FAILURE: 100 - - // Reserved for client protocols (128-191) - - // Local extensions (192-155) - }, - DISCONNECT_REASON: { - HOST_NOT_ALLOWED_TO_CONNECT: 1, - PROTOCOL_ERROR: 2, - KEY_EXCHANGE_FAILED: 3, - RESERVED: 4, - MAC_ERROR: 5, - COMPRESSION_ERROR: 6, - SERVICE_NOT_AVAILABLE: 7, - PROTOCOL_VERSION_NOT_SUPPORTED: 8, - HOST_KEY_NOT_VERIFIABLE: 9, - CONNECTION_LOST: 10, - BY_APPLICATION: 11, - TOO_MANY_CONNECTIONS: 12, - AUTH_CANCELED_BY_USER: 13, - NO_MORE_AUTH_METHODS_AVAILABLE: 14, - ILLEGAL_USER_NAME: 15, - }, - DISCONNECT_REASON_STR: undefined, - CHANNEL_OPEN_FAILURE: { - ADMINISTRATIVELY_PROHIBITED: 1, - CONNECT_FAILED: 2, - UNKNOWN_CHANNEL_TYPE: 3, - RESOURCE_SHORTAGE: 4 - }, - TERMINAL_MODE: { - TTY_OP_END: 0, // Indicates end of options. - VINTR: 1, // Interrupt character; 255 if none. Similarly for the - // other characters. Not all of these characters are - // supported on all systems. - VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX - // systems). - VERASE: 3, // Erase the character to left of the cursor. - VKILL: 4, // Kill the current input line. - VEOF: 5, // End-of-file character (sends EOF from the - // terminal). - VEOL: 6, // End-of-line character in addition to carriage - // return and/or linefeed. - VEOL2: 7, // Additional end-of-line character. - VSTART: 8, // Continues paused output (normally control-Q). - VSTOP: 9, // Pauses output (normally control-S). - VSUSP: 10, // Suspends the current program. - VDSUSP: 11, // Another suspend character. - VREPRINT: 12, // Reprints the current input line. - VWERASE: 13, // Erases a word left of cursor. - VLNEXT: 14, // Enter the next character typed literally, even if - // it is a special character - VFLUSH: 15, // Character to flush output. - VSWTCH: 16, // Switch to a different shell layer. - VSTATUS: 17, // Prints system status line (load, command, pid, - // etc). - VDISCARD: 18, // Toggles the flushing of terminal output. - IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 - // if this flag is FALSE, and 1 if it is TRUE. - PARMRK: 31, // Mark parity and framing errors. - INPCK: 32, // Enable checking of parity errors. - ISTRIP: 33, // Strip 8th bit off characters. - INLCR: 34, // Map NL into CR on input. - IGNCR: 35, // Ignore CR on input. - ICRNL: 36, // Map CR to NL on input. - IUCLC: 37, // Translate uppercase characters to lowercase. - IXON: 38, // Enable output flow control. - IXANY: 39, // Any char will restart after stop. - IXOFF: 40, // Enable input flow control. - IMAXBEL: 41, // Ring bell on input queue full. - ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. - ICANON: 51, // Canonicalize input lines. - XCASE: 52, // Enable input and output of uppercase characters by - // preceding their lowercase equivalents with "\". - ECHO: 53, // Enable echoing. - ECHOE: 54, // Visually erase chars. - ECHOK: 55, // Kill character discards current line. - ECHONL: 56, // Echo NL even if ECHO is off. - NOFLSH: 57, // Don't flush after interrupt. - TOSTOP: 58, // Stop background jobs from output. - IEXTEN: 59, // Enable extensions. - ECHOCTL: 60, // Echo control characters as ^(Char). - ECHOKE: 61, // Visual erase for line kill. - PENDIN: 62, // Retype pending input. - OPOST: 70, // Enable output processing. - OLCUC: 71, // Convert lowercase to uppercase. - ONLCR: 72, // Map NL to CR-NL. - OCRNL: 73, // Translate carriage return to newline (output). - ONOCR: 74, // Translate newline to carriage return-newline - // (output). - ONLRET: 75, // Newline performs a carriage return (output). - CS7: 90, // 7 bit mode. - CS8: 91, // 8 bit mode. - PARENB: 92, // Parity enable. - PARODD: 93, // Odd parity, else even. - TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. - TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. - }, - CHANNEL_EXTENDED_DATATYPE: { - STDERR: 1, - }, - - SIGNALS: [ - 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', - 'USR2', 'KILL', 'PIPE' - ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), - - COMPAT, - COMPAT_CHECKS: [ - [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], - [ /^Cisco-1\./, COMPAT.BUG_DHGEX_LARGE ], - [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations - [ /^OpenSSH_5\.\d+/, COMPAT.DYN_RPORT_BUG ], - ], - - // KEX proposal-related - DEFAULT_KEX, - SUPPORTED_KEX, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY, - DEFAULT_CIPHER, - SUPPORTED_CIPHER, - DEFAULT_MAC, - SUPPORTED_MAC, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION, - - curve25519Supported, - eddsaSupported, -}; - -module.exports.DISCONNECT_REASON_BY_VALUE = - Array.from(Object.entries(module.exports.DISCONNECT_REASON)) - .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto.js b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto.js deleted file mode 100644 index b4c3ecb..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto.js +++ /dev/null @@ -1,1607 +0,0 @@ -// TODO: -// * make max packet size configurable -// * if decompression is enabled, use `._packet` in decipher instances as -// input to (sync) zlib inflater with appropriate offset and length to -// avoid an additional copy of payload data before inflation -// * factor decompression status into packet length checks -'use strict'; - -const { - createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual -} = require('crypto'); - -const { readUInt32BE, writeUInt32BE } = require('./utils.js'); - -const FastBuffer = Buffer[Symbol.species]; -const MAX_SEQNO = 2 ** 32 - 1; -const EMPTY_BUFFER = Buffer.alloc(0); -const BUF_INT = Buffer.alloc(4); -const DISCARD_CACHE = new Map(); -const MAX_PACKET_SIZE = 35000; - -let binding; -let AESGCMCipher; -let ChaChaPolyCipher; -let GenericCipher; -let AESGCMDecipher; -let ChaChaPolyDecipher; -let GenericDecipher; -try { - binding = require('./crypto/build/Release/sshcrypto.node'); - ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, - AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); -} catch {} - -const CIPHER_STREAM = 1 << 0; -const CIPHER_INFO = (() => { - function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { - return { - sslName, - blockLen, - keyLen, - ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) - ? ivLen - : blockLen), - authLen, - discardLen, - stream: !!(flags & CIPHER_STREAM), - }; - } - - return { - 'chacha20-poly1305@openssh.com': - info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), - - 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - 'aes128-gcm@openssh.com': - info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm@openssh.com': - info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - - 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), - 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), - 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), - 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), - 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), - 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), - - 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), - 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), - 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), - '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), - 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), - 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), - }; -})(); - -const MAC_INFO = (() => { - function info(sslName, len, actualLen, isETM) { - return { - sslName, - len, - actualLen, - isETM, - }; - } - - return { - 'hmac-md5': info('md5', 16, 16, false), - 'hmac-md5-96': info('md5', 16, 12, false), - 'hmac-ripemd160': info('ripemd160', 20, 20, false), - 'hmac-sha1': info('sha1', 20, 20, false), - 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), - 'hmac-sha1-96': info('sha1', 20, 12, false), - 'hmac-sha2-256': info('sha256', 32, 32, false), - 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), - 'hmac-sha2-256-96': info('sha256', 32, 12, false), - 'hmac-sha2-512': info('sha512', 64, 64, false), - 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), - 'hmac-sha2-512-96': info('sha512', 64, 12, false), - }; -})(); - - -// Should only_be used during the initial handshake -class NullCipher { - constructor(seqno, onWrite) { - this.outSeqno = seqno; - this._onWrite = onWrite; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -const POLY1305_ZEROS = Buffer.alloc(32); -const POLY1305_OUT_COMPUTE = Buffer.alloc(16); -let POLY1305_WASM_MODULE; -let POLY1305_RESULT_MALLOC; -let poly1305_auth; -class ChaChaPolyCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encKeyMain = enc.cipherKey.slice(0, 32); - this._encKeyPktLen = enc.cipherKey.slice(32); - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Encrypt packet length - const pktLenEnc = - createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) - .update(packet.slice(0, 4)); - this._onWrite(pktLenEnc); - - // Encrypt rest of packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const payloadEnc = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(packet.slice(4)); - this._onWrite(payloadEnc); - - // Calculate Poly1305 MAC - poly1305_auth(POLY1305_RESULT_MALLOC, - pktLenEnc, - pktLenEnc.length, - payloadEnc, - payloadEnc.length, - polyKey); - const mac = Buffer.allocUnsafe(16); - mac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - this._onWrite(mac); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class ChaChaPolyCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new ChaChaPolyCipher(enc.cipherKey); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class AESGCMCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encSSLName = enc.cipherInfo.sslName; - this._encKey = enc.cipherKey; - this._encIV = enc.cipherIV; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); - cipher.setAutoPadding(false); - - const lenData = packet.slice(0, 4); - cipher.setAAD(lenData); - this._onWrite(lenData); - - // Encrypt pad length, payload, and padding - const encrypted = cipher.update(packet.slice(4)); - this._onWrite(encrypted); - const final = cipher.final(); - // XXX: final.length === 0 always? - if (final.length) - this._onWrite(final); - - // Generate MAC - const tag = cipher.getAuthTag(); - this._onWrite(tag); - - // Increment counter in IV by 1 for next packet - ivIncrement(this._encIV); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class AESGCMCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new AESGCMCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class GenericCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._macSSLName = enc.macInfo.sslName; - this._macKey = enc.macKey; - this._macActualLen = enc.macInfo.actualLen; - this._macETM = enc.macInfo.isETM; - this._aadLen = (this._macETM ? 4 : 0); - this._dead = false; - - const discardLen = enc.cipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._cipherInstance.update(discard); - } - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - let mac; - if (this._macETM) { - // Encrypt pad length, payload, and padding - const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); - const encrypted = this._cipherInstance.update( - new Uint8Array(packet.buffer, - packet.byteOffset + 4, - packet.length - 4) - ); - - this._onWrite(lenBytes); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(lenBytes); - mac.update(encrypted); - } else { - // Encrypt length field, pad length, payload, and padding - const encrypted = this._cipherInstance.update(packet); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(packet); - } - - let digest = mac.digest(); - if (digest.length > this._macActualLen) - digest = digest.slice(0, this._macActualLen); - this._onWrite(digest); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class GenericCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._macLen = enc.macInfo.len; - this._macActualLen = enc.macInfo.actualLen; - this._aadLen = (enc.macInfo.isETM ? 4 : 0); - this._instance = new GenericCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV, - enc.macInfo.sslName, - enc.macKey, - enc.macInfo.isETM); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + this._macLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - if (this._macActualLen < this._macLen) { - packet = new FastBuffer(packet.buffer, - packet.byteOffset, - (packet.length - - (this._macLen - this._macActualLen))); - } - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class NullDecipher { - constructor(seqno, onPayload) { - this.inSeqno = seqno; - this._onPayload = onPayload; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - while (p < dataLen) { - // Read packet length - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - - if (this._lenBytes < 4) - return; - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (4 + this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._packetPos < this._len) { - const nb = Math.min(this._len - this._packetPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - if (nb === this._len) { - this._packet = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._packetPos - ); - } - } else if (nb === this._len) { - this._packet = data; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(data, this._packetPos); - } - p += nb; - this._packetPos += nb; - if (this._packetPos < this._len) - return; - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class ChaChaPolyDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decKeyMain = dec.decipherKey.slice(0, 32); - this._decKeyPktLen = dec.decipherKey.slice(32); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._calcMac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - - const decLenBytes = - createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) - .update(this._lenBuf); - this._len = readUInt32BE(decLenBytes, 0); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Calculate and compare Poly1305 MACs - poly1305_auth(POLY1305_RESULT_MALLOC, - this._lenBuf, - 4, - this._packet, - this._packet.length, - polyKey); - - this._calcMac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - if (!timingSafeEqual(this._calcMac, this._mac)) - throw new Error('Invalid MAC'); - - // Decrypt packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const packet = - createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(this._packet); - - const payload = new FastBuffer(packet.buffer, - packet.byteOffset + 1, - packet.length - packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class ChaChaPolyDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new ChaChaPolyDecipher(dec.decipherKey); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - this._instance.decrypt(this._packet, this._mac, this.inSeqno); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class AESGCMDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = null; - this._decipherSSLName = dec.decipherInfo.sslName; - this._decipherKey = dec.decipherKey; - this._decipherIV = dec.decipherIV; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error('Bad packet length'); - } - - this._decipherInstance = createDecipheriv( - this._decipherSSLName, - this._decipherKey, - this._decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._decipherInstance.setAAD(intToBytes(this._len)); - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let decrypted; - if (p !== 0 || nb !== dataLen) { - decrypted = this._decipherInstance.update( - new Uint8Array(data.buffer, data.byteOffset + p, nb) - ); - } else { - decrypted = this._decipherInstance.update(data); - } - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - - { - // Verify authentication tag - this._decipherInstance.setAuthTag(this._tag); - - const decrypted = this._decipherInstance.final(); - - // XXX: this should never output any data since stream ciphers always - // return data from .update() and block ciphers must end on a multiple - // of the block length, which would have caused an exception to be - // thrown if the total input was not... - if (decrypted.length) { - if (this._packet) - this._packet.set(decrypted, this._packetPos); - else - this._packet = decrypted; - } - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - ivIncrement(this._decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tagPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class AESGCMDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error(`Bad packet length: ${this._len}`); - } - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - - this._instance.decrypt(this._packet, this._len, this._tag); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tagPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -// TODO: test incremental .update()s vs. copying to _packet and doing a single -// .update() after entire packet read -- a single .update() would allow -// verifying MAC before decrypting for ETM MACs -class GenericDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._decipherInstance.setAutoPadding(false); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen - ); - this._blockSize = dec.decipherInfo.blockLen; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macSSLName = dec.macInfo.sslName; - this._macKey = dec.macKey; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - this._macInstance = null; - - const discardLen = dec.decipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._decipherInstance.update(discard); - } - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } - - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - - let decrypted; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - decrypted = this._decipherInstance.update(this._block); - this._len = readUInt32BE(decrypted, 0); - need = 4 + this._len - this._blockSize; - } - - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._blockSize - 1)) !== 0) { - throw new Error('Bad packet length'); - } - - // Create MAC up front to calculate in parallel with decryption - this._macInstance = createHmac(this._macSSLName, this._macKey); - - writeUInt32BE(BUF_INT, this.inSeqno, 0); - this._macInstance.update(BUF_INT); - if (this._macETM) { - this._macInstance.update(this._block); - } else { - this._macInstance.update(new Uint8Array(decrypted.buffer, - decrypted.byteOffset, - 4)); - this._pktLen = decrypted.length - 4; - this._packetPos = this._pktLen; - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(decrypted.buffer, - decrypted.byteOffset + 4, - this._packetPos), - 0 - ); - } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (this._macETM) - this._macInstance.update(encrypted); - const decrypted = this._decipherInstance.update(encrypted); - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - - // Verify MAC - if (!this._macETM) - this._macInstance.update(this._packet); - let calculated = this._macInstance.digest(); - if (this._macActualLen < calculated.length) { - calculated = new Uint8Array(calculated.buffer, - calculated.byteOffset, - this._macActualLen); - } - if (!timingSafeEquals(calculated, this._mac)) - throw new Error('Invalid MAC'); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class GenericDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new GenericDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV, - dec.macInfo.sslName, - dec.macKey, - dec.macInfo.isETM, - dec.macInfo.actualLen); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM || dec.decipherInfo.stream - ? 4 - : dec.decipherInfo.blockLen - ); - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } - - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - this._instance.decryptBlock(this._block); - this._len = readUInt32BE(this._block, 0); - need = 4 + this._len - this._block.length; - } - - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._block.length - 1)) !== 0) { - throw new Error('Bad packet length'); - } - - if (!this._macETM) { - this._pktLen = (this._block.length - 4); - if (this._pktLen) { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(this._block.buffer, - this._block.byteOffset + 4, - this._pktLen), - 0 - ); - } - } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - - // Decrypt and verify MAC - this._instance.decrypt(this._packet, - this.inSeqno, - this._block, - this._mac); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV -function ivIncrement(iv) { - // eslint-disable-next-line no-unused-expressions - ++iv[11] >>> 8 - && ++iv[10] >>> 8 - && ++iv[9] >>> 8 - && ++iv[8] >>> 8 - && ++iv[7] >>> 8 - && ++iv[6] >>> 8 - && ++iv[5] >>> 8 - && ++iv[4] >>> 8; -} - -const intToBytes = (() => { - const ret = Buffer.alloc(4); - return (n) => { - ret[0] = (n >>> 24); - ret[1] = (n >>> 16); - ret[2] = (n >>> 8); - ret[3] = n; - return ret; - }; -})(); - -function timingSafeEquals(a, b) { - if (a.length !== b.length) { - timingSafeEqual(a, a); - return false; - } - return timingSafeEqual(a, b); -} - -function createCipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.outbound !== 'object' || config.outbound === null) - throw new Error('Invalid outbound'); - - const outbound = config.outbound; - - if (typeof outbound.onWrite !== 'function') - throw new Error('Invalid outbound.onWrite'); - - if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) - throw new Error('Invalid outbound.cipherInfo'); - - if (!Buffer.isBuffer(outbound.cipherKey) - || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { - throw new Error('Invalid outbound.cipherKey'); - } - - if (outbound.cipherInfo.ivLen - && (!Buffer.isBuffer(outbound.cipherIV) - || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { - throw new Error('Invalid outbound.cipherIV'); - } - - if (typeof outbound.seqno !== 'number' - || outbound.seqno < 0 - || outbound.seqno > MAX_SEQNO) { - throw new Error('Invalid outbound.seqno'); - } - - const forceNative = !!outbound.forceNative; - - switch (outbound.cipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMCipher && !forceNative - ? new AESGCMCipherBinding(config) - : new AESGCMCipherNative(config)); - case 'chacha20': - return (ChaChaPolyCipher && !forceNative - ? new ChaChaPolyCipherBinding(config) - : new ChaChaPolyCipherNative(config)); - default: { - if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) - throw new Error('Invalid outbound.macInfo'); - if (!Buffer.isBuffer(outbound.macKey) - || outbound.macKey.length !== outbound.macInfo.len) { - throw new Error('Invalid outbound.macKey'); - } - return (GenericCipher && !forceNative - ? new GenericCipherBinding(config) - : new GenericCipherNative(config)); - } - } -} - -function createDecipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.inbound !== 'object' || config.inbound === null) - throw new Error('Invalid inbound'); - - const inbound = config.inbound; - - if (typeof inbound.onPayload !== 'function') - throw new Error('Invalid inbound.onPayload'); - - if (typeof inbound.decipherInfo !== 'object' - || inbound.decipherInfo === null) { - throw new Error('Invalid inbound.decipherInfo'); - } - - if (!Buffer.isBuffer(inbound.decipherKey) - || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { - throw new Error('Invalid inbound.decipherKey'); - } - - if (inbound.decipherInfo.ivLen - && (!Buffer.isBuffer(inbound.decipherIV) - || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { - throw new Error('Invalid inbound.decipherIV'); - } - - if (typeof inbound.seqno !== 'number' - || inbound.seqno < 0 - || inbound.seqno > MAX_SEQNO) { - throw new Error('Invalid inbound.seqno'); - } - - const forceNative = !!inbound.forceNative; - - switch (inbound.decipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMDecipher && !forceNative - ? new AESGCMDecipherBinding(config) - : new AESGCMDecipherNative(config)); - case 'chacha20': - return (ChaChaPolyDecipher && !forceNative - ? new ChaChaPolyDecipherBinding(config) - : new ChaChaPolyDecipherNative(config)); - default: { - if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) - throw new Error('Invalid inbound.macInfo'); - if (!Buffer.isBuffer(inbound.macKey) - || inbound.macKey.length !== inbound.macInfo.len) { - throw new Error('Invalid inbound.macKey'); - } - return (GenericDecipher && !forceNative - ? new GenericDecipherBinding(config) - : new GenericDecipherNative(config)); - } - } -} - -module.exports = { - CIPHER_INFO, - MAC_INFO, - bindingAvailable: !!binding, - init: (() => { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - try { - POLY1305_WASM_MODULE = await require('./crypto/poly1305.js')(); - POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); - poly1305_auth = POLY1305_WASM_MODULE.cwrap( - 'poly1305_auth', - null, - ['number', 'array', 'number', 'array', 'number', 'array'] - ); - } catch (ex) { - return reject(ex); - } - resolve(); - }); - })(), - - NullCipher, - createCipher, - NullDecipher, - createDecipher, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/binding.gyp b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/binding.gyp deleted file mode 100644 index 29c3282..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/binding.gyp +++ /dev/null @@ -1,14 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'sshcrypto', - 'include_dirs': [ - "> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) -o $@ $< $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) -o $@ $< $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@") - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) -o $@ $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,--start-group $(LD_INPUTS) $(LIBS) -Wl,--end-group - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,sshcrypto.target.mk)))),) - include sshcrypto.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /home/volodymyr/.nvm/versions/node/v14.10.0/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/volodymyr/.cache/node-gyp/14.10.0" "-Dnode_gyp_dir=/home/volodymyr/.nvm/versions/node/v14.10.0/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=/home/volodymyr/.cache/node-gyp/14.10.0/<(target_arch)/node.lib" "-Dmodule_root_dir=/home/volodymyr/projects/plugins/DocumentDB/reverse_engineering/node_modules/ssh2/lib/protocol/crypto" "-Dnode_engine=v8" "--depth=." "-Goutput_dir=." "--generator-output=build" -I/home/volodymyr/projects/plugins/DocumentDB/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi -I/home/volodymyr/.nvm/versions/node/v14.10.0/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/volodymyr/.cache/node-gyp/14.10.0/include/node/common.gypi "--toplevel-dir=." binding.gyp -Makefile: $(srcdir)/../../../../../../../../../.cache/node-gyp/14.10.0/include/node/common.gypi $(srcdir)/../../../../../../../../../.nvm/versions/node/v14.10.0/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/binding.gyp $(srcdir)/build/config.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto.node.d b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto.node.d deleted file mode 100644 index cd5809e..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/sshcrypto.node := g++ -o Release/obj.target/sshcrypto.node -shared -pthread -rdynamic -m64 -Wl,-soname=sshcrypto.node -Wl,--start-group Release/obj.target/sshcrypto/src/binding.o -Wl,--end-group diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d deleted file mode 100644 index e66424e..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d +++ /dev/null @@ -1,117 +0,0 @@ -cmd_Release/obj.target/sshcrypto/src/binding.o := g++ -o Release/obj.target/sshcrypto/src/binding.o ../src/binding.cc '-DNODE_GYP_MODULE_NAME=sshcrypto' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__STDC_FORMAT_MACROS' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/home/volodymyr/.cache/node-gyp/14.10.0/include/node -I/home/volodymyr/.cache/node-gyp/14.10.0/src -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/openssl/config -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/openssl/openssl/include -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/uv/include -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/zlib -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/v8/include -I../../../../../nan -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -O3 -fno-omit-frame-pointer -fno-rtti -fno-exceptions -std=gnu++1y -MMD -MF ./Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d.raw -c -Release/obj.target/sshcrypto/src/binding.o: ../src/binding.cc \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/node.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/cppgc/common.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8config.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8-internal.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8-version.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8config.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8-platform.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_version.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_buffer.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/node.h \ - ../../../../../nan/nan.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_version.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/errno.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/version.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/unix.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/threadpool.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/linux.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_object_wrap.h \ - ../../../../../nan/nan_callbacks.h \ - ../../../../../nan/nan_callbacks_12_inl.h \ - ../../../../../nan/nan_maybe_43_inl.h \ - ../../../../../nan/nan_converters.h \ - ../../../../../nan/nan_converters_43_inl.h ../../../../../nan/nan_new.h \ - ../../../../../nan/nan_implementation_12_inl.h \ - ../../../../../nan/nan_persistent_12_inl.h ../../../../../nan/nan_weak.h \ - ../../../../../nan/nan_object_wrap.h ../../../../../nan/nan_private.h \ - ../../../../../nan/nan_typedarray_contents.h \ - ../../../../../nan/nan_json.h ../../../../../nan/nan_scriptorigin.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/err.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/e_os2.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/opensslconf.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/./opensslconf_asm.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/././archs/linux-x86_64/asm/include/openssl/opensslconf.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/opensslv.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/ossl_typ.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bio.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/crypto.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/safestack.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/stack.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/cryptoerr.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/symhacks.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bioerr.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/lhash.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/evp.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/evperr.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/objects.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/obj_mac.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/asn1.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/asn1err.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bn.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bnerr.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/objectserr.h \ - /home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/hmac.h -../src/binding.cc: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/node.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/cppgc/common.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8config.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8-internal.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8-version.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8config.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/v8-platform.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_version.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_buffer.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/node.h: -../../../../../nan/nan.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_version.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/errno.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/version.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/unix.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/threadpool.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/uv/linux.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/node_object_wrap.h: -../../../../../nan/nan_callbacks.h: -../../../../../nan/nan_callbacks_12_inl.h: -../../../../../nan/nan_maybe_43_inl.h: -../../../../../nan/nan_converters.h: -../../../../../nan/nan_converters_43_inl.h: -../../../../../nan/nan_new.h: -../../../../../nan/nan_implementation_12_inl.h: -../../../../../nan/nan_persistent_12_inl.h: -../../../../../nan/nan_weak.h: -../../../../../nan/nan_object_wrap.h: -../../../../../nan/nan_private.h: -../../../../../nan/nan_typedarray_contents.h: -../../../../../nan/nan_json.h: -../../../../../nan/nan_scriptorigin.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/err.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/e_os2.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/opensslconf.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/./opensslconf_asm.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/././archs/linux-x86_64/asm/include/openssl/opensslconf.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/opensslv.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/ossl_typ.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bio.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/crypto.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/safestack.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/stack.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/cryptoerr.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/symhacks.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bioerr.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/lhash.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/evp.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/evperr.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/objects.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/obj_mac.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/asn1.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/asn1err.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bn.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/bnerr.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/objectserr.h: -/home/volodymyr/.cache/node-gyp/14.10.0/include/node/openssl/hmac.h: diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/sshcrypto.node.d b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/sshcrypto.node.d deleted file mode 100644 index 236a0f9..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/sshcrypto.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/sshcrypto.node := ln -f "Release/obj.target/sshcrypto.node" "Release/sshcrypto.node" 2>/dev/null || (rm -rf "Release/sshcrypto.node" && cp -af "Release/obj.target/sshcrypto.node" "Release/sshcrypto.node") diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto.node b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto.node deleted file mode 100755 index 8045aac..0000000 Binary files a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto.node and /dev/null differ diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto/src/binding.o b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto/src/binding.o deleted file mode 100644 index 012df0e..0000000 Binary files a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto/src/binding.o and /dev/null differ diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node deleted file mode 100755 index 8045aac..0000000 Binary files a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node and /dev/null differ diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/binding.Makefile b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/binding.Makefile deleted file mode 100644 index 64db433..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) sshcrypto diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi deleted file mode 100644 index 9f1375c..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi +++ /dev/null @@ -1,91 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "asan": 0, - "build_v8_with_gn": "false", - "coverage": "false", - "dcheck_always_on": 0, - "debug_nghttp2": "false", - "debug_node": "false", - "enable_lto": "false", - "enable_pgo_generate": "false", - "enable_pgo_use": "false", - "error_on_warn": "false", - "force_dynamic_crt": 0, - "gas_version": "2.30", - "host_arch": "x64", - "icu_data_in": "../../deps/icu-tmp/icudt67l.dat", - "icu_endianness": "l", - "icu_gyp_path": "tools/icu/icu-generic.gyp", - "icu_path": "deps/icu-small", - "icu_small": "false", - "icu_ver_major": "67", - "is_debug": 0, - "llvm_version": "0.0", - "napi_build_version": "6", - "node_byteorder": "little", - "node_debug_lib": "false", - "node_enable_d8": "false", - "node_install_npm": "true", - "node_module_version": 83, - "node_no_browser_globals": "false", - "node_prefix": "/", - "node_release_urlbase": "https://nodejs.org/download/release/", - "node_shared": "false", - "node_shared_brotli": "false", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_nghttp2": "false", - "node_shared_openssl": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_target_type": "executable", - "node_use_bundled_v8": "true", - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_node_code_cache": "true", - "node_use_node_snapshot": "true", - "node_use_openssl": "true", - "node_use_v8_platform": "true", - "node_with_ltcg": "false", - "node_without_node_options": "false", - "openssl_fips": "", - "openssl_is_fips": "false", - "ossfuzz": "false", - "shlib_suffix": "so.83", - "target_arch": "x64", - "v8_enable_31bit_smis_on_64bit_arch": 0, - "v8_enable_gdbjit": 0, - "v8_enable_i18n_support": 1, - "v8_enable_inspector": 1, - "v8_enable_lite_mode": 0, - "v8_enable_object_print": 1, - "v8_enable_pointer_compression": 0, - "v8_no_strict_aliasing": 1, - "v8_optimized_debug": 1, - "v8_promise_internal_field_count": 1, - "v8_random_seed": 0, - "v8_trace_maps": 0, - "v8_use_siphash": 1, - "want_separate_host_toolset": 0, - "nodedir": "/home/volodymyr/.cache/node-gyp/14.10.0", - "standalone_static_library": 1, - "target": "v14.10.0", - "user_agent": "npm/7.20.6 node/v14.10.0 linux x64 workspaces/false", - "userconfig": "/home/volodymyr/.npmrc", - "metrics_registry": "https://registry.npmjs.org/", - "prefix": "/home/volodymyr/.nvm/versions/node/v14.10.0", - "cache": "/home/volodymyr/.npm", - "node_gyp": "/home/volodymyr/.nvm/versions/node/v14.10.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js", - "globalconfig": "/home/volodymyr/.nvm/versions/node/v14.10.0/etc/npmrc", - "init_module": "/home/volodymyr/.npm-init.js" - } -} diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/sshcrypto.target.mk b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/sshcrypto.target.mk deleted file mode 100644 index 9c4269b..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/sshcrypto.target.mk +++ /dev/null @@ -1,161 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := sshcrypto -DEFS_Debug := \ - '-DNODE_GYP_MODULE_NAME=sshcrypto' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__STDC_FORMAT_MACROS' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' \ - '-DV8_ENABLE_CHECKS' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O3 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti \ - -fno-exceptions \ - -std=gnu++1y - -INCS_Debug := \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/include/node \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/src \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/openssl/config \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/openssl/openssl/include \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/uv/include \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/zlib \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/v8/include \ - -I$(srcdir)/../../../../nan - -DEFS_Release := \ - '-DNODE_GYP_MODULE_NAME=sshcrypto' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__STDC_FORMAT_MACROS' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O3 \ - -O3 \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti \ - -fno-exceptions \ - -std=gnu++1y - -INCS_Release := \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/include/node \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/src \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/openssl/config \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/openssl/openssl/include \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/uv/include \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/zlib \ - -I/home/volodymyr/.cache/node-gyp/14.10.0/deps/v8/include \ - -I$(srcdir)/../../../../nan - -OBJS := \ - $(obj).target/$(TARGET)/src/binding.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m64 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m64 - -LIBS := - -$(obj).target/sshcrypto.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/sshcrypto.node: LIBS := $(LIBS) -$(obj).target/sshcrypto.node: TOOLSET := $(TOOLSET) -$(obj).target/sshcrypto.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/sshcrypto.node -# Add target alias -.PHONY: sshcrypto -sshcrypto: $(builddir)/sshcrypto.node - -# Copy this to the executable output path. -$(builddir)/sshcrypto.node: TOOLSET := $(TOOLSET) -$(builddir)/sshcrypto.node: $(obj).target/sshcrypto.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/sshcrypto.node -# Short alias for building this executable. -.PHONY: sshcrypto.node -sshcrypto.node: $(obj).target/sshcrypto.node $(builddir)/sshcrypto.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/sshcrypto.node - diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/poly1305.js b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/poly1305.js deleted file mode 100644 index a6953fe..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/poly1305.js +++ /dev/null @@ -1,43 +0,0 @@ - -var createPoly1305 = (function() { - var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; - if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; - return ( -function(createPoly1305) { - createPoly1305 = createPoly1305 || {}; - - -var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; -if(z)B=y?require("path").dirname(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=require("fs"));G||(G=require("path"));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=require("fs"));G||(G=require("path"));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= -0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; -function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; -function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0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AggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} -function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} -function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; -(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, -a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); -b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; -b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; -function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 -#include -#include - -#include -#include -#include - -#include -#include -#include - -using namespace node; -using namespace v8; -using namespace std; - -struct MarkPopErrorOnReturn { - MarkPopErrorOnReturn() { ERR_set_mark(); } - ~MarkPopErrorOnReturn() { ERR_pop_to_mark(); } -}; - -enum ErrorType { - kErrNone, - kErrOpenSSL, - kErrBadIVLen, - kErrBadKeyLen, - kErrAADFailure, - kErrTagFailure, - kErrPartialEncrypt, - kErrBadCipherName, - kErrBadHMACName, - kErrBadHMACLen, - kErrBadInit, - kErrPartialDecrypt, - kErrInvalidMAC, - kErrBadBlockLen -}; - -#define MAX_MAC_LEN 64 - -#define POLY1305_KEYLEN 32 -#define POLY1305_TAGLEN 16 -class ChaChaPolyCipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("ChaChaPolyCipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "encrypt", Encrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("ChaChaPolyCipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit ChaChaPolyCipher() - : ctx_main_(nullptr), - ctx_pktlen_(nullptr), - md_ctx_(nullptr), - polykey_(nullptr) {} - - ~ChaChaPolyCipher() { - clear(); - } - - void clear() { - if (ctx_pktlen_) { - EVP_CIPHER_CTX_cleanup(ctx_pktlen_); - EVP_CIPHER_CTX_free(ctx_pktlen_); - ctx_pktlen_ = nullptr; - } - if (ctx_main_) { - EVP_CIPHER_CTX_cleanup(ctx_main_); - EVP_CIPHER_CTX_free(ctx_main_); - ctx_main_ = nullptr; - } - if (polykey_) { - EVP_PKEY_free(polykey_); - polykey_ = nullptr; - } - if (md_ctx_) { - EVP_MD_CTX_free(md_ctx_); - md_ctx_ = nullptr; - } - // `polykey_ctx_` is not explicitly freed as it is freed implicitly when - // `md_ctx_` is freed - } - - ErrorType init(unsigned char* keys, size_t keys_len) { - ErrorType r = kErrNone; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname("chacha20"); - - if (keys_len != 64) { - r = kErrBadKeyLen; - goto out; - } - - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_pktlen_ = EVP_CIPHER_CTX_new()) == nullptr - || (ctx_main_ = EVP_CIPHER_CTX_new()) == nullptr - || (md_ctx_ = EVP_MD_CTX_new()) == nullptr - || EVP_EncryptInit_ex(ctx_pktlen_, - cipher, - nullptr, - keys + 32, - nullptr) != 1 - || EVP_EncryptInit_ex(ctx_main_, - cipher, - nullptr, - keys, - nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_CIPHER_CTX_iv_length(ctx_pktlen_) != 16) { - r = kErrBadIVLen; - goto out; - } - -out: - return r; - } - - ErrorType encrypt(unsigned char* packet, - uint32_t packet_len, - uint32_t seqno) { - ErrorType r = kErrNone; - size_t sig_len = 16; - int outlen = 0; - - // `packet` layout: - // - uint32_t data_len = packet_len - POLY1305_TAGLEN; - - unsigned char polykey[POLY1305_KEYLEN] = {0}; - - uint8_t seqbuf[16] = {0}; - ((uint8_t*)(seqbuf))[12] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[13] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[14] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[15] = seqno & 0xff; - - // Generate Poly1305 key - if (EVP_EncryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_main_, - polykey, - &outlen, - polykey, - sizeof(polykey)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(polykey)) { - r = kErrPartialEncrypt; - goto out; - } - - // Encrypt packet length - if (EVP_EncryptInit_ex(ctx_pktlen_, - nullptr, - nullptr, - nullptr, - seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_pktlen_, packet, &outlen, packet, 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != 4) { - r = kErrPartialEncrypt; - goto out; - } - - // Encrypt rest of packet - seqbuf[0] = 1; - if (EVP_EncryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_main_, - packet + 4, - &outlen, - packet + 4, - data_len - 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len - 4) { - r = kErrPartialEncrypt; - goto out; - } - - // Poly1305 over ciphertext - if (polykey_) { - if (EVP_PKEY_CTX_ctrl(polykey_ctx_, - -1, - EVP_PKEY_OP_SIGNCTX, - EVP_PKEY_CTRL_SET_MAC_KEY, - sizeof(polykey), - (void*)polykey) <= 0) { - r = kErrOpenSSL; - goto out; - } - } else { - polykey_ = EVP_PKEY_new_raw_private_key(EVP_PKEY_POLY1305, - nullptr, - polykey, - sizeof(polykey)); - if (polykey_ == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_DigestSignInit(md_ctx_, - &polykey_ctx_, - nullptr, - nullptr, - polykey_)) { - r = kErrOpenSSL; - goto out; - } - } - - // Generate and write Poly1305 tag - if (EVP_DigestSign(md_ctx_, - packet + data_len, - &sig_len, - packet, - data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - - out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid keys"); - - ChaChaPolyCipher* obj = new ChaChaPolyCipher(); - ErrorType r = obj->init( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Encrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - ChaChaPolyCipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - ErrorType r = obj->encrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust() - ); - switch (r) { - case kErrNone: - return; - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown encrypt failure"); - } - } - - static NAN_METHOD(Free) { - ChaChaPolyCipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_main_; - EVP_CIPHER_CTX* ctx_pktlen_; - EVP_MD_CTX* md_ctx_; - EVP_PKEY* polykey_; - EVP_PKEY_CTX* polykey_ctx_; -}; - -class AESGCMCipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("AESGCMCipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "encrypt", Encrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("AESGCMCipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit AESGCMCipher() : ctx_(nullptr) {} - - ~AESGCMCipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len) { - ErrorType r = kErrNone; - - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (cipher != EVP_aes_128_gcm() && cipher != EVP_aes_256_gcm()) { - r = kErrBadCipherName; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_EncryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_SET_IVLEN, iv_len, nullptr)) { - r = kErrOpenSSL; - goto out; - } - - //~ if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - //~ r = kErrBadIVLen; - //~ goto out; - //~ } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_EncryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_SET_IV_FIXED, -1, iv)) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - -out: - return r; - } - - ErrorType encrypt(unsigned char* packet, uint32_t packet_len) { - ErrorType r = kErrNone; - - // `packet` layout: - // - uint32_t data_len = packet_len - 16; - - int outlen = 0; - - // Increment IV - unsigned char lastiv[1]; - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_IV_GEN, 1, lastiv)) { - r = kErrOpenSSL; - goto out; - } - - // Set AAD (the packet length) - if (!EVP_EncryptUpdate(ctx_, nullptr, &outlen, packet, 4)) { - r = kErrOpenSSL; - goto out; - } - if (outlen != 4) { - r = kErrAADFailure; - goto out; - } - - // Encrypt everything but the packet length - if (EVP_EncryptUpdate(ctx_, - packet + 4, - &outlen, - packet + 4, - data_len - 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len - 4) { - r = kErrPartialEncrypt; - goto out; - } - - // Generate authentication tag - if (!EVP_EncryptFinal_ex(ctx_, nullptr, &outlen)) { - r = kErrOpenSSL; - goto out; - } - - // Write authentication tag - if (EVP_CIPHER_CTX_ctrl(ctx_, - EVP_CTRL_AEAD_GET_TAG, - 16, - packet + data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid OpenSSL cipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid iv"); - - const Nan::Utf8String cipher_name(info[0]); - - AESGCMCipher* obj = new AESGCMCipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid AES GCM cipher name"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Encrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - AESGCMCipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - ErrorType r = obj->encrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - switch (r) { - case kErrNone: - return; - case kErrAADFailure: - return Nan::ThrowError("Error setting AAD"); - case kErrPartialEncrypt: - return Nan::ThrowError("Failed to completely encrypt packet"); - case kErrTagFailure: - return Nan::ThrowError("Error generating authentication tag"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown encrypt failure"); - } - } - - static NAN_METHOD(Free) { - AESGCMCipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; -}; - -class GenericCipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("GenericCipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "encrypt", Encrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("GenericCipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit GenericCipher() - : ctx_(nullptr), - ctx_hmac_(nullptr), - hmac_len_(0), - is_etm_(0) {} - - ~GenericCipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - if (ctx_hmac_) { - HMAC_CTX_free(ctx_hmac_); - ctx_hmac_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len, - const char* hmac_name, - unsigned char* hmac_key, - size_t hmac_key_len, - int is_etm) { - ErrorType r = kErrNone; - - const EVP_MD* md; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_EncryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - r = kErrBadIVLen; - goto out; - } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_EncryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - - if (cipher == EVP_rc4()) { - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - unsigned char zeros[1536] = {0}; - int outlen = sizeof(zeros); - if (EVP_EncryptUpdate(ctx_, - zeros, - &outlen, - zeros, - sizeof(zeros)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(zeros)) { - r = kErrBadInit; - goto out; - } - } - - md = EVP_get_digestbyname(hmac_name); - if (md == nullptr) { - r = kErrBadHMACName; - goto out; - } - - if ((ctx_hmac_ = HMAC_CTX_new()) == nullptr - || HMAC_Init_ex(ctx_hmac_, hmac_key, hmac_key_len, md, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - hmac_len_ = HMAC_size(ctx_hmac_); - is_etm_ = is_etm; - -out: - return r; - } - - ErrorType encrypt(unsigned char* packet, - uint32_t packet_len, - uint32_t seqno) { - ErrorType r = kErrNone; - - // `packet` layout: - // - uint32_t data_len = packet_len - hmac_len_; - - int outlen; - - uint8_t seqbuf[4] = {0}; - ((uint8_t*)(seqbuf))[0] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[1] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[2] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[3] = seqno & 0xff; - - if (is_etm_) { - // Encrypt everything but packet length - if (EVP_EncryptUpdate(ctx_, - packet + 4, - &outlen, - packet + 4, - data_len - 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len - 4) { - r = kErrPartialEncrypt; - goto out; - } - - // HMAC over unencrypted packet length and ciphertext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, packet, data_len) != 1 - || HMAC_Final(ctx_hmac_, packet + data_len, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - if (outlen != hmac_len_) { - r = kErrBadHMACLen; - goto out; - } - } - } else { - // HMAC over plaintext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, packet, data_len) != 1 - || HMAC_Final(ctx_hmac_, packet + data_len, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - if (outlen != hmac_len_) { - r = kErrBadHMACLen; - goto out; - } - } - - // Encrypt packet - if (EVP_EncryptUpdate(ctx_, - packet, - &outlen, - packet, - data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len) { - - r = kErrPartialEncrypt; - goto out; - } - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid cipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid cipher key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid cipher IV"); - - if (!info[3]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid HMAC name"); - - if (!Buffer::HasInstance(info[4])) - return Nan::ThrowTypeError("Missing/Invalid HMAC key"); - - if (!info[5]->IsBoolean()) - return Nan::ThrowTypeError("Missing/Invalid HMAC ETM flag"); - - const Nan::Utf8String cipher_name(info[0]); - const Nan::Utf8String mac_name(info[3]); - int is_etm = (Nan::To(info[5]).FromJust() ? 1 : 0); - - GenericCipher* obj = new GenericCipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]), - *mac_name, - reinterpret_cast(Buffer::Data(info[4])), - Buffer::Length(info[4]), - is_etm - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid cipher name"); - case kErrBadHMACName: - return Nan::ThrowError("Invalid MAC name"); - case kErrBadInit: - return Nan::ThrowError("Failed to properly initialize cipher"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Encrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - GenericCipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - ErrorType r = obj->encrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust() - ); - switch (r) { - case kErrNone: - return; - case kErrPartialEncrypt: - return Nan::ThrowError("Failed to completely encrypt packet"); - case kErrBadHMACLen: - return Nan::ThrowError("Unexpected HMAC length"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown encrypt failure"); - } - } - - static NAN_METHOD(Free) { - GenericCipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; - HMAC_CTX* ctx_hmac_; - unsigned int hmac_len_; - int is_etm_; -}; - -// ============================================================================= - -class ChaChaPolyDecipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("ChaChaPolyDecipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "decrypt", Decrypt); - SetPrototypeMethod(tpl, "decryptLen", DecryptLen); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("ChaChaPolyDecipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit ChaChaPolyDecipher() - : ctx_main_(nullptr), - ctx_pktlen_(nullptr), - md_ctx_(nullptr), - polykey_(nullptr) {} - - ~ChaChaPolyDecipher() { - clear(); - } - - void clear() { - if (ctx_pktlen_) { - EVP_CIPHER_CTX_cleanup(ctx_pktlen_); - EVP_CIPHER_CTX_free(ctx_pktlen_); - ctx_pktlen_ = nullptr; - } - if (ctx_main_) { - EVP_CIPHER_CTX_cleanup(ctx_main_); - EVP_CIPHER_CTX_free(ctx_main_); - ctx_main_ = nullptr; - } - if (polykey_) { - EVP_PKEY_free(polykey_); - polykey_ = nullptr; - } - if (md_ctx_) { - EVP_MD_CTX_free(md_ctx_); - md_ctx_ = nullptr; - } - // `polykey_ctx_` is not explicitly freed as it is freed implicitly when - // `md_ctx_` is freed - } - - ErrorType init(unsigned char* keys, size_t keys_len) { - ErrorType r = kErrNone; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname("chacha20"); - - if (keys_len != 64) { - r = kErrBadKeyLen; - goto out; - } - - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_pktlen_ = EVP_CIPHER_CTX_new()) == nullptr - || (ctx_main_ = EVP_CIPHER_CTX_new()) == nullptr - || (md_ctx_ = EVP_MD_CTX_new()) == nullptr - || EVP_DecryptInit_ex(ctx_pktlen_, - cipher, - nullptr, - keys + 32, - nullptr) != 1 - || EVP_DecryptInit_ex(ctx_main_, - cipher, - nullptr, - keys, - nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_CIPHER_CTX_iv_length(ctx_pktlen_) != 16) { - r = kErrBadIVLen; - goto out; - } - -out: - return r; - } - - ErrorType decrypt_length(unsigned char* data, - size_t data_len, - uint32_t seqno, - uint32_t* packet_length) { - ErrorType r = kErrNone; - int outlen; - - unsigned char dec_length_bytes[4]; - - uint8_t seqbuf[16] = {0}; - ((uint8_t*)(seqbuf))[12] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[13] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[14] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[15] = seqno & 0xff; - - if (EVP_DecryptInit_ex(ctx_pktlen_, - nullptr, - nullptr, - nullptr, - seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_DecryptUpdate(ctx_pktlen_, - dec_length_bytes, - &outlen, - data, - data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != 4) { - r = kErrPartialDecrypt; - goto out; - } - - *packet_length = (uint32_t)dec_length_bytes[0] << 24 - | (uint32_t)dec_length_bytes[1] << 16 - | (uint32_t)dec_length_bytes[2] << 8 - | (uint32_t)dec_length_bytes[3]; - memcpy(length_bytes, data, data_len); -out: - return r; - } - - ErrorType decrypt(unsigned char* packet, - uint32_t packet_len, - unsigned char* mac, - uint32_t seqno) { - ErrorType r = kErrNone; - size_t sig_len = 16; - int outlen = 0; - - // `packet` layout: - // - - unsigned char polykey[POLY1305_KEYLEN] = {0}; - unsigned char calc_mac[POLY1305_TAGLEN] = {0}; - - uint8_t seqbuf[16] = {0}; - ((uint8_t*)(seqbuf))[12] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[13] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[14] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[15] = seqno & 0xff; - - // Generate Poly1305 key - if (EVP_EncryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_main_, - polykey, - &outlen, - polykey, - sizeof(polykey)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(polykey)) { - r = kErrPartialEncrypt; - goto out; - } - - // Poly1305 over ciphertext - if (polykey_) { - if (EVP_PKEY_CTX_ctrl(polykey_ctx_, - -1, - EVP_PKEY_OP_SIGNCTX, - EVP_PKEY_CTRL_SET_MAC_KEY, - sizeof(polykey), - (void*)polykey) <= 0) { - r = kErrOpenSSL; - goto out; - } - } else { - polykey_ = EVP_PKEY_new_raw_private_key(EVP_PKEY_POLY1305, - nullptr, - polykey, - sizeof(polykey)); - if (polykey_ == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_DigestSignInit(md_ctx_, - &polykey_ctx_, - nullptr, - nullptr, - polykey_)) { - r = kErrOpenSSL; - goto out; - } - } - if (EVP_DigestSignUpdate(md_ctx_, - length_bytes, - sizeof(length_bytes)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_DigestSignUpdate(md_ctx_, packet, packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Generate Poly1305 MAC - if (EVP_DigestSignFinal(md_ctx_, calc_mac, &sig_len) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Compare MACs - if (CRYPTO_memcmp(mac, calc_mac, sizeof(calc_mac))) { - r = kErrInvalidMAC; - goto out; - } - - // Decrypt packet - seqbuf[0] = 1; - if (EVP_DecryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_DecryptUpdate(ctx_main_, - packet, - &outlen, - packet, - packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len) { - r = kErrPartialDecrypt; - goto out; - } - - out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid keys"); - - ChaChaPolyDecipher* obj = new ChaChaPolyDecipher(); - ErrorType r = obj->init( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(DecryptLen) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - ChaChaPolyDecipher* obj = - ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0]) || Buffer::Length(info[0]) != 4) - return Nan::ThrowTypeError("Missing/Invalid length bytes"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - unsigned char* length_bytes = - reinterpret_cast(Buffer::Data(info[0])); - - uint32_t dec_packet_length; - ErrorType r = obj->decrypt_length( - length_bytes, - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust(), - &dec_packet_length - ); - - switch (r) { - case kErrNone: - return info.GetReturnValue().Set(dec_packet_length); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet length"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Decrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - ChaChaPolyDecipher* obj = - ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!Buffer::HasInstance(info[1]) - || Buffer::Length(info[1]) != POLY1305_TAGLEN) { - return Nan::ThrowTypeError("Missing/Invalid mac"); - } - - if (!info[2]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - ErrorType r = obj->decrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - reinterpret_cast(Buffer::Data(info[1])), - Nan::To(info[2]).FromJust() - ); - - switch (r) { - case kErrNone: - return; - case kErrInvalidMAC: - return Nan::ThrowError("Invalid MAC"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet length"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Free) { - ChaChaPolyDecipher* obj = - ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - unsigned char length_bytes[4]; - EVP_CIPHER_CTX* ctx_main_; - EVP_CIPHER_CTX* ctx_pktlen_; - EVP_MD_CTX* md_ctx_; - EVP_PKEY* polykey_; - EVP_PKEY_CTX* polykey_ctx_; -}; - -class AESGCMDecipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("AESGCMDecipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "decrypt", Decrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("AESGCMDecipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit AESGCMDecipher() : ctx_(nullptr) {} - - ~AESGCMDecipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len) { - ErrorType r = kErrNone; - - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (cipher != EVP_aes_128_gcm() && cipher != EVP_aes_256_gcm()) { - r = kErrBadCipherName; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_DecryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_SET_IVLEN, iv_len, nullptr)) { - r = kErrOpenSSL; - goto out; - } - - //~ if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - //~ r = kErrBadIVLen; - //~ goto out; - //~ } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_DecryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_SET_IV_FIXED, -1, iv)) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - -out: - return r; - } - - ErrorType decrypt(unsigned char* packet, - uint32_t packet_len, - unsigned char* length_bytes, - unsigned char* tag) { - ErrorType r = kErrNone; - - // `packet` layout: - // - - int outlen; - - // Increment IV - unsigned char lastiv[1]; - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_IV_GEN, 1, lastiv)) { - r = kErrOpenSSL; - goto out; - } - - // Set AAD (the packet length) - if (!EVP_DecryptUpdate(ctx_, nullptr, &outlen, length_bytes, 4)) { - r = kErrOpenSSL; - goto out; - } - if (outlen != 4) { - r = kErrAADFailure; - goto out; - } - - // Decrypt everything but the packet length - if (EVP_DecryptUpdate(ctx_, packet, &outlen, packet, packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len) { - r = kErrPartialDecrypt; - goto out; - } - - // Set authentication tag - if (EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_SET_TAG, 16, tag) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Verify authentication tag - if (!EVP_DecryptFinal_ex(ctx_, nullptr, &outlen)) { - r = kErrOpenSSL; - goto out; - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid OpenSSL cipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid iv"); - - const Nan::Utf8String cipher_name(info[0]); - - AESGCMDecipher* obj = new AESGCMDecipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid AES GCM cipher name"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Decrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - AESGCMDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid length"); - - if (!Buffer::HasInstance(info[2]) || Buffer::Length(info[2]) != 16) - return Nan::ThrowTypeError("Missing/Invalid tag"); - - uint32_t length = Nan::To(info[1]).FromJust(); - unsigned char length_bytes[4]; - length_bytes[0] = (length >> 24) & 0xFF; - length_bytes[1] = (length >> 16) & 0xFF; - length_bytes[2] = (length >> 8) & 0xFF; - length_bytes[3] = length & 0xFF; - - ErrorType r = obj->decrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - length_bytes, - reinterpret_cast(Buffer::Data(info[2])) - ); - switch (r) { - case kErrNone: - return; - case kErrAADFailure: - return Nan::ThrowError("Error setting AAD"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet"); - case kErrTagFailure: - return Nan::ThrowError("Error generating authentication tag"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Free) { - AESGCMDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; -}; - -class GenericDecipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("GenericDecipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "decryptBlock", DecryptBlock); - SetPrototypeMethod(tpl, "decrypt", Decrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("GenericDecipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit GenericDecipher() - : ctx_(nullptr), - ctx_hmac_(nullptr), - hmac_len_(0), - is_etm_(0) {} - - ~GenericDecipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - if (ctx_hmac_) { - HMAC_CTX_free(ctx_hmac_); - ctx_hmac_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len, - const char* hmac_name, - unsigned char* hmac_key, - size_t hmac_key_len, - int is_etm, - size_t hmac_actual_len) { - ErrorType r = kErrNone; - - const EVP_MD* md; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_DecryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - r = kErrBadIVLen; - goto out; - } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_DecryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - - if (cipher == EVP_rc4()) { - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - unsigned char zeros[1536] = {0}; - int outlen = sizeof(zeros); - if (EVP_DecryptUpdate(ctx_, - zeros, - &outlen, - zeros, - sizeof(zeros)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(zeros)) { - r = kErrBadInit; - goto out; - } - } - - md = EVP_get_digestbyname(hmac_name); - if (md == nullptr) { - r = kErrBadHMACName; - goto out; - } - - if ((ctx_hmac_ = HMAC_CTX_new()) == nullptr - || HMAC_Init_ex(ctx_hmac_, hmac_key, hmac_key_len, md, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - hmac_len_ = HMAC_size(ctx_hmac_); - hmac_actual_len_ = hmac_actual_len; - is_etm_ = is_etm; - switch (EVP_CIPHER_CTX_mode(ctx_)) { - case EVP_CIPH_STREAM_CIPHER: - case EVP_CIPH_CTR_MODE: - is_stream_ = 1; - break; - default: - is_stream_ = 0; - } - block_size_ = EVP_CIPHER_CTX_block_size(ctx_); - -out: - return r; - } - - ErrorType decrypt_block(unsigned char* data, uint32_t data_len) { - ErrorType r = kErrNone; - - int outlen; - - if (!is_stream_ && data_len != block_size_) { - r = kErrBadBlockLen; - goto out; - } - - // Decrypt block - if (EVP_DecryptUpdate(ctx_, data, &outlen, data, data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len) { - r = kErrPartialDecrypt; - goto out; - } - -out: - return r; - } - - ErrorType decrypt(unsigned char* packet, - uint32_t packet_len, - uint32_t seqno, - unsigned char* first_block, - uint32_t first_block_len, - unsigned char* mac, - uint32_t mac_len) { - ErrorType r = kErrNone; - - int outlen; - unsigned char calc_mac[MAX_MAC_LEN] = {0}; - - uint8_t seqbuf[4] = {0}; - ((uint8_t*)(seqbuf))[0] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[1] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[2] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[3] = seqno & 0xff; - - if (is_etm_) { - // `first_block` for ETM should just be the unencrypted packet length - if (first_block_len != 4) { - r = kErrBadBlockLen; - goto out; - } - - // HMAC over unencrypted packet length and ciphertext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, first_block, 4) != 1 - || HMAC_Update(ctx_hmac_, packet, packet_len) != 1 - || HMAC_Final(ctx_hmac_, calc_mac, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (outlen != hmac_len_ || mac_len != hmac_len_) { - r = kErrBadHMACLen; - goto out; - } - - // Compare MACs - if (CRYPTO_memcmp(mac, calc_mac, hmac_len_)) { - r = kErrInvalidMAC; - goto out; - } - } - - // Decrypt packet - if (EVP_DecryptUpdate(ctx_, packet, &outlen, packet, packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len) { - r = kErrPartialDecrypt; - goto out; - } - } else { - // `first_block` for non-ETM should be a completely decrypted first block - if (!is_stream_ && first_block_len != block_size_) { - r = kErrBadBlockLen; - goto out; - } - - const int offset = (is_stream_ ? 0 : block_size_ - 4); - // Decrypt the rest of the packet - if (EVP_DecryptUpdate(ctx_, - packet + offset, - &outlen, - packet + offset, - packet_len - offset) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len - offset) { - r = kErrPartialDecrypt; - goto out; - } - - // HMAC over plaintext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, first_block, 4) != 1 - || HMAC_Update(ctx_hmac_, packet, packet_len) != 1 - || HMAC_Final(ctx_hmac_, calc_mac, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (outlen != hmac_len_ || mac_len != hmac_actual_len_) { - r = kErrBadHMACLen; - goto out; - } - - // Compare MACs - if (CRYPTO_memcmp(mac, calc_mac, hmac_actual_len_)) { - r = kErrInvalidMAC; - goto out; - } - } - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid decipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid decipher key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid decipher IV"); - - if (!info[3]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid HMAC name"); - - if (!Buffer::HasInstance(info[4])) - return Nan::ThrowTypeError("Missing/Invalid HMAC key"); - - if (!info[5]->IsBoolean()) - return Nan::ThrowTypeError("Missing/Invalid HMAC ETM flag"); - - if (!info[6]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid HMAC ETM flag"); - - const Nan::Utf8String cipher_name(info[0]); - const Nan::Utf8String mac_name(info[3]); - int is_etm = (Nan::To(info[5]).FromJust() ? 1 : 0); - - GenericDecipher* obj = new GenericDecipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]), - *mac_name, - reinterpret_cast(Buffer::Data(info[4])), - Buffer::Length(info[4]), - is_etm, - Nan::To(info[6]).FromJust() - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid decipher key length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid decipher IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid decipher name"); - case kErrBadHMACName: - return Nan::ThrowError("Invalid MAC name"); - case kErrBadInit: - return Nan::ThrowError("Failed to properly initialize decipher"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(DecryptBlock) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - GenericDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid block"); - - ErrorType r = obj->decrypt_block( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - switch (r) { - case kErrNone: - return; - case kErrBadBlockLen: - return Nan::ThrowError("Invalid block length"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Decrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - GenericDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid first block"); - - if (!Buffer::HasInstance(info[3])) - return Nan::ThrowTypeError("Missing/Invalid MAC"); - - ErrorType r = obj->decrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust(), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]), - reinterpret_cast(Buffer::Data(info[3])), - Buffer::Length(info[3]) - ); - switch (r) { - case kErrNone: - return; - case kErrBadBlockLen: - return Nan::ThrowError("Invalid block length"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet"); - case kErrBadHMACLen: - return Nan::ThrowError("Unexpected HMAC length"); - case kErrInvalidMAC: - return Nan::ThrowError("Invalid MAC"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Free) { - GenericDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; - HMAC_CTX* ctx_hmac_; - unsigned int hmac_len_; - unsigned int hmac_actual_len_; - uint8_t is_etm_; - uint8_t is_stream_; - uint32_t block_size_; -}; - - -NAN_MODULE_INIT(init) { - ChaChaPolyCipher::Init(target); - AESGCMCipher::Init(target); - GenericCipher::Init(target); - - ChaChaPolyDecipher::Init(target); - AESGCMDecipher::Init(target); - GenericDecipher::Init(target); -} - -NODE_MODULE(sshcrypto, init) diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.js b/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.js deleted file mode 100644 index 35fb9f2..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const MESSAGE_HANDLERS = new Array(256); -[ - require('./kex.js').HANDLERS, - require('./handlers.misc.js'), -].forEach((handlers) => { - // eslint-disable-next-line prefer-const - for (let [type, handler] of Object.entries(handlers)) { - type = +type; - if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) - MESSAGE_HANDLERS[type] = handler; - } -}); - -module.exports = MESSAGE_HANDLERS; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.misc.js b/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.misc.js deleted file mode 100644 index 647564b..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.misc.js +++ /dev/null @@ -1,1214 +0,0 @@ -'use strict'; - -const { - bufferSlice, - bufferParser, - doFatalError, - sigSSHToASN1, - writeUInt32BE, -} = require('./utils.js'); - -const { - CHANNEL_OPEN_FAILURE, - COMPAT, - MESSAGE, - TERMINAL_MODE, -} = require('./constants.js'); - -const { - parseKey, -} = require('./keyParser.js'); - -const TERMINAL_MODE_BY_VALUE = - Array.from(Object.entries(TERMINAL_MODE)) - .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); - -module.exports = { - // Transport layer protocol ================================================== - [MESSAGE.DISCONNECT]: (self, payload) => { - /* - byte SSH_MSG_DISCONNECT - uint32 reason code - string description in ISO-10646 UTF-8 encoding - string language tag - */ - bufferParser.init(payload, 1); - const reason = bufferParser.readUInt32BE(); - const desc = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DISCONNECT packet' - ); - } - - self._debug && self._debug( - `Inbound: Received DISCONNECT (${reason}, "${desc}")` - ); - - const handler = self._handlers.DISCONNECT; - handler && handler(self, reason, desc); - }, - [MESSAGE.IGNORE]: (self, payload) => { - /* - byte SSH_MSG_IGNORE - string data - */ - self._debug && self._debug('Inbound: Received IGNORE'); - }, - [MESSAGE.UNIMPLEMENTED]: (self, payload) => { - /* - byte SSH_MSG_UNIMPLEMENTED - uint32 packet sequence number of rejected message - */ - bufferParser.init(payload, 1); - const seqno = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (seqno === undefined) { - return doFatalError( - self, - 'Inbound: Malformed UNIMPLEMENTED packet' - ); - } - - self._debug - && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); - }, - [MESSAGE.DEBUG]: (self, payload) => { - /* - byte SSH_MSG_DEBUG - boolean always_display - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const display = bufferParser.readBool(); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DEBUG packet' - ); - } - - self._debug && self._debug('Inbound: Received DEBUG'); - - const handler = self._handlers.DEBUG; - handler && handler(self, display, msg); - }, - [MESSAGE.SERVICE_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_SERVICE_REQUEST - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_REQUEST packet' - ); - } - - self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); - - const handler = self._handlers.SERVICE_REQUEST; - handler && handler(self, name); - }, - [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { - // S->C - /* - byte SSH_MSG_SERVICE_ACCEPT - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_ACCEPT packet' - ); - } - - self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); - - const handler = self._handlers.SERVICE_ACCEPT; - handler && handler(self, name); - }, - - // User auth protocol -- generic ============================================= - [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_USERAUTH_REQUEST - string user name in ISO-10646 UTF-8 encoding [RFC3629] - string service name in US-ASCII - string method name in US-ASCII - .... method specific fields - */ - bufferParser.init(payload, 1); - const user = bufferParser.readString(true); - const service = bufferParser.readString(true); - const method = bufferParser.readString(true); - let methodData; - let methodDesc; - switch (method) { - case 'none': - methodData = null; - break; - case 'password': { - /* - boolean - string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] - [string new password] - */ - const isChange = bufferParser.readBool(); - if (isChange !== undefined) { - methodData = bufferParser.readString(true); - if (methodData !== undefined && isChange) { - const newPassword = bufferParser.readString(true); - if (newPassword !== undefined) - methodData = { oldPassword: methodData, newPassword }; - else - methodData = undefined; - } - } - break; - } - case 'publickey': { - /* - boolean - string public key algorithm name - string public key blob - [string signature] - */ - const hasSig = bufferParser.readBool(); - if (hasSig !== undefined) { - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - if (hasSig) { - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, keyAlgo); - if (signature) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - }; - } - } - } else { - methodData = { keyAlgo, key }; - methodDesc = 'publickey -- check'; - } - } - break; - } - case 'hostbased': { - /* - string public key algorithm for host key - string public host key and certificates for client host - string client host name expressed as the FQDN in US-ASCII - string user name on the client host in ISO-10646 UTF-8 encoding - [RFC3629] - string signature - */ - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - const localHostname = bufferParser.readString(true); - const localUsername = bufferParser.readString(true); - - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, keyAlgo); - if (signature !== undefined) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - localHostname, - localUsername, - }; - } - } - break; - } - case 'keyboard-interactive': - /* - string language tag (as defined in [RFC-3066]) - string submethods (ISO-10646 UTF-8) - */ - // Skip/ignore language field -- it's deprecated in RFC 4256 - bufferParser.skipString(); - - methodData = bufferParser.readList(); - break; - default: - if (method !== undefined) - methodData = bufferParser.readRaw(); - } - bufferParser.clear(); - - if (methodData === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_REQUEST packet' - ); - } - - if (methodDesc === undefined) - methodDesc = method; - - self._authsQueue.push(method); - - self._debug - && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); - - const handler = self._handlers.USERAUTH_REQUEST; - handler && handler(self, user, service, method, methodData); - }, - [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_FAILURE - name-list authentications that can continue - boolean partial success - */ - bufferParser.init(payload, 1); - const authMethods = bufferParser.readList(); - const partialSuccess = bufferParser.readBool(); - bufferParser.clear(); - - if (partialSuccess === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_FAILURE packet' - ); - } - - self._debug - && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_FAILURE; - handler && handler(self, authMethods, partialSuccess); - }, - [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_SUCCESS - */ - self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_SUCCESS; - handler && handler(self); - }, - [MESSAGE.USERAUTH_BANNER]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_BANNER - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_BANNER packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); - - const handler = self._handlers.USERAUTH_BANNER; - handler && handler(self, msg); - }, - - // User auth protocol -- method-specific ===================================== - 60: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 60 without auth'); - return; - } - - switch (self._authsQueue[0]) { - case 'password': { - // S->C - /* - byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ - string prompt in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const prompt = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' - ); - } - - self._debug - && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); - - const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; - handler && handler(self, prompt); - break; - } - case 'publickey': { - // S->C - /* - byte SSH_MSG_USERAUTH_PK_OK - string public key algorithm name from the request - string public key blob from the request - */ - bufferParser.init(payload, 1); - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - bufferParser.clear(); - - if (key === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PK_OK packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_PK_OK; - handler && handler(self, keyAlgo, key); - break; - } - case 'keyboard-interactive': { - // S->C - /* - byte SSH_MSG_USERAUTH_INFO_REQUEST - string name (ISO-10646 UTF-8) - string instruction (ISO-10646 UTF-8) - string language tag (as defined in [RFC-3066]) - int num-prompts - string prompt[1] (ISO-10646 UTF-8) - boolean echo[1] - ... - string prompt[num-prompts] (ISO-10646 UTF-8) - boolean echo[num-prompts] - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const instructions = bufferParser.readString(true); - bufferParser.readString(); // skip lang - const numPrompts = bufferParser.readUInt32BE(); - let prompts; - if (numPrompts !== undefined) { - prompts = new Array(numPrompts); - let i; - for (i = 0; i < numPrompts; ++i) { - const prompt = bufferParser.readString(true); - const echo = bufferParser.readBool(); - if (echo === undefined) - break; - prompts[i] = { prompt, echo }; - } - if (i !== numPrompts) - prompts = undefined; - } - bufferParser.clear(); - - if (prompts === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); - - const handler = self._handlers.USERAUTH_INFO_REQUEST; - handler && handler(self, name, instructions, prompts); - break; - } - default: - self._debug - && self._debug('Inbound: Received unexpected payload type 60'); - } - }, - 61: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 61 without auth'); - return; - } - /* - byte SSH_MSG_USERAUTH_INFO_RESPONSE - int num-responses - string response[1] (ISO-10646 UTF-8) - ... - string response[num-responses] (ISO-10646 UTF-8) - */ - if (self._authsQueue[0] !== 'keyboard-interactive') { - return doFatalError( - self, - 'Inbound: Received unexpected payload type 61' - ); - } - bufferParser.init(payload, 1); - const numResponses = bufferParser.readUInt32BE(); - let responses; - if (numResponses !== undefined) { - responses = new Array(numResponses); - let i; - for (i = 0; i < numResponses; ++i) { - const response = bufferParser.readString(true); - if (response === undefined) - break; - responses[i] = response; - } - if (i !== numResponses) - responses = undefined; - } - bufferParser.clear(); - - if (responses === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); - - const handler = self._handlers.USERAUTH_INFO_RESPONSE; - handler && handler(self, responses); - }, - - // Connection protocol -- generic ============================================ - [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_GLOBAL_REQUEST - string request name in US-ASCII only - boolean want reply - .... request-specific data follows - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (name) { - case 'tcpip-forward': - case 'cancel-tcpip-forward': { - /* - string address to bind (e.g., "0.0.0.0") - uint32 port number to bind - */ - const bindAddr = bufferParser.readString(true); - const bindPort = bufferParser.readUInt32BE(); - if (bindPort !== undefined) - data = { bindAddr, bindPort }; - break; - } - case 'streamlocal-forward@openssh.com': - case 'cancel-streamlocal-forward@openssh.com': { - /* - string socket path - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) - data = { socketPath }; - break; - } - case 'no-more-sessions@openssh.com': - data = null; - break; - case 'hostkeys-00@openssh.com': { - data = []; - while (bufferParser.avail() > 0) { - const keyRaw = bufferParser.readString(); - if (keyRaw === undefined) { - data = undefined; - break; - } - const key = parseKey(keyRaw); - if (!(key instanceof Error)) - data.push(key); - } - break; - } - default: - data = bufferParser.readRaw(); - } - } - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed GLOBAL_REQUEST packet' - ); - } - - self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); - - const handler = self._handlers.GLOBAL_REQUEST; - if (handler) - handler(self, name, wantReply, data); - else - self.requestFailure(); // Auto reject - }, - [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_SUCCESS - .... response specific data - */ - const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); - - self._debug && self._debug('Inbound: REQUEST_SUCCESS'); - - const handler = self._handlers.REQUEST_SUCCESS; - handler && handler(self, data); - }, - [MESSAGE.REQUEST_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_FAILURE - */ - self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); - - const handler = self._handlers.REQUEST_FAILURE; - handler && handler(self); - }, - - // Connection protocol -- channel-related ==================================== - [MESSAGE.CHANNEL_OPEN]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN - string channel type in US-ASCII only - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - bufferParser.init(payload, 1); - const type = bufferParser.readString(true); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - let channelInfo; - - switch (type) { - case 'forwarded-tcpip': // S->C - case 'direct-tcpip': { // C->S - /* - string address that was connected / host to connect - uint32 port that was connected / port to connect - string originator IP address - uint32 originator port - */ - const destIP = bufferParser.readString(true); - const destPort = bufferParser.readUInt32BE(); - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { destIP, destPort, srcIP, srcPort } - }; - } - break; - } - case 'forwarded-streamlocal@openssh.com': // S->C - case 'direct-streamlocal@openssh.com': { // C->S - /* - string socket path - string reserved for future use - - (direct-streamlocal@openssh.com additionally has:) - uint32 reserved - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { socketPath } - }; - } - break; - } - case 'x11': { // S->C - /* - string originator address (e.g., "192.168.7.38") - uint32 originator port - */ - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { srcIP, srcPort } - }; - } - break; - } - default: - // Includes: - // 'session' (C->S) - // 'auth-agent@openssh.com' (S->C) - channelInfo = { - type, - sender, - window, - packetSize, - data: {} - }; - } - bufferParser.clear(); - - if (channelInfo === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); - - const handler = self._handlers.CHANNEL_OPEN; - if (handler) { - handler(self, channelInfo); - } else { - self.channelOpenFail( - channelInfo.sender, - CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, - '', - '' - ); - } - }, - [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION - uint32 recipient channel - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - // "The 'recipient channel' is the channel number given in the - // original open request, and 'sender channel' is the channel number - // allocated by the other side." - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); - bufferParser.clear(); - - if (packetSize === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' - ); - } - - self._debug && self._debug( - `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` - ); - - const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; - if (handler) - handler(self, { recipient, sender, window, packetSize, data }); - }, - [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_FAILURE - uint32 recipient channel - uint32 reason code - string description in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const reason = bufferParser.readUInt32BE(); - const description = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' - ); - } - - self._debug - && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_OPEN_FAILURE; - handler && handler(self, recipient, reason, description); - }, - [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_WINDOW_ADJUST - uint32 recipient channel - uint32 bytes to add - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const bytesToAdd = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (bytesToAdd === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' - ); - } - - self._debug && self._debug( - `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` - ); - - const handler = self._handlers.CHANNEL_WINDOW_ADJUST; - handler && handler(self, recipient, bytesToAdd); - }, - [MESSAGE.CHANNEL_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_DATA - uint32 recipient channel - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_DATA packet' - ); - } - - self._debug - && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); - - const handler = self._handlers.CHANNEL_DATA; - handler && handler(self, recipient, data); - }, - [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EXTENDED_DATA - uint32 recipient channel - uint32 data_type_code - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' - ); - } - - self._debug && self._debug( - `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` - ); - - const handler = self._handlers.CHANNEL_EXTENDED_DATA; - handler && handler(self, recipient, data, type); - }, - [MESSAGE.CHANNEL_EOF]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EOF - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EOF packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); - - const handler = self._handlers.CHANNEL_EOF; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_CLOSE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_CLOSE packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_CLOSE; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_REQUEST - uint32 recipient channel - string request type in US-ASCII characters only - boolean want reply - .... type-specific data follows - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (type) { - case 'exit-status': // S->C - /* - uint32 exit_status - */ - data = bufferParser.readUInt32BE(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'exit-signal': { // S->C - /* - string signal name (without the "SIG" prefix) - boolean core dumped - string error message in ISO-10646 UTF-8 encoding - string language tag - */ - let signal; - let coreDumped; - if (self._compatFlags & COMPAT.OLD_EXIT) { - /* - Instead of `signal name` and `core dumped`, we have just: - uint32 signal number - */ - const num = bufferParser.readUInt32BE(); - switch (num) { - case 1: - signal = 'HUP'; - break; - case 2: - signal = 'INT'; - break; - case 3: - signal = 'QUIT'; - break; - case 6: - signal = 'ABRT'; - break; - case 9: - signal = 'KILL'; - break; - case 14: - signal = 'ALRM'; - break; - case 15: - signal = 'TERM'; - break; - default: - if (num !== undefined) { - // Unknown or OS-specific - signal = `UNKNOWN (${num})`; - } - } - coreDumped = false; - } else { - signal = bufferParser.readString(true); - coreDumped = bufferParser.readBool(); - if (coreDumped === undefined) - signal = undefined; - } - const errorMessage = bufferParser.readString(true); - if (bufferParser.skipString() !== undefined) - data = { signal, coreDumped, errorMessage }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` - ); - break; - } - case 'pty-req': { // C->S - /* - string TERM environment variable value (e.g., vt100) - uint32 terminal width, characters (e.g., 80) - uint32 terminal height, rows (e.g., 24) - uint32 terminal width, pixels (e.g., 640) - uint32 terminal height, pixels (e.g., 480) - string encoded terminal modes - */ - const term = bufferParser.readString(true); - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - const modesBinary = bufferParser.readString(); - if (modesBinary !== undefined) { - bufferParser.init(modesBinary, 1); - let modes = {}; - while (bufferParser.avail()) { - const opcode = bufferParser.readByte(); - if (opcode === TERMINAL_MODE.TTY_OP_END) - break; - const name = TERMINAL_MODE_BY_VALUE[opcode]; - const value = bufferParser.readUInt32BE(); - if (opcode === undefined - || name === undefined - || value === undefined) { - modes = undefined; - break; - } - modes[name] = value; - } - if (modes !== undefined) - data = { term, cols, rows, width, height, modes }; - } - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'window-change': { // C->S - /* - uint32 terminal width, columns - uint32 terminal height, rows - uint32 terminal width, pixels - uint32 terminal height, pixels - */ - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - if (height !== undefined) - data = { cols, rows, width, height }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'x11-req': { // C->S - /* - boolean single connection - string x11 authentication protocol - string x11 authentication cookie - uint32 x11 screen number - */ - const single = bufferParser.readBool(); - const protocol = bufferParser.readString(true); - const cookie = bufferParser.readString(); - const screen = bufferParser.readUInt32BE(); - if (screen !== undefined) - data = { single, protocol, cookie, screen }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'env': { // C->S - /* - string variable name - string variable value - */ - const name = bufferParser.readString(true); - const value = bufferParser.readString(true); - if (value !== undefined) - data = { name, value }; - if (self._debug) { - self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` - + `${name}=${value})` - ); - } - break; - } - case 'shell': // C->S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - case 'exec': // C->S - /* - string command - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'subsystem': // C->S - /* - string subsystem name - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'signal': // C->S - /* - string signal name (without the "SIG" prefix) - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'xon-xoff': // C->S - /* - boolean client can do - */ - data = bufferParser.readBool(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'auth-agent-req@openssh.com': // C-S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - default: - data = (bufferParser.avail() ? bufferParser.readRaw() : null); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - } - } - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_REQUEST packet' - ); - } - - const handler = self._handlers.CHANNEL_REQUEST; - handler && handler(self, recipient, type, wantReply, data); - }, - [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_SUCCESS - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_SUCCESS packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); - - const handler = self._handlers.CHANNEL_SUCCESS; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_FAILURE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_FAILURE packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_FAILURE; - handler && handler(self, recipient); - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/kex.js b/reverse_engineering/node_modules/ssh2/lib/protocol/kex.js deleted file mode 100644 index 507c88a..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/kex.js +++ /dev/null @@ -1,1831 +0,0 @@ -'use strict'; - -const { - createDiffieHellman, - createDiffieHellmanGroup, - createECDH, - createHash, - createPublicKey, - diffieHellman, - generateKeyPairSync, - randomFillSync, -} = require('crypto'); - -const { Ber } = require('asn1'); - -const { - COMPAT, - curve25519Supported, - DEFAULT_KEX, - DEFAULT_SERVER_HOST_KEY, - DEFAULT_CIPHER, - DEFAULT_MAC, - DEFAULT_COMPRESSION, - DISCONNECT_REASON, - MESSAGE, -} = require('./constants.js'); -const { - CIPHER_INFO, - createCipher, - createDecipher, - MAC_INFO, -} = require('./crypto.js'); -const { parseDERKey } = require('./keyParser.js'); -const { - bufferFill, - bufferParser, - convertSignature, - doFatalError, - FastBuffer, - sigSSHToASN1, - writeUInt32BE, -} = require('./utils.js'); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = require('./zlib.js'); - -let MESSAGE_HANDLERS; - -const GEX_MIN_BITS = 2048; // RFC 8270 -const GEX_MAX_BITS = 8192; // RFC 8270 - -const EMPTY_BUFFER = Buffer.alloc(0); - -// Client/Server -function kexinit(self) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - - let payload; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - const entry = self._offer.lists.kex; - let kex = entry.array; - let found = false; - for (let i = 0; i < kex.length; ++i) { - if (kex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - kex = kex.slice(); - } - kex.splice(i--, 1); - } - } - if (found) { - let len = 1 + 16 + self._offer.totalSize + 1 + 4; - const newKexBuf = Buffer.from(kex.join(',')); - len -= (entry.buffer.length - newKexBuf.length); - - const all = self._offer.lists.all; - const rest = new Uint8Array( - all.buffer, - all.byteOffset + 4 + entry.buffer.length, - all.length - (4 + entry.buffer.length) - ); - - payload = Buffer.allocUnsafe(len); - writeUInt32BE(payload, newKexBuf.length, 0); - payload.set(newKexBuf, 4); - payload.set(rest, 4 + newKexBuf.length); - } - } - - if (payload === undefined) { - payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); - self._offer.copyAllTo(payload, 17); - } - - self._debug && self._debug('Outbound: Sending KEXINIT'); - - payload[0] = MESSAGE.KEXINIT; - randomFillSync(payload, 1, 16); - - // Zero-fill first_kex_packet_follows and reserved bytes - bufferFill(payload, 0, payload.length - 5); - - self._kexinit = payload; - - // Needed to correct the starting position in allocated "packets" when packets - // will be buffered due to active key exchange - self._packetRW.write.allocStart = 0; - - // TODO: only create single buffer and set _kexinit as slice of packet instead - { - const p = self._packetRW.write.allocStartKEX; - const packet = self._packetRW.write.alloc(payload.length, true); - packet.set(payload, p); - self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); - } -} - -function handleKexInit(self, payload) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - const init = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - }; - - bufferParser.init(payload, 17); - - if ((init.kex = bufferParser.readList()) === undefined - || (init.serverHostKey = bufferParser.readList()) === undefined - || (init.cs.cipher = bufferParser.readList()) === undefined - || (init.sc.cipher = bufferParser.readList()) === undefined - || (init.cs.mac = bufferParser.readList()) === undefined - || (init.sc.mac = bufferParser.readList()) === undefined - || (init.cs.compress = bufferParser.readList()) === undefined - || (init.sc.compress = bufferParser.readList()) === undefined - || (init.cs.lang = bufferParser.readList()) === undefined - || (init.sc.lang = bufferParser.readList()) === undefined) { - bufferParser.clear(); - return doFatalError( - self, - 'Received malformed KEXINIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const pos = bufferParser.pos(); - const firstFollows = (pos < payload.length && payload[pos] === 1); - bufferParser.clear(); - - const local = self._offer; - const remote = init; - - let localKex = local.lists.kex.array; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - let found = false; - for (let i = 0; i < localKex.length; ++i) { - if (localKex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - localKex = localKex.slice(); - } - localKex.splice(i--, 1); - } - } - } - - let clientList; - let serverList; - let i; - const debug = self._debug; - - debug && debug('Inbound: Handshake in progress'); - - // Key exchange method ======================================================= - debug && debug(`Handshake: (local) KEX method: ${localKex}`); - debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); - if (self._server) { - serverList = localKex; - clientList = remote.kex; - } else { - serverList = remote.kex; - clientList = localKex; - } - // Check for agreeable key exchange algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching key exchange algorithm'); - return doFatalError( - self, - 'Handshake failed: no matching key exchange algorithm', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.kex = clientList[i]; - debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); - if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { - // Ignore next inbound packet, it was a wrong first guess at KEX algorithm - self._skipNextInboundPacket = true; - } - - - // Server host key format ==================================================== - const localSrvHostKey = local.lists.serverHostKey.array; - debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug && debug( - `Handshake: (remote) Host key format: ${remote.serverHostKey}` - ); - if (self._server) { - serverList = localSrvHostKey; - clientList = remote.serverHostKey; - } else { - serverList = remote.serverHostKey; - clientList = localSrvHostKey; - } - // Check for agreeable server host key format - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching host key format'); - return doFatalError( - self, - 'Handshake failed: no matching host key format', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.serverHostKey = clientList[i]; - debug && debug(`Handshake: Host key format: ${clientList[i]}`); - - - // Client->Server cipher ===================================================== - const localCSCipher = local.lists.cs.cipher.array; - debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); - if (self._server) { - serverList = localCSCipher; - clientList = remote.cs.cipher; - } else { - serverList = remote.cs.cipher; - clientList = localCSCipher; - } - // Check for agreeable client->server cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S cipher'); - return doFatalError( - self, - 'Handshake failed: no matching C->S cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.cipher = clientList[i]; - debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); - - - // Server->Client cipher ===================================================== - const localSCCipher = local.lists.sc.cipher.array; - debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); - if (self._server) { - serverList = localSCCipher; - clientList = remote.sc.cipher; - } else { - serverList = remote.sc.cipher; - clientList = localSCCipher; - } - // Check for agreeable server->client cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C cipher'); - return doFatalError( - self, - 'Handshake failed: no matching S->C cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.cipher = clientList[i]; - debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); - - - // Client->Server MAC ======================================================== - const localCSMAC = local.lists.cs.mac.array; - debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); - if (CIPHER_INFO[init.cs.cipher].authLen > 0) { - init.cs.mac = ''; - debug && debug('Handshake: C->S MAC: '); - } else { - if (self._server) { - serverList = localCSMAC; - clientList = remote.cs.mac; - } else { - serverList = remote.cs.mac; - clientList = localCSMAC; - } - // Check for agreeable client->server hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S MAC'); - return doFatalError( - self, - 'Handshake failed: no matching C->S MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.mac = clientList[i]; - debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); - } - - - // Server->Client MAC ======================================================== - const localSCMAC = local.lists.sc.mac.array; - debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); - if (CIPHER_INFO[init.sc.cipher].authLen > 0) { - init.sc.mac = ''; - debug && debug('Handshake: S->C MAC: '); - } else { - if (self._server) { - serverList = localSCMAC; - clientList = remote.sc.mac; - } else { - serverList = remote.sc.mac; - clientList = localSCMAC; - } - // Check for agreeable server->client hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C MAC'); - return doFatalError( - self, - 'Handshake failed: no matching S->C MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.mac = clientList[i]; - debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); - } - - - // Client->Server compression ================================================ - const localCSCompress = local.lists.cs.compress.array; - debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); - if (self._server) { - serverList = localCSCompress; - clientList = remote.cs.compress; - } else { - serverList = remote.cs.compress; - clientList = localCSCompress; - } - // Check for agreeable client->server compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S compression'); - return doFatalError( - self, - 'Handshake failed: no matching C->S compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.compress = clientList[i]; - debug && debug(`Handshake: C->S compression: ${clientList[i]}`); - - - // Server->Client compression ================================================ - const localSCCompress = local.lists.sc.compress.array; - debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); - if (self._server) { - serverList = localSCCompress; - clientList = remote.sc.compress; - } else { - serverList = remote.sc.compress; - clientList = localSCCompress; - } - // Check for agreeable server->client compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C compression'); - return doFatalError( - self, - 'Handshake failed: no matching S->C compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.compress = clientList[i]; - debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - - init.cs.lang = ''; - init.sc.lang = ''; - - // XXX: hack -- find a better way to do this - if (self._kex) { - if (!self._kexinit) { - // We received a rekey request, but we haven't sent a KEXINIT in response - // yet - kexinit(self); - } - self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); - } - - self._kex = createKeyExchange(init, self, payload); - self._kex.start(); -} - -const createKeyExchange = (() => { - function convertToMpint(buf) { - let idx = 0; - let length = buf.length; - while (buf[idx] === 0x00) { - ++idx; - --length; - } - let newBuf; - if (buf[idx] & 0x80) { - newBuf = Buffer.allocUnsafe(1 + length); - newBuf[0] = 0; - buf.copy(newBuf, 1, idx); - buf = newBuf; - } else if (length !== buf.length) { - newBuf = Buffer.allocUnsafe(length); - buf.copy(newBuf, 0, idx); - buf = newBuf; - } - return buf; - } - - class KeyExchange { - constructor(negotiated, protocol, remoteKexinit) { - this._protocol = protocol; - - this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); - this.negotiated = negotiated; - this._step = 1; - this._public = null; - this._dh = null; - this._sentNEWKEYS = false; - this._receivedNEWKEYS = false; - this._finished = false; - this._hostVerified = false; - - // Data needed for initializing cipher/decipher/etc. - this._kexinit = protocol._kexinit; - this._remoteKexinit = remoteKexinit; - this._identRaw = protocol._identRaw; - this._remoteIdentRaw = protocol._remoteIdentRaw; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - } - finish() { - if (this._finished) - return false; - this._finished = true; - - const isServer = this._protocol._server; - const negotiated = this.negotiated; - - const pubKey = this.convertPublicKey(this._dhData); - let secret = this.computeSecret(this._dhData); - if (secret instanceof Error) { - secret.message = - `Error while computing DH secret (${this.type}): ${secret.message}`; - secret.level = 'handshake'; - return doFatalError( - this._protocol, - secret, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const hash = createHash(this.hashName); - // V_C - hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); - // "V_S" - hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); - // "I_C" - hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); - // "I_S" - hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); - // "K_S" - const serverPublicHostKey = (isServer - ? this._hostKey.getPublicSSH() - : this._hostKey); - hashString(hash, serverPublicHostKey); - - if (this.type === 'groupex') { - // Group exchange-specific - const params = this.getDHParams(); - const num = Buffer.allocUnsafe(4); - // min (uint32) - writeUInt32BE(num, this._minBits, 0); - hash.update(num); - // preferred (uint32) - writeUInt32BE(num, this._prefBits, 0); - hash.update(num); - // max (uint32) - writeUInt32BE(num, this._maxBits, 0); - hash.update(num); - // prime - hashString(hash, params.prime); - // generator - hashString(hash, params.generator); - } - - // method-specific data sent by client - hashString(hash, (isServer ? pubKey : this.getPublicKey())); - // method-specific data sent by server - const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); - hashString(hash, serverPublicKey); - // shared secret ("K") - hashString(hash, secret); - - // "H" - const exchangeHash = hash.digest(); - - if (!isServer) { - bufferParser.init(this._sig, 0); - const sigType = bufferParser.readString(true); - - if (!sigType) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (sigType !== negotiated.serverHostKey) { - return doFatalError( - this._protocol, - `Wrong signature type: ${sigType}, ` - + `expected: ${negotiated.serverHostKey}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // "s" - let sigValue = bufferParser.readString(); - - bufferParser.clear(); - - if (sigValue === undefined) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { - return doFatalError( - this._protocol, - 'Malformed signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - let parsedHostKey; - { - bufferParser.init(this._hostKey, 0); - const name = bufferParser.readString(true); - const hostKey = this._hostKey.slice(bufferParser.pos()); - bufferParser.clear(); - parsedHostKey = parseDERKey(hostKey, name); - if (parsedHostKey instanceof Error) { - parsedHostKey.level = 'handshake'; - return doFatalError( - this._protocol, - parsedHostKey, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug - && this._protocol._debug('Verifying signature ...'); - - const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); - if (verified !== true) { - if (verified instanceof Error) { - this._protocol._debug && this._protocol._debug( - `Signature verification failed: ${verified.stack}` - ); - } else { - this._protocol._debug && this._protocol._debug( - 'Signature verification failed' - ); - } - return doFatalError( - this._protocol, - 'Handshake failed: signature verification failed', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug('Verified signature'); - } else { - // Server - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug && this._protocol._debug( - 'Generating signature ...' - ); - - let signature = this._hostKey.sign(exchangeHash, hashAlgo); - if (signature instanceof Error) { - return doFatalError( - this._protocol, - 'Handshake failed: signature generation failed for ' - + `${this._hostKey.type} host key: ${signature.message}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - signature = convertSignature(signature, this._hostKey.type); - if (signature === false) { - return doFatalError( - this._protocol, - 'Handshake failed: signature conversion failed for ' - + `${this._hostKey.type} host key`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Send KEX reply - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - const sigType = this.negotiated.serverHostKey; - const sigTypeLen = Buffer.byteLength(sigType); - const sigLen = 4 + sigTypeLen + 4 + signature.length; - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 - + 4 + serverPublicHostKey.length - + 4 + serverPublicKey.length - + 4 + sigLen, - true - ); - - packet[p] = MESSAGE.KEXDH_REPLY; - - writeUInt32BE(packet, serverPublicHostKey.length, ++p); - packet.set(serverPublicHostKey, p += 4); - - writeUInt32BE(packet, - serverPublicKey.length, - p += serverPublicHostKey.length); - packet.set(serverPublicKey, p += 4); - - writeUInt32BE(packet, sigLen, p += serverPublicKey.length); - - writeUInt32BE(packet, sigTypeLen, p += 4); - packet.utf8Write(sigType, p += 4, sigTypeLen); - - writeUInt32BE(packet, signature.length, p += sigTypeLen); - packet.set(signature, p += 4); - - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_REPLY'; - break; - case 'groupex': - type = 'KEXDH_GEX_REPLY'; - break; - default: - type = 'KEXECDH_REPLY'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - trySendNEWKEYS(this); - - const completeHandshake = () => { - if (!this.sessionID) - this.sessionID = exchangeHash; - - { - const newSecret = Buffer.allocUnsafe(4 + secret.length); - writeUInt32BE(newSecret, secret.length, 0); - newSecret.set(secret, 4); - secret = newSecret; - } - - // Initialize new ciphers, deciphers, etc. - - const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; - const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; - - const csIV = generateKEXVal(csCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'A'); - const scIV = generateKEXVal(scCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'B'); - const csKey = generateKEXVal(csCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'C'); - const scKey = generateKEXVal(scCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'D'); - let csMacInfo; - let csMacKey; - if (!csCipherInfo.authLen) { - csMacInfo = MAC_INFO[negotiated.cs.mac]; - csMacKey = generateKEXVal(csMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'E'); - } - let scMacInfo; - let scMacKey; - if (!scCipherInfo.authLen) { - scMacInfo = MAC_INFO[negotiated.sc.mac]; - scMacKey = generateKEXVal(scMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'F'); - } - - const config = { - inbound: { - onPayload: this._protocol._onPayload, - seqno: this._protocol._decipher.inSeqno, - decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), - decipherIV: (!isServer ? scIV : csIV), - decipherKey: (!isServer ? scKey : csKey), - macInfo: (!isServer ? scMacInfo : csMacInfo), - macKey: (!isServer ? scMacKey : csMacKey), - }, - outbound: { - onWrite: this._protocol._onWrite, - seqno: this._protocol._cipher.outSeqno, - cipherInfo: (isServer ? scCipherInfo : csCipherInfo), - cipherIV: (isServer ? scIV : csIV), - cipherKey: (isServer ? scKey : csKey), - macInfo: (isServer ? scMacInfo : csMacInfo), - macKey: (isServer ? scMacKey : csMacKey), - }, - }; - this._protocol._cipher && this._protocol._cipher.free(); - this._protocol._decipher && this._protocol._decipher.free(); - this._protocol._cipher = createCipher(config); - this._protocol._decipher = createDecipher(config); - - const rw = { - read: undefined, - write: undefined, - }; - switch (negotiated.cs.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.read = new PacketReader(); - else - rw.write = new PacketWriter(this._protocol); - } - switch (negotiated.sc.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.write = new PacketWriter(this._protocol); - else - rw.read = new PacketReader(); - } - this._protocol._packetRW.read.cleanup(); - this._protocol._packetRW.write.cleanup(); - this._protocol._packetRW = rw; - - // Cleanup/reset various state - this._public = null; - this._dh = null; - this._kexinit = this._protocol._kexinit = undefined; - this._remoteKexinit = undefined; - this._identRaw = undefined; - this._remoteIdentRaw = undefined; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - - this._protocol._onHandshakeComplete(negotiated); - - return false; - }; - if (!isServer) - return completeHandshake(); - this.finish = completeHandshake; - } - - start() { - if (!this._protocol._server) { - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_INIT'; - break; - default: - type = 'KEXECDH_INIT'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - - const pubKey = this.getPublicKey(); - - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + pubKey.length, - true - ); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - getPublicKey() { - this.generateKeys(); - - const key = this._public; - - if (key) - return this.convertPublicKey(key); - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - - if (key[idx] & 0x80) { - newKey = Buffer.allocUnsafe(1 + len); - newKey[0] = 0; - key.copy(newKey, 1, idx); - return newKey; - } - - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - return convertToMpint(this._dh.computeSecret(otherPublicKey)); - } catch (ex) { - return ex; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - // Server - if (type !== MESSAGE.KEXDH_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Init' - ); - /* - byte SSH_MSG_KEXDH_INIT - / SSH_MSG_KEX_ECDH_INIT - string - */ - bufferParser.init(payload, 1); - const dhData = bufferParser.readString(); - bufferParser.clear(); - if (dhData === undefined) { - return doFatalError( - this._protocol, - 'Received malformed KEX*_INIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Client public key - this._dhData = dhData; - - let hostKey = - this._protocol._hostKeys[this.negotiated.serverHostKey]; - if (Array.isArray(hostKey)) - hostKey = hostKey[0]; - this._hostKey = hostKey; - - this.finish(); - } else { - // Client - if (type !== MESSAGE.KEXDH_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Reply' - ); - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - bufferParser.init(payload, 1); - let hostPubKey; - let dhData; - let sig; - if ((hostPubKey = bufferParser.readString()) === undefined - || (dhData = bufferParser.readString()) === undefined - || (sig = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEX*_REPLY', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // Check that the host public key type matches what was negotiated - // during KEXINIT swap - bufferParser.init(hostPubKey, 0); - const hostPubKeyType = bufferParser.readString(true); - bufferParser.clear(); - if (hostPubKeyType === undefined) { - return doFatalError( - this._protocol, - 'Received malformed host public key', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (hostPubKeyType !== this.negotiated.serverHostKey) { - // Check if we need to make an exception - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': - case 'rsa-sha2-512': - if (hostPubKeyType === 'ssh-rsa') - break; - // FALLTHROUGH - default: - return doFatalError( - this._protocol, - 'Host key does not match negotiated type', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - this._hostKey = hostPubKey; - this._dhData = dhData; - this._sig = sig; - - let checked = false; - let ret; - if (this._protocol._hostVerifier === undefined) { - ret = true; - this._protocol._debug && this._protocol._debug( - 'Host accepted by default (no verification)' - ); - } else { - ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { - if (checked) - return; - checked = true; - if (permitted === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - if (this._receivedNEWKEYS) - this.finish(); - else - trySendNEWKEYS(this); - }); - } - if (ret === undefined) { - // Async host verification - ++this._step; - return; - } - checked = true; - if (ret === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - trySendNEWKEYS(this); - } - ++this._step; - break; - case 2: - if (type !== MESSAGE.NEWKEYS) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Inbound: NEWKEYS' - ); - this._receivedNEWKEYS = true; - ++this._step; - if (this._protocol._server || this._hostVerified) - return this.finish(); - - // Signal to current decipher that we need to change to a new decipher - // for the next packet - return false; - default: - return doFatalError( - this._protocol, - `Received unexpected packet ${type} after NEWKEYS`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - } - - class Curve25519Exchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - - this.type = '25519'; - this.hashName = hashName; - this._keys = null; - } - generateKeys() { - if (!this._keys) - this._keys = generateKeyPairSync('x25519'); - } - getPublicKey() { - this.generateKeys(); - - const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); - return key.slice(-32); // HACK: avoids parsing DER/BER header - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - - if (key.length === 32) - return key; - - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.110'); // id-X25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(otherPublicKey.length); - otherPublicKey.copy(asnWriter._buf, - asnWriter._offset, - 0, - otherPublicKey.length); - asnWriter._offset += otherPublicKey.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - - return convertToMpint(diffieHellman({ - privateKey: this._keys.privateKey, - publicKey: createPublicKey({ - key: asnWriter.buffer, - type: 'spki', - format: 'der', - }), - })); - } catch (ex) { - return ex; - } - } - } - - class ECDHExchange extends KeyExchange { - constructor(curveName, hashName, ...args) { - super(...args); - - this.type = 'ecdh'; - this.curveName = curveName; - this.hashName = hashName; - } - generateKeys() { - if (!this._dh) { - this._dh = createECDH(this.curveName); - this._public = this._dh.generateKeys(); - } - } - } - - class DHGroupExchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - - this.type = 'groupex'; - this.hashName = hashName; - this._prime = null; - this._generator = null; - this._minBits = GEX_MIN_BITS; - this._prefBits = dhEstimate(this.negotiated); - if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) - this._prefBits = Math.min(this._prefBits, 4096); - this._maxBits = GEX_MAX_BITS; - } - start() { - if (this._protocol._server) - return; - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_REQUEST' - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + 4 + 4, - true - ); - packet[p] = MESSAGE.KEXDH_GEX_REQUEST; - writeUInt32BE(packet, this._minBits, ++p); - writeUInt32BE(packet, this._prefBits, p += 4); - writeUInt32BE(packet, this._maxBits, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - generateKeys() { - if (!this._dh && this._prime && this._generator) { - this._dh = createDiffieHellman(this._prime, this._generator); - this._public = this._dh.generateKeys(); - } - } - setDHParams(prime, generator) { - if (!Buffer.isBuffer(prime)) - throw new Error('Invalid prime value'); - if (!Buffer.isBuffer(generator)) - throw new Error('Invalid generator value'); - this._prime = prime; - this._generator = generator; - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_REQUEST) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ` - + MESSAGE.KEXDH_GEX_REQUEST, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - // TODO: allow user implementation to provide safe prime and - // generator on demand to support group exchange on server side - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (type !== MESSAGE.KEXDH_GEX_GROUP) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Group' - ); - - /* - byte SSH_MSG_KEX_DH_GEX_GROUP - mpint p, safe prime - mpint g, generator for subgroup in GF(p) - */ - bufferParser.init(payload, 1); - let prime; - let gen; - if ((prime = bufferParser.readString()) === undefined - || (gen = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEXDH_GEX_GROUP', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // TODO: validate prime - this.setDHParams(prime, gen); - this.generateKeys(); - const pubkey = this.getPublicKey(); - - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_INIT' - ); - - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); - packet[p] = MESSAGE.KEXDH_GEX_INIT; - writeUInt32BE(packet, pubkey.length, ++p); - packet.set(pubkey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - - ++this._step; - break; - case 2: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Init' - ); - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Reply' - ); - this._step = 1; - payload[0] = MESSAGE.KEXDH_REPLY; - this.parse = KeyExchange.prototype.parse; - this.parse(payload); - } - } - } - - class DHExchange extends KeyExchange { - constructor(groupName, hashName, ...args) { - super(...args); - - this.type = 'group'; - this.groupName = groupName; - this.hashName = hashName; - } - start() { - if (!this._protocol._server) { - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_INIT' - ); - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - generateKeys() { - if (!this._dh) { - this._dh = createDiffieHellmanGroup(this.groupName); - this._public = this._dh.generateKeys(); - } - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } - } - } - - return (negotiated, ...args) => { - if (typeof negotiated !== 'object' || negotiated === null) - throw new Error('Invalid negotiated argument'); - const kexType = negotiated.kex; - if (typeof kexType === 'string') { - args = [negotiated, ...args]; - switch (kexType) { - case 'curve25519-sha256': - case 'curve25519-sha256@libssh.org': - if (!curve25519Supported) - break; - return new Curve25519Exchange('sha256', ...args); - - case 'ecdh-sha2-nistp256': - return new ECDHExchange('prime256v1', 'sha256', ...args); - case 'ecdh-sha2-nistp384': - return new ECDHExchange('secp384r1', 'sha384', ...args); - case 'ecdh-sha2-nistp521': - return new ECDHExchange('secp521r1', 'sha512', ...args); - - case 'diffie-hellman-group1-sha1': - return new DHExchange('modp2', 'sha1', ...args); - case 'diffie-hellman-group14-sha1': - return new DHExchange('modp14', 'sha1', ...args); - case 'diffie-hellman-group14-sha256': - return new DHExchange('modp14', 'sha256', ...args); - case 'diffie-hellman-group15-sha512': - return new DHExchange('modp15', 'sha512', ...args); - case 'diffie-hellman-group16-sha512': - return new DHExchange('modp16', 'sha512', ...args); - case 'diffie-hellman-group17-sha512': - return new DHExchange('modp17', 'sha512', ...args); - case 'diffie-hellman-group18-sha512': - return new DHExchange('modp18', 'sha512', ...args); - - case 'diffie-hellman-group-exchange-sha1': - return new DHGroupExchange('sha1', ...args); - case 'diffie-hellman-group-exchange-sha256': - return new DHGroupExchange('sha256', ...args); - } - throw new Error(`Unsupported key exchange algorithm: ${kexType}`); - } - throw new Error(`Invalid key exchange type: ${kexType}`); - }; -})(); - -const KexInit = (() => { - const KEX_PROPERTY_NAMES = [ - 'kex', - 'serverHostKey', - ['cs', 'cipher' ], - ['sc', 'cipher' ], - ['cs', 'mac' ], - ['sc', 'mac' ], - ['cs', 'compress' ], - ['sc', 'compress' ], - ['cs', 'lang' ], - ['sc', 'lang' ], - ]; - return class KexInit { - constructor(obj) { - if (typeof obj !== 'object' || obj === null) - throw new TypeError('Argument must be an object'); - - const lists = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - - all: undefined, - }; - let totalSize = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let base; - let val; - let desc; - let key; - if (typeof prop === 'string') { - base = lists; - val = obj[prop]; - desc = key = prop; - } else { - const parent = prop[0]; - base = lists[parent]; - key = prop[1]; - val = obj[parent][key]; - desc = `${parent}.${key}`; - } - const entry = { array: undefined, buffer: undefined }; - if (Buffer.isBuffer(val)) { - entry.array = ('' + val).split(','); - entry.buffer = val; - totalSize += 4 + val.length; - } else { - if (typeof val === 'string') - val = val.split(','); - if (Array.isArray(val)) { - entry.array = val; - entry.buffer = Buffer.from(val.join(',')); - } else { - throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); - } - totalSize += 4 + entry.buffer.length; - } - base[key] = entry; - } - - const all = Buffer.allocUnsafe(totalSize); - lists.all = all; - - let allPos = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let data; - if (typeof prop === 'string') - data = lists[prop].buffer; - else - data = lists[prop[0]][prop[1]].buffer; - allPos = writeUInt32BE(all, data.length, allPos); - all.set(data, allPos); - allPos += data.length; - } - - this.totalSize = totalSize; - this.lists = lists; - } - copyAllTo(buf, offset) { - const src = this.lists.all; - if (typeof offset !== 'number') - throw new TypeError(`Invalid offset value: ${typeof offset}`); - if (buf.length - offset < src.length) - throw new Error('Insufficient space to copy list'); - buf.set(src, offset); - return src.length; - } - }; -})(); - -const hashString = (() => { - const LEN = Buffer.allocUnsafe(4); - return (hash, buf) => { - writeUInt32BE(LEN, buf.length, 0); - hash.update(LEN); - hash.update(buf); - }; -})(); - -function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { - let ret; - if (len) { - let digest = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(char) - .update(sessionID) - .digest(); - while (digest.length < len) { - const chunk = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(digest) - .digest(); - const extended = Buffer.allocUnsafe(digest.length + chunk.length); - extended.set(digest, 0); - extended.set(chunk, digest.length); - digest = extended; - } - if (digest.length === len) - ret = digest; - else - ret = new FastBuffer(digest.buffer, digest.byteOffset, len); - } else { - ret = EMPTY_BUFFER; - } - return ret; -} - -function onKEXPayload(state, payload) { - // XXX: move this to the Decipher implementations? - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - if (this._skipNextInboundPacket) { - this._skipNextInboundPacket = false; - return; - } - - payload = this._packetRW.read.read(payload); - - const type = payload[0]; - switch (type) { - case MESSAGE.DISCONNECT: - case MESSAGE.IGNORE: - case MESSAGE.UNIMPLEMENTED: - case MESSAGE.DEBUG: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = require('./handlers.js'); - return MESSAGE_HANDLERS[type](this, payload); - case MESSAGE.KEXINIT: - if (!state.firstPacket) { - return doFatalError( - this, - 'Received extra KEXINIT during handshake', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - state.firstPacket = false; - return handleKexInit(this, payload); - default: - if (type < 20 || type > 49) { - return doFatalError( - this, - `Received unexpected packet type ${type}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - return this._kex.parse(payload); -} - -function dhEstimate(neg) { - const csCipher = CIPHER_INFO[neg.cs.cipher]; - const scCipher = CIPHER_INFO[neg.sc.cipher]; - // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will - // also need to be considered when calculating `bits` - const bits = Math.max( - 0, - (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), - csCipher.blockLen, - csCipher.ivLen, - (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), - scCipher.blockLen, - scCipher.ivLen - ) * 8; - if (bits <= 112) - return 2048; - if (bits <= 128) - return 3072; - if (bits <= 192) - return 7680; - return 8192; -} - -function trySendNEWKEYS(kex) { - if (!kex._sentNEWKEYS) { - kex._protocol._debug && kex._protocol._debug( - 'Outbound: Sending NEWKEYS' - ); - const p = kex._protocol._packetRW.write.allocStartKEX; - const packet = kex._protocol._packetRW.write.alloc(1, true); - packet[p] = MESSAGE.NEWKEYS; - kex._protocol._cipher.encrypt( - kex._protocol._packetRW.write.finalize(packet, true) - ); - kex._sentNEWKEYS = true; - } -} - -module.exports = { - KexInit, - kexinit, - onKEXPayload, - DEFAULT_KEXINIT: new KexInit({ - kex: DEFAULT_KEX, - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - HANDLERS: { - [MESSAGE.KEXINIT]: handleKexInit, - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/keyParser.js b/reverse_engineering/node_modules/ssh2/lib/protocol/keyParser.js deleted file mode 100644 index 9860e3f..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/keyParser.js +++ /dev/null @@ -1,1481 +0,0 @@ -// TODO: -// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` -// * handle multi-line header values (OpenSSH)? -// * more thorough validation? -'use strict'; - -const { - createDecipheriv, - createECDH, - createHash, - createHmac, - createSign, - createVerify, - getCiphers, - sign: sign_, - verify: verify_, -} = require('crypto'); -const supportedOpenSSLCiphers = getCiphers(); - -const { Ber } = require('asn1'); -const bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf; - -const { CIPHER_INFO } = require('./crypto.js'); -const { eddsaSupported, SUPPORTED_CIPHER } = require('./constants.js'); -const { - bufferSlice, - makeBufferParser, - readString, - readUInt32BE, - writeUInt32BE, -} = require('./utils.js'); - -const SYM_HASH_ALGO = Symbol('Hash Algorithm'); -const SYM_PRIV_PEM = Symbol('Private key PEM'); -const SYM_PUB_PEM = Symbol('Public key PEM'); -const SYM_PUB_SSH = Symbol('Public key SSH'); -const SYM_DECRYPTED = Symbol('Decrypted Key'); - -// Create OpenSSL cipher name -> SSH cipher name conversion table -const CIPHER_INFO_OPENSSL = Object.create(null); -{ - const keys = Object.keys(CIPHER_INFO); - for (let i = 0; i < keys.length; ++i) { - const cipherName = CIPHER_INFO[keys[i]].sslName; - if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) - continue; - CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; - } -} - -const binaryKeyParser = makeBufferParser(); - -function makePEM(type, data) { - data = data.base64Slice(0, data.length); - let formatted = data.replace(/.{64}/g, '$&\n'); - if (data.length & 63) - formatted += '\n'; - return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; -} - -function combineBuffers(buf1, buf2) { - const result = Buffer.allocUnsafe(buf1.length + buf2.length); - result.set(buf1, 0); - result.set(buf2, buf1.length); - return result; -} - -function skipFields(buf, nfields) { - const bufLen = buf.length; - let pos = (buf._pos || 0); - for (let i = 0; i < nfields; ++i) { - const left = (bufLen - pos); - if (pos >= bufLen || left < 4) - return false; - const len = readUInt32BE(buf, pos); - if (left < 4 + len) - return false; - pos += 4 + len; - } - buf._pos = pos; - return true; -} - -function genOpenSSLRSAPub(n, e) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption - // algorithm parameters (RSA has none) - asnWriter.writeNull(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.startSequence(); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHRSAPub(n, e) { - const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); - - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-rsa', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, e.length, i); - publicKey.set(e, i += 4); - - writeUInt32BE(publicKey, n.length, i += e.length); - publicKey.set(n, i + 4); - - return publicKey; -} - -const genOpenSSLRSAPriv = (() => { - function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.writeBuffer(d, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(dmp1, Ber.Integer); - asnWriter.writeBuffer(dmq1, Ber.Integer); - asnWriter.writeBuffer(iqmp, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - - function bigIntFromBuffer(buf) { - return BigInt(`0x${buf.hexSlice(0, buf.length)}`); - } - - function bigIntToBuffer(bn) { - let hex = bn.toString(16); - if ((hex.length & 1) !== 0) { - hex = `0${hex}`; - } else { - const sigbit = hex.charCodeAt(0); - // BER/DER integers require leading zero byte to denote a positive value - // when first byte >= 0x80 - if (sigbit === 56/* '8' */ - || sigbit === 57/* '9' */ - || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { - hex = `00${hex}`; - } - } - return Buffer.from(hex, 'hex'); - } - - return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { - const bn_d = bigIntFromBuffer(d); - const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); - const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); - return makePEM('RSA PRIVATE', - genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); - }; -})(); - -function genOpenSSLDSAPub(p, q, g, y) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa - // algorithm parameters - asnWriter.startSequence(); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHDSAPub(p, q, g, y) { - const publicKey = Buffer.allocUnsafe( - 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length - ); - - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-dss', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, p.length, i); - publicKey.set(p, i += 4); - - writeUInt32BE(publicKey, q.length, i += p.length); - publicKey.set(q, i += 4); - - writeUInt32BE(publicKey, g.length, i += q.length); - publicKey.set(g, i += 4); - - writeUInt32BE(publicKey, y.length, i += g.length); - publicKey.set(y, i + 4); - - return publicKey; -} - -function genOpenSSLDSAPriv(p, q, g, y, x) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.writeBuffer(x, Ber.Integer); - asnWriter.endSequence(); - return makePEM('DSA PRIVATE', asnWriter.buffer); -} - -function genOpenSSLEdPub(pub) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHEdPub(pub) { - const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); - - writeUInt32BE(publicKey, 11, 0); - publicKey.utf8Write('ssh-ed25519', 4, 11); - - writeUInt32BE(publicKey, pub.length, 15); - publicKey.set(pub, 19); - - return publicKey; -} - -function genOpenSSLEdPriv(priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x00, Ber.Integer); - - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PrivateKey - asnWriter.startSequence(Ber.OctetString); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPub(oid, Q) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey - // algorithm parameters (namedCurve) - asnWriter.writeOID(oid); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(Q.length); - asnWriter._buf.set(Q, asnWriter._offset); - asnWriter._offset += Q.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHECDSAPub(oid, Q) { - let curveName; - switch (oid) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - curveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - curveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - curveName = 'nistp521'; - break; - default: - return; - } - - const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); - - writeUInt32BE(publicKey, 19, 0); - publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); - - writeUInt32BE(publicKey, 8, 23); - publicKey.utf8Write(curveName, 27, 8); - - writeUInt32BE(publicKey, Q.length, 35); - publicKey.set(Q, 39); - - return publicKey; -} - -function genOpenSSLECDSAPriv(oid, pub, priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x01, Ber.Integer); - // privateKey - asnWriter.writeBuffer(priv, Ber.OctetString); - // parameters (optional) - asnWriter.startSequence(0xA0); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - // publicKey (optional) - asnWriter.startSequence(0xA1); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('EC PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPubFromPriv(curveName, priv) { - const tempECDH = createECDH(curveName); - tempECDH.setPrivateKey(priv); - return tempECDH.getPublicKey(); -} - -const BaseKey = { - sign: (() => { - if (typeof sign_ === 'function') { - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return sign_(algo, data, pem); - } catch (ex) { - return ex; - } - }; - } - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const signature = createSign(algo); - signature.update(data); - try { - return signature.sign(pem); - } catch (ex) { - return ex; - } - }; - })(), - verify: (() => { - if (typeof verify_ === 'function') { - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return verify_(algo, data, pem, signature); - } catch (ex) { - return ex; - } - }; - } - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const verifier = createVerify(algo); - verifier.update(data); - try { - return verifier.verify(pem, signature); - } catch (ex) { - return ex; - } - }; - })(), - isPrivateKey: function isPrivateKey() { - return (this[SYM_PRIV_PEM] !== null); - }, - getPrivatePEM: function getPrivatePEM() { - return this[SYM_PRIV_PEM]; - }, - getPublicPEM: function getPublicPEM() { - return this[SYM_PUB_PEM]; - }, - getPublicSSH: function getPublicSSH() { - return this[SYM_PUB_SSH]; - }, - equals: function equals(key) { - const parsed = parseKey(key); - if (parsed instanceof Error) - return false; - return ( - this.type === parsed.type - && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] - && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] - && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH] - ); - }, -}; - - -function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; - OpenSSH_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let ret; - const data = Buffer.from(m[1], 'base64'); - if (data.length < 31) // magic (+ magic null term.) + minimum field lengths - return new Error('Malformed OpenSSH private key'); - const magic = data.utf8Slice(0, 15); - if (magic !== 'openssh-key-v1\0') - return new Error(`Unsupported OpenSSH key magic: ${magic}`); - - const cipherName = readString(data, 15, true); - if (cipherName === undefined) - return new Error('Malformed OpenSSH private key'); - if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) - return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); - - const kdfName = readString(data, data._pos, true); - if (kdfName === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'none') { - if (cipherName === 'none') - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'bcrypt') - return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); - if (!passphrase) { - return new Error( - 'Encrypted private OpenSSH key detected, but no passphrase given' - ); - } - } else if (cipherName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - let encInfo; - let cipherKey; - let cipherIV; - if (cipherName !== 'none') - encInfo = CIPHER_INFO[cipherName]; - const kdfOptions = readString(data, data._pos); - if (kdfOptions === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfOptions.length) { - switch (kdfName) { - case 'none': - return new Error('Malformed OpenSSH private key'); - case 'bcrypt': - /* - string salt - uint32 rounds - */ - const salt = readString(kdfOptions, 0); - if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) - return new Error('Malformed OpenSSH private key'); - const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); - const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); - const r = bcrypt_pbkdf(passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds); - if (r !== 0) - return new Error('Failed to generate information to decrypt key'); - cipherKey = bufferSlice(gen, 0, encInfo.keyLen); - cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); - break; - } - } else if (kdfName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - if (data._pos + 3 >= data.length) - return new Error('Malformed OpenSSH private key'); - const keyCount = readUInt32BE(data, data._pos); - data._pos += 4; - - if (keyCount > 0) { - // TODO: place sensible limit on max `keyCount` - - // Read public keys first - for (let i = 0; i < keyCount; ++i) { - const pubData = readString(data, data._pos); - if (pubData === undefined) - return new Error('Malformed OpenSSH private key'); - const type = readString(pubData, 0, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - } - - let privBlob = readString(data, data._pos); - if (privBlob === undefined) - return new Error('Malformed OpenSSH private key'); - - if (cipherKey !== undefined) { - // Encrypted private key(s) - if (privBlob.length < encInfo.blockLen - || (privBlob.length % encInfo.blockLen) !== 0) { - return new Error('Malformed OpenSSH private key'); - } - try { - const options = { authTagLength: encInfo.authLen }; - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - cipherIV, - options); - if (encInfo.authLen > 0) { - if (data.length - data._pos < encInfo.authLen) - return new Error('Malformed OpenSSH private key'); - decipher.setAuthTag( - bufferSlice(data, data._pos, data._pos += encInfo.authLen) - ); - } - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } - // Nothing should we follow the private key(s), except a possible - // authentication tag for relevant ciphers - if (data._pos !== data.length) - return new Error('Malformed OpenSSH private key'); - - ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); - } else { - ret = []; - } - // This will need to change if/when OpenSSH ever starts storing multiple - // keys in their key files - return ret[0]; - }; - - function parseOpenSSHPrivKeys(data, nkeys, decrypted) { - const keys = []; - /* - uint32 checkint - uint32 checkint - string privatekey1 - string comment1 - string privatekey2 - string comment2 - ... - string privatekeyN - string commentN - char 1 - char 2 - char 3 - ... - char padlen % 255 - */ - if (data.length < 8) - return new Error('Malformed OpenSSH private key'); - const check1 = readUInt32BE(data, 0); - const check2 = readUInt32BE(data, 4); - if (check1 !== check2) { - if (decrypted) { - return new Error( - 'OpenSSH key integrity check failed -- bad passphrase?' - ); - } - return new Error('OpenSSH key integrity check failed'); - } - data._pos = 8; - let i; - let oid; - for (i = 0; i < nkeys; ++i) { - let algo; - let privPEM; - let pubPEM; - let pubSSH; - // The OpenSSH documentation for the key format actually lies, the - // entirety of the private key content is not contained with a string - // field, it's actually the literal contents of the private key, so to be - // able to find the end of the key data you need to know the layout/format - // of each key type ... - const type = readString(data, data._pos, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - - switch (type) { - case 'ssh-rsa': { - /* - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH private key'); - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed OpenSSH private key'); - const d = readString(data, data._pos); - if (d === undefined) - return new Error('Malformed OpenSSH private key'); - const iqmp = readString(data, data._pos); - if (iqmp === undefined) - return new Error('Malformed OpenSSH private key'); - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - /* - string p -- public - string q -- public - string g -- public - string y -- public - string x -- private - */ - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH private key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH private key'); - const x = readString(data, data._pos); - if (x === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - if (!eddsaSupported) - return new Error(`Unsupported OpenSSH private key type: ${type}`); - /* - * string public key - * string private key + public key - */ - const edpub = readString(data, data._pos); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH private key'); - const edpriv = readString(data, data._pos); - if (edpriv === undefined || edpriv.length !== 64) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - /* - string curve name - string Q -- public - string d -- private - */ - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH private key'); - const ecpub = readString(data, data._pos); - if (ecpub === undefined) - return new Error('Malformed OpenSSH private key'); - const ecpriv = readString(data, data._pos); - if (ecpriv === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); - break; - } - default: - return new Error(`Unsupported OpenSSH private key type: ${type}`); - } - - const privComment = readString(data, data._pos, true); - if (privComment === undefined) - return new Error('Malformed OpenSSH private key'); - - keys.push( - new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, - decrypted) - ); - } - let cnt = 0; - for (i = data._pos; i < data.length; ++i) { - if (data[i] !== (++cnt % 255)) - return new Error('Malformed OpenSSH private key'); - } - - return keys; - } -} - - -function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Old_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; - OpenSSH_Old_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let privBlob = Buffer.from(m[3], 'base64'); - let headers = m[2]; - let decrypted = false; - if (headers !== undefined) { - // encrypted key - headers = headers.split(/\r\n|\n/g); - for (let i = 0; i < headers.length; ++i) { - const header = headers[i]; - let sepIdx = header.indexOf(':'); - if (header.slice(0, sepIdx) === 'DEK-Info') { - const val = header.slice(sepIdx + 2); - sepIdx = val.indexOf(','); - if (sepIdx === -1) - continue; - const cipherName = val.slice(0, sepIdx).toLowerCase(); - if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const encInfo = CIPHER_INFO_OPENSSL[cipherName]; - if (!encInfo) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); - if (cipherIV.length !== encInfo.ivLen) - return new Error('Malformed encrypted OpenSSH private key'); - if (!passphrase) { - return new Error( - 'Encrypted OpenSSH private key detected, but no passphrase given' - ); - } - const ivSlice = bufferSlice(cipherIV, 0, 8); - let cipherKey = createHash('md5') - .update(passphrase) - .update(ivSlice) - .digest(); - while (cipherKey.length < encInfo.keyLen) { - cipherKey = combineBuffers( - cipherKey, - createHash('md5') - .update(cipherKey) - .update(passphrase) - .update(ivSlice) - .digest() - ); - } - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - decrypted = true; - } catch (ex) { - return ex; - } - } - } - } - - let type; - let privPEM; - let pubPEM; - let pubSSH; - let algo; - let reader; - let errMsg = 'Malformed OpenSSH private key'; - if (decrypted) - errMsg += '. Bad passphrase?'; - switch (m[1]) { - case 'RSA': - type = 'ssh-rsa'; - privPEM = makePEM('RSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const n = reader.readString(Ber.Integer, true); - if (n === null) - return new Error(errMsg); - const e = reader.readString(Ber.Integer, true); - if (e === null) - return new Error(errMsg); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'DSA': - type = 'ssh-dss'; - privPEM = makePEM('DSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const p = reader.readString(Ber.Integer, true); - if (p === null) - return new Error(errMsg); - const q = reader.readString(Ber.Integer, true); - if (q === null) - return new Error(errMsg); - const g = reader.readString(Ber.Integer, true); - if (g === null) - return new Error(errMsg); - const y = reader.readString(Ber.Integer, true); - if (y === null) - return new Error(errMsg); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'EC': - let ecSSLName; - let ecPriv; - let ecOID; - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - ecPriv = reader.readString(Ber.OctetString, true); - reader.readByte(); // Skip "complex" context type byte - const offset = reader.readLength(); // Skip context length - if (offset !== null) { - reader._offset = offset; - ecOID = reader.readOID(); - if (ecOID === null) - return new Error(errMsg); - switch (ecOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - ecSSLName = 'prime256v1'; - type = 'ecdsa-sha2-nistp256'; - algo = 'sha256'; - break; - case '1.3.132.0.34': - // secp384r1 - ecSSLName = 'secp384r1'; - type = 'ecdsa-sha2-nistp384'; - algo = 'sha384'; - break; - case '1.3.132.0.35': - // secp521r1 - ecSSLName = 'secp521r1'; - type = 'ecdsa-sha2-nistp521'; - algo = 'sha512'; - break; - default: - return new Error(`Unsupported private key EC OID: ${ecOID}`); - } - } else { - return new Error(errMsg); - } - } catch { - return new Error(errMsg); - } - privPEM = makePEM('EC PRIVATE', privBlob); - const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); - pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); - pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); - break; - } - - return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, - decrypted); - }; -} - - -function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -PPK_Private.prototype = BaseKey; -{ - const EMPTY_PASSPHRASE = Buffer.alloc(0); - const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - const PPK_PP1 = Buffer.from([0, 0, 0, 0]); - const PPK_PP2 = Buffer.from([0, 0, 0, 1]); - const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; - PPK_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = key type - // m[2] = encryption type - // m[3] = comment - // m[4] = base64-encoded public key data: - // for "ssh-rsa": - // string "ssh-rsa" - // mpint e (public exponent) - // mpint n (modulus) - // for "ssh-dss": - // string "ssh-dss" - // mpint p (modulus) - // mpint q (prime) - // mpint g (base number) - // mpint y (public key parameter: g^x mod p) - // m[5] = base64-encoded private key data: - // for "ssh-rsa": - // mpint d (private exponent) - // mpint p (prime 1) - // mpint q (prime 2) - // mpint iqmp ([inverse of q] mod p) - // for "ssh-dss": - // mpint x (private key parameter) - // m[6] = SHA1 HMAC over: - // string name of algorithm ("ssh-dss", "ssh-rsa") - // string encryption type - // string comment - // string public key data - // string private-plaintext (including the final padding) - const cipherName = m[2]; - const encrypted = (cipherName !== 'none'); - if (encrypted && !passphrase) { - return new Error( - 'Encrypted PPK private key detected, but no passphrase given' - ); - } - - let privBlob = Buffer.from(m[5], 'base64'); - - if (encrypted) { - const encInfo = CIPHER_INFO[cipherName]; - let cipherKey = combineBuffers( - createHash('sha1').update(PPK_PP1).update(passphrase).digest(), - createHash('sha1').update(PPK_PP2).update(passphrase).digest() - ); - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - PPK_IV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } - - const type = m[1]; - const comment = m[3]; - const pubBlob = Buffer.from(m[4], 'base64'); - - const mac = m[6]; - const typeLen = type.length; - const cipherNameLen = cipherName.length; - const commentLen = Buffer.byteLength(comment); - const pubLen = pubBlob.length; - const privLen = privBlob.length; - const macData = Buffer.allocUnsafe(4 + typeLen - + 4 + cipherNameLen - + 4 + commentLen - + 4 + pubLen - + 4 + privLen); - let p = 0; - - writeUInt32BE(macData, typeLen, p); - macData.utf8Write(type, p += 4, typeLen); - writeUInt32BE(macData, cipherNameLen, p += typeLen); - macData.utf8Write(cipherName, p += 4, cipherNameLen); - writeUInt32BE(macData, commentLen, p += cipherNameLen); - macData.utf8Write(comment, p += 4, commentLen); - writeUInt32BE(macData, pubLen, p += commentLen); - macData.set(pubBlob, p += 4); - writeUInt32BE(macData, privLen, p += pubLen); - macData.set(privBlob, p + 4); - - if (!passphrase) - passphrase = EMPTY_PASSPHRASE; - - const calcMAC = createHmac( - 'sha1', - createHash('sha1') - .update('putty-private-key-file-mac-key') - .update(passphrase) - .digest() - ).update(macData).digest('hex'); - - if (calcMAC !== mac) { - if (encrypted) { - return new Error( - 'PPK private key integrity check failed -- bad passphrase?' - ); - } - return new Error('PPK private key integrity check failed'); - } - - let pubPEM; - let pubSSH; - let privPEM; - pubBlob._pos = 0; - skipFields(pubBlob, 1); // skip (duplicate) key type - switch (type) { - case 'ssh-rsa': { - const e = readString(pubBlob, pubBlob._pos); - if (e === undefined) - return new Error('Malformed PPK public key'); - const n = readString(pubBlob, pubBlob._pos); - if (n === undefined) - return new Error('Malformed PPK public key'); - const d = readString(privBlob, 0); - if (d === undefined) - return new Error('Malformed PPK private key'); - const p = readString(privBlob, privBlob._pos); - if (p === undefined) - return new Error('Malformed PPK private key'); - const q = readString(privBlob, privBlob._pos); - if (q === undefined) - return new Error('Malformed PPK private key'); - const iqmp = readString(privBlob, privBlob._pos); - if (iqmp === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - break; - } - case 'ssh-dss': { - const p = readString(pubBlob, pubBlob._pos); - if (p === undefined) - return new Error('Malformed PPK public key'); - const q = readString(pubBlob, pubBlob._pos); - if (q === undefined) - return new Error('Malformed PPK public key'); - const g = readString(pubBlob, pubBlob._pos); - if (g === undefined) - return new Error('Malformed PPK public key'); - const y = readString(pubBlob, pubBlob._pos); - if (y === undefined) - return new Error('Malformed PPK public key'); - const x = readString(privBlob, 0); - if (x === undefined) - return new Error('Malformed PPK private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - break; - } - } - - return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', - encrypted); - }; -} - - -function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -OpenSSH_Public.prototype = BaseKey; -{ - let regexp; - if (eddsaSupported) - regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - else - regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - OpenSSH_Public.parse = (str) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = full type - // m[2] = base type - // m[3] = base64-encoded public key - // m[4] = comment - - const fullType = m[1]; - const baseType = m[2]; - const data = Buffer.from(m[3], 'base64'); - const comment = (m[4] || ''); - - const type = readString(data, data._pos, true); - if (type === undefined || type.indexOf(baseType) !== 0) - return new Error('Malformed OpenSSH public key'); - - return parseDER(data, baseType, comment, fullType); - }; -} - - -function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -RFC4716_Public.prototype = BaseKey; -{ - const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; - const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; - const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; - const RE_HEADER_ENDS = /\\\r?\n/g; - RFC4716_Public.parse = (str) => { - let m = regexp.exec(str); - if (m === null) - return null; - - const body = m[1]; - let dataStart = 0; - let comment = ''; - - while (m = RE_HEADER.exec(body)) { - const headerName = m[1]; - const headerValue = m[2].replace(RE_HEADER_ENDS, ''); - if (headerValue.length > 1024) { - RE_HEADER.lastIndex = 0; - return new Error('Malformed RFC4716 public key'); - } - - dataStart = RE_HEADER.lastIndex; - - if (headerName.toLowerCase() === 'comment') { - comment = headerValue; - if (comment.length > 1 - && comment.charCodeAt(0) === 34/* '"' */ - && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { - comment = comment.slice(1, -1); - } - } - } - - let data = body.slice(dataStart); - if (!RE_DATA.test(data)) - return new Error('Malformed RFC4716 public key'); - - data = Buffer.from(data, 'base64'); - - const type = readString(data, 0, true); - if (type === undefined) - return new Error('Malformed RFC4716 public key'); - - let pubPEM = null; - let pubSSH = null; - switch (type) { - case 'ssh-rsa': { - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed RFC4716 public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed RFC4716 public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed RFC4716 public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed RFC4716 public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - break; - } - default: - return new Error('Malformed RFC4716 public key'); - } - - return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); - }; -} - - -function parseDER(data, baseType, comment, fullType) { - if (!isSupportedKeyType(baseType)) - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - - let algo; - let oid; - let pubPEM = null; - let pubSSH = null; - - switch (baseType) { - case 'ssh-rsa': { - const e = readString(data, data._pos || 0); - if (e === undefined) - return new Error('Malformed OpenSSH public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos || 0); - if (p === undefined) - return new Error('Malformed OpenSSH public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - const edpub = readString(data, data._pos || 0); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH public key'); - const ecpub = readString(data, data._pos || 0); - if (ecpub === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - break; - } - default: - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - } - - return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); -} - -function isSupportedKeyType(type) { - switch (type) { - case 'ssh-rsa': - case 'ssh-dss': - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': - return true; - case 'ssh-ed25519': - if (eddsaSupported) - return true; - // FALLTHROUGH - default: - return false; - } -} - -function isParsedKey(val) { - if (!val) - return false; - return (typeof val[SYM_DECRYPTED] === 'boolean'); -} - -function parseKey(data, passphrase) { - if (isParsedKey(data)) - return data; - - let origBuffer; - if (Buffer.isBuffer(data)) { - origBuffer = data; - data = data.utf8Slice(0, data.length).trim(); - } else if (typeof data === 'string') { - data = data.trim(); - } else { - return new Error('Key data must be a Buffer or string'); - } - - // eslint-disable-next-line eqeqeq - if (passphrase != undefined) { - if (typeof passphrase === 'string') - passphrase = Buffer.from(passphrase); - else if (!Buffer.isBuffer(passphrase)) - return new Error('Passphrase must be a string or Buffer when supplied'); - } - - let ret; - - // First try as printable string format (e.g. PEM) - - // Private keys - if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = PPK_Private.parse(data, passphrase)) !== null) - return ret; - - // Public keys - if ((ret = OpenSSH_Public.parse(data)) !== null) - return ret; - if ((ret = RFC4716_Public.parse(data)) !== null) - return ret; - - // Finally try as a binary format if we were originally passed binary data - if (origBuffer) { - binaryKeyParser.init(origBuffer, 0); - const type = binaryKeyParser.readString(true); - if (type !== undefined) { - data = binaryKeyParser.readRaw(); - if (data !== undefined) { - ret = parseDER(data, type, '', type); - // Ignore potentially useless errors in case the data was not actually - // in the binary format - if (ret instanceof Error) - ret = null; - } - } - binaryKeyParser.clear(); - } - - if (ret) - return ret; - - return new Error('Unsupported key format'); -} - -module.exports = { - isParsedKey, - isSupportedKeyType, - parseDERKey: (data, type) => parseDER(data, type, '', type), - parseKey, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/node-fs-compat.js b/reverse_engineering/node_modules/ssh2/lib/protocol/node-fs-compat.js deleted file mode 100644 index 80ed71f..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/node-fs-compat.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -// Only use this for integers! Decimal numbers do not work with this function. -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 oneOf(expected, thing) { - assert(typeof thing === 'string', '`thing` has to be of type string'); - if (Array.isArray(expected)) { - const len = expected.length; - assert(len > 0, 'At least one expected value needs to be specified'); - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` - + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } - return `of ${thing} ${expected[0]}`; - } - return `of ${thing} ${String(expected)}`; -} - - -exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { - constructor(message) { - super(); - Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); - - const suffix = 'This is caused by either a bug in ssh2 ' - + 'or incorrect usage of ssh2 internals.\n' - + 'Please open an issue with this stack trace at ' - + 'https://github.com/mscdex/ssh2/issues\n'; - - this.message = (message === undefined ? suffix : `${message}\n${suffix}`); - } -}; - -const MAX_32BIT_INT = 2 ** 32; -const MAX_32BIT_BIGINT = (() => { - try { - return new Function('return 2n ** 32n')(); - } catch {} -})(); -exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { - constructor(str, range, input, replaceDefaultBoolean) { - super(); - Error.captureStackTrace(this, ERR_OUT_OF_RANGE); - - assert(range, 'Missing "range" argument'); - let msg = (replaceDefaultBoolean - ? str - : `The value of "${str}" is out of range.`); - let received; - if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === 'bigint') { - received = String(input); - if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) - received = addNumericalSeparator(received); - received += 'n'; - } else { - received = inspect(input); - } - msg += ` It must be ${range}. Received ${received}`; - - this.message = msg; - } -}; - -class ERR_INVALID_ARG_TYPE extends TypeError { - constructor(name, expected, actual) { - super(); - Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); - - assert(typeof name === 'string', `'name' must be a string`); - - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && expected.startsWith('not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (name.endsWith(' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = (name.includes('.') ? 'property' : 'argument'); - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - - this.message = msg; - } -} -exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; - -exports.validateNumber = function validateNumber(value, name) { - if (typeof value !== 'number') - throw new ERR_INVALID_ARG_TYPE(name, 'number', value); -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/utils.js b/reverse_engineering/node_modules/ssh2/lib/protocol/utils.js deleted file mode 100644 index 0dab875..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/utils.js +++ /dev/null @@ -1,356 +0,0 @@ -'use strict'; - -const Ber = require('asn1').Ber; - -let DISCONNECT_REASON; - -const FastBuffer = Buffer[Symbol.species]; -const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; - -function readUInt32BE(buf, offset) { - return (buf[offset++] * 16777216) - + (buf[offset++] * 65536) - + (buf[offset++] * 256) - + buf[offset]; -} - -function bufferCopy(src, dest, srcStart, srcEnd, destStart) { - if (!destStart) - destStart = 0; - if (srcEnd > src.length) - srcEnd = src.length; - let nb = srcEnd - srcStart; - const destLeft = (dest.length - destStart); - if (nb > destLeft) - nb = destLeft; - dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), - destStart); - return nb; -} - -function bufferSlice(buf, start, end) { - if (end === undefined) - end = buf.length; - return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); -} - -function makeBufferParser() { - let pos = 0; - let buffer; - - const self = { - init: (buf, start) => { - buffer = buf; - pos = (typeof start === 'number' ? start : 0); - }, - pos: () => pos, - length: () => (buffer ? buffer.length : 0), - avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), - clear: () => { - buffer = undefined; - }, - readUInt32BE: () => { - if (!buffer || pos + 3 >= buffer.length) - return; - return (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - }, - readUInt64BE: (behavior) => { - if (!buffer || pos + 7 >= buffer.length) - return; - switch (behavior) { - case 'always': - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - case 'maybe': - if (buffer[pos] > 0x1F) - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - // FALLTHROUGH - default: - return (buffer[pos++] * 72057594037927940) - + (buffer[pos++] * 281474976710656) - + (buffer[pos++] * 1099511627776) - + (buffer[pos++] * 4294967296) - + (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - } - }, - skip: (n) => { - if (buffer && n > 0) - pos += n; - }, - skipString: () => { - const len = self.readUInt32BE(); - if (len === undefined) - return; - pos += len; - return (pos <= buffer.length ? len : undefined); - }, - readByte: () => { - if (buffer && pos < buffer.length) - return buffer[pos++]; - }, - readBool: () => { - if (buffer && pos < buffer.length) - return !!buffer[pos++]; - }, - readList: () => { - const list = self.readString(true); - if (list === undefined) - return; - return (list ? list.split(',') : []); - }, - readString: (dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } - - const len = self.readUInt32BE(); - if (len === undefined) - return; - - if ((buffer.length - pos) < len - || (typeof maxLen === 'number' && len > maxLen)) { - return; - } - - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, pos, pos += len); - return buffer.utf8Slice(pos, pos += len); - } - return bufferSlice(buffer, pos, pos += len); - }, - readRaw: (len) => { - if (!buffer) - return; - if (typeof len !== 'number') - return bufferSlice(buffer, pos, pos += (buffer.length - pos)); - if ((buffer.length - pos) >= len) - return bufferSlice(buffer, pos, pos += len); - }, - }; - - return self; -} - -function makeError(msg, level, fatal) { - const err = new Error(msg); - if (typeof level === 'boolean') { - fatal = level; - err.level = 'protocol'; - } else { - err.level = level || 'protocol'; - } - err.fatal = !!fatal; - return err; -} - -function writeUInt32BE(buf, value, offset) { - buf[offset++] = (value >>> 24); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 8); - buf[offset++] = value; - return offset; -} - -const utilBufferParser = makeBufferParser(); - -module.exports = { - bufferCopy, - bufferSlice, - FastBuffer, - bufferFill: (buf, value, start, end) => { - return TypedArrayFill.call(buf, value, start, end); - }, - makeError, - doFatalError: (protocol, msg, level, reason) => { - let err; - if (DISCONNECT_REASON === undefined) - ({ DISCONNECT_REASON } = require('./utils.js')); - if (msg instanceof Error) { - // doFatalError(protocol, err[, reason]) - err = msg; - if (typeof level !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - else - reason = level; - } else { - // doFatalError(protocol, msg[, level[, reason]]) - err = makeError(msg, level, true); - } - if (typeof reason !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - protocol.disconnect(reason); - protocol._destruct(); - protocol._onError(err); - return Infinity; - }, - readUInt32BE, - writeUInt32BE, - writeUInt32LE: (buf, value, offset) => { - buf[offset++] = value; - buf[offset++] = (value >>> 8); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 24); - return offset; - }, - makeBufferParser, - bufferParser: makeBufferParser(), - readString: (buffer, start, dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } - - if (start === undefined) - start = 0; - - const left = (buffer.length - start); - if (start < 0 || start >= buffer.length || left < 4) - return; - - const len = readUInt32BE(buffer, start); - if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) - return; - - start += 4; - const end = start + len; - buffer._pos = end; - - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, start, end); - return buffer.utf8Slice(start, end); - } - return bufferSlice(buffer, start, end); - }, - sigSSHToASN1: (sig, type) => { - switch (type) { - case 'ssh-dss': { - if (sig.length > 40) - return sig; - // Change bare signature r and s values to ASN.1 BER values for OpenSSL - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - let r = sig.slice(0, 20); - let s = sig.slice(20); - if (r[0] & 0x80) { - const rNew = Buffer.allocUnsafe(21); - rNew[0] = 0x00; - r.copy(rNew, 1); - r = rNew; - } else if (r[0] === 0x00 && !(r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] & 0x80) { - const sNew = Buffer.allocUnsafe(21); - sNew[0] = 0x00; - s.copy(sNew, 1); - s = sNew; - } else if (s[0] === 0x00 && !(s[1] & 0x80)) { - s = s.slice(1); - } - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - utilBufferParser.init(sig, 0); - const r = utilBufferParser.readString(); - const s = utilBufferParser.readString(); - utilBufferParser.clear(); - if (r === undefined || s === undefined) - return; - - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - default: - return sig; - } - }, - convertSignature: (signature, keyType) => { - switch (keyType) { - case 'ssh-dss': { - if (signature.length <= 40) - return signature; - // This is a quick and dirty way to get from BER encoded r and s that - // OpenSSL gives us, to just the bare values back to back (40 bytes - // total) like OpenSSH (and possibly others) are expecting - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - let r = asnReader.readString(Ber.Integer, true); - let s = asnReader.readString(Ber.Integer, true); - let rOffset = 0; - let sOffset = 0; - if (r.length < 20) { - const rNew = Buffer.allocUnsafe(20); - rNew.set(r, 1); - r = rNew; - r[0] = 0; - } - if (s.length < 20) { - const sNew = Buffer.allocUnsafe(20); - sNew.set(s, 1); - s = sNew; - s[0] = 0; - } - if (r.length > 20 && r[0] === 0) - rOffset = 1; - if (s.length > 20 && s[0] === 0) - sOffset = 1; - const newSig = - Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); - bufferCopy(r, newSig, rOffset, r.length, 0); - bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); - return newSig; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - if (signature[0] === 0) - return signature; - // Convert SSH signature parameters to ASN.1 BER values for OpenSSL - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - const r = asnReader.readString(Ber.Integer, true); - const s = asnReader.readString(Ber.Integer, true); - if (r === null || s === null) - return; - const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); - writeUInt32BE(newSig, r.length, 0); - newSig.set(r, 4); - writeUInt32BE(newSig, s.length, 4 + r.length); - newSig.set(s, 4 + 4 + r.length); - return newSig; - } - } - - return signature; - }, - sendPacket: (proto, packet, bypass) => { - if (!bypass && proto._kexinit !== undefined) { - // We're currently in the middle of a handshake - - if (proto._queue === undefined) - proto._queue = []; - proto._queue.push(packet); - proto._debug && proto._debug('Outbound: ... packet queued'); - return false; - } - proto._cipher.encrypt(packet); - return true; - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/zlib.js b/reverse_engineering/node_modules/ssh2/lib/protocol/zlib.js deleted file mode 100644 index f68319a..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/zlib.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -const { kMaxLength } = require('buffer'); -const { - createInflate, - constants: { - DEFLATE, - INFLATE, - Z_DEFAULT_CHUNK, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_MEMLEVEL, - Z_DEFAULT_STRATEGY, - Z_DEFAULT_WINDOWBITS, - Z_PARTIAL_FLUSH, - } -} = require('zlib'); -const ZlibHandle = createInflate()._handle.constructor; - -function processCallback() { - throw new Error('Should not get here'); -} - -function zlibOnError(message, errno, code) { - const self = this._owner; - // There is no way to cleanly recover. - // Continuing only obscures problems. - - const error = new Error(message); - error.errno = errno; - error.code = code; - self._err = error; -} - -function _close(engine) { - // Caller may invoke .close after a zlib error (which will null _handle). - if (!engine._handle) - return; - - engine._handle.close(); - engine._handle = null; -} - -class Zlib { - constructor(mode) { - const windowBits = Z_DEFAULT_WINDOWBITS; - const level = Z_DEFAULT_COMPRESSION; - const memLevel = Z_DEFAULT_MEMLEVEL; - const strategy = Z_DEFAULT_STRATEGY; - const dictionary = undefined; - - this._err = undefined; - this._writeState = new Uint32Array(2); - this._chunkSize = Z_DEFAULT_CHUNK; - this._maxOutputLength = kMaxLength; - this._outBuffer = Buffer.allocUnsafe(this._chunkSize); - this._outOffset = 0; - - this._handle = new ZlibHandle(mode); - this._handle._owner = this; - this._handle.onerror = zlibOnError; - this._handle.init(windowBits, - level, - memLevel, - strategy, - this._writeState, - processCallback, - dictionary); - } - - writeSync(chunk, retChunks) { - const handle = this._handle; - if (!handle) - throw new Error('Invalid Zlib instance'); - - let availInBefore = chunk.length; - let availOutBefore = this._chunkSize - this._outOffset; - let inOff = 0; - let availOutAfter; - let availInAfter; - - let buffers; - let nread = 0; - const state = this._writeState; - let buffer = this._outBuffer; - let offset = this._outOffset; - const chunkSize = this._chunkSize; - - while (true) { - handle.writeSync(Z_PARTIAL_FLUSH, - chunk, // in - inOff, // in_off - availInBefore, // in_len - buffer, // out - offset, // out_off - availOutBefore); // out_len - if (this._err) - throw this._err; - - availOutAfter = state[0]; - availInAfter = state[1]; - - const inDelta = availInBefore - availInAfter; - const have = availOutBefore - availOutAfter; - - if (have > 0) { - const out = (offset === 0 && have === buffer.length - ? buffer - : buffer.slice(offset, offset + have)); - offset += have; - if (!buffers) - buffers = out; - else if (buffers.push === undefined) - buffers = [buffers, out]; - else - buffers.push(out); - nread += out.byteLength; - - if (nread > this._maxOutputLength) { - _close(this); - throw new Error( - `Output length exceeded maximum of ${this._maxOutputLength}` - ); - } - } else if (have !== 0) { - throw new Error('have should not go down'); - } - - // Exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || offset >= chunkSize) { - availOutBefore = chunkSize; - offset = 0; - buffer = Buffer.allocUnsafe(chunkSize); - } - - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += inDelta; - availInBefore = availInAfter; - } else { - break; - } - } - - this._outBuffer = buffer; - this._outOffset = offset; - - if (nread === 0) - buffers = Buffer.alloc(0); - - if (retChunks) { - buffers.totalLen = nread; - return buffers; - } - - if (buffers.push === undefined) - return buffers; - - const output = Buffer.allocUnsafe(nread); - for (let i = 0, p = 0; i < buffers.length; ++i) { - const buf = buffers[i]; - output.set(buf, p); - p += buf.length; - } - return output; - } -} - -class ZlibPacketWriter { - constructor(protocol) { - this.allocStart = 0; - this.allocStartKEX = 0; - this._protocol = protocol; - this._zlib = new Zlib(DEFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - alloc(payloadSize, force) { - return Buffer.allocUnsafe(payloadSize); - } - - finalize(payload, force) { - if (this._protocol._kexinit === undefined || force) { - const output = this._zlib.writeSync(payload, true); - const packet = this._protocol._cipher.allocPacket(output.totalLen); - if (output.push === undefined) { - packet.set(output, 5); - } else { - for (let i = 0, p = 5; i < output.length; ++i) { - const chunk = output[i]; - packet.set(chunk, p); - p += chunk.length; - } - } - return packet; - } - return payload; - } -} - -class PacketWriter { - constructor(protocol) { - this.allocStart = 5; - this.allocStartKEX = 5; - this._protocol = protocol; - } - - cleanup() {} - - alloc(payloadSize, force) { - if (this._protocol._kexinit === undefined || force) - return this._protocol._cipher.allocPacket(payloadSize); - return Buffer.allocUnsafe(payloadSize); - } - - finalize(packet, force) { - return packet; - } -} - -class ZlibPacketReader { - constructor() { - this._zlib = new Zlib(INFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - read(data) { - return this._zlib.writeSync(data, false); - } -} - -class PacketReader { - cleanup() {} - - read(data) { - return data; - } -} - -module.exports = { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/server.js b/reverse_engineering/node_modules/ssh2/lib/server.js deleted file mode 100644 index 11c15a1..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/server.js +++ /dev/null @@ -1,1363 +0,0 @@ -// TODO: -// * convert listenerCount() usage to emit() return value checking? -// * emit error when connection severed early (e.g. before handshake) -// * add '.connected' or similar property to connection objects to allow -// immediate connection status checking -'use strict'; - -const { Server: netServer } = require('net'); -const EventEmitter = require('events'); -const { listenerCount } = EventEmitter; - -const { - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = require('./protocol/constants.js'); -const { init: cryptoInit } = require('./protocol/crypto.js'); -const { KexInit } = require('./protocol/kex.js'); -const { parseKey } = require('./protocol/keyParser.js'); -const Protocol = require('./protocol/Protocol.js'); -const { SFTP } = require('./protocol/SFTP.js'); -const { writeUInt32BE } = require('./protocol/utils.js'); - -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = require('./Channel.js'); - -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = require('./utils.js'); - -const MAX_PENDING_AUTHS = 10; - -class AuthContext extends EventEmitter { - constructor(protocol, username, service, method, cb) { - super(); - - this.username = this.user = username; - this.service = service; - this.method = method; - this._initialResponse = false; - this._finalResponse = false; - this._multistep = false; - this._cbfinal = (allowed, methodsLeft, isPartial) => { - if (!this._finalResponse) { - this._finalResponse = true; - cb(this, allowed, methodsLeft, isPartial); - } - }; - this._protocol = protocol; - } - - accept() { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(true); - } - reject(methodsLeft, isPartial) { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(false, methodsLeft, isPartial); - } -} - - -class KeyboardAuthContext extends AuthContext { - constructor(protocol, username, service, method, submethods, cb) { - super(protocol, username, service, method, cb); - - this._multistep = true; - - this._cb = undefined; - this._onInfoResponse = (responses) => { - const callback = this._cb; - if (callback) { - this._cb = undefined; - callback(responses); - } - }; - this.submethods = submethods; - this.on('abort', () => { - this._cb && this._cb(new Error('Authentication request aborted')); - }); - } - - prompt(prompts, title, instructions, cb) { - if (!Array.isArray(prompts)) - prompts = [ prompts ]; - - if (typeof title === 'function') { - cb = title; - title = instructions = undefined; - } else if (typeof instructions === 'function') { - cb = instructions; - instructions = undefined; - } else if (typeof cb !== 'function') { - cb = undefined; - } - - for (let i = 0; i < prompts.length; ++i) { - if (typeof prompts[i] === 'string') { - prompts[i] = { - prompt: prompts[i], - echo: true - }; - } - } - - this._cb = cb; - this._initialResponse = true; - - this._protocol.authInfoReq(title, instructions, prompts); - } -} - -class PKAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - } - - accept() { - if (!this.signature) { - this._initialResponse = true; - this._protocol.authPKOK(this.key.algo, this.key.data); - } else { - AuthContext.prototype.accept.call(this); - } - } -} - -class HostbasedAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - this.localHostname = pkInfo.localHostname; - this.localUsername = pkInfo.localUsername; - } -} - -class PwdAuthContext extends AuthContext { - constructor(protocol, username, service, method, password, cb) { - super(protocol, username, service, method, cb); - - this.password = password; - this._changeCb = undefined; - } - - requestChange(prompt, cb) { - if (this._changeCb) - throw new Error('Change request already in progress'); - if (typeof prompt !== 'string') - throw new Error('prompt argument must be a string'); - if (typeof cb !== 'function') - throw new Error('Callback argument must be a function'); - this._changeCb = cb; - this._protocol.authPasswdChg(prompt); - } -} - - -class Session extends EventEmitter { - constructor(client, info, localChan) { - super(); - - this.type = 'session'; - this.subtype = undefined; - this._ending = false; - this._channel = undefined; - this._chanInfo = { - type: 'session', - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - } -} - - -class Server extends EventEmitter { - constructor(cfg, listener) { - super(); - - if (typeof cfg !== 'object' || cfg === null) - throw new Error('Missing configuration object'); - - const hostKeys = Object.create(null); - const hostKeyAlgoOrder = []; - - const hostKeys_ = cfg.hostKeys; - if (!Array.isArray(hostKeys_)) - throw new Error('hostKeys must be an array'); - - const cfgAlgos = ( - typeof cfg.algorithms === 'object' && cfg.algorithms !== null - ? cfg.algorithms - : {} - ); - - const hostKeyAlgos = generateAlgorithmList( - cfgAlgos.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - for (let i = 0; i < hostKeys_.length; ++i) { - let privateKey; - if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') - privateKey = parseKey(hostKeys_[i]); - else - privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); - - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - - if (privateKey.getPrivatePEM() === null) - throw new Error('privateKey value contains an invalid private key'); - - // Discard key if we already found a key of the same type - if (hostKeyAlgoOrder.includes(privateKey.type)) - continue; - - if (privateKey.type === 'ssh-rsa') { - // SSH supports multiple signature hashing algorithms for RSA, so we add - // the algorithms in the desired order - let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); - const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); - const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); - if (sha1Pos === -1) { - // Fall back to giving SHA1 the lowest priority - sha1Pos = Infinity; - } - [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { - if (pos === -1) - return; - - let type; - switch (pos) { - case sha1Pos: type = 'ssh-rsa'; break; - case sha256Pos: type = 'rsa-sha2-256'; break; - case sha512Pos: type = 'rsa-sha2-512'; break; - default: return; - } - - // Store same RSA key under each hash algorithm name for convenience - hostKeys[type] = privateKey; - - hostKeyAlgoOrder.push(type); - }); - } else { - hostKeys[privateKey.type] = privateKey; - hostKeyAlgoOrder.push(privateKey.type); - } - } - - const algorithms = { - kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX), - serverHostKey: hostKeyAlgoOrder, - cs: { - cipher: generateAlgorithmList( - cfgAlgos.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ), - mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), - compress: generateAlgorithmList( - cfgAlgos.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ), - lang: [], - }, - sc: undefined, - }; - algorithms.sc = algorithms.cs; - - if (typeof listener === 'function') - this.on('connection', listener); - - const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); - const offer = new KexInit(algorithms); - - this._srv = new netServer((socket) => { - if (this._connections >= this.maxConnections) { - socket.destroy(); - return; - } - ++this._connections; - socket.once('close', () => { - --this._connections; - }); - - let debug; - if (origDebug) { - // Prepend debug output with a unique identifier in case there are - // multiple clients connected at the same time - const debugPrefix = `[${process.hrtime().join('.')}] `; - debug = (msg) => { - origDebug(`${debugPrefix}${msg}`); - }; - } - - // eslint-disable-next-line no-use-before-define - new Client(socket, hostKeys, ident, offer, debug, this, cfg); - }).on('error', (err) => { - this.emit('error', err); - }).on('listening', () => { - this.emit('listening'); - }).on('close', () => { - this.emit('close'); - }); - this._connections = 0; - this.maxConnections = Infinity; - } - - injectSocket(socket) { - this._srv.emit('connection', socket); - } - - listen(...args) { - this._srv.listen(...args); - return this; - } - - address() { - return this._srv.address(); - } - - getConnections(cb) { - this._srv.getConnections(cb); - return this; - } - - close(cb) { - this._srv.close(cb); - return this; - } - - ref() { - this._srv.ref(); - return this; - } - - unref() { - this._srv.unref(); - return this; - } -} -Server.KEEPALIVE_CLIENT_INTERVAL = 15000; -Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; - - -class Client extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { - super(); - - let exchanges = 0; - let acceptedAuthSvc = false; - let pendingAuths = []; - let authCtx; - let kaTimer; - let onPacket; - const unsentGlobalRequestsReplies = []; - this._sock = socket; - this._chanMgr = new ChannelManager(this); - this._debug = debug; - this.noMoreSessions = false; - this.authenticated = false; - - // Silence pre-header errors - function onClientPreHeaderError(err) {} - this.on('error', onClientPreHeaderError); - - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from client: ${JSON.stringify(msg)}`); - }); - - const kaIntvl = ( - typeof srvCfg.keepaliveInterval === 'number' - && isFinite(srvCfg.keepaliveInterval) - && srvCfg.keepaliveInterval > 0 - ? srvCfg.keepaliveInterval - : ( - typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) - && Server.KEEPALIVE_CLIENT_INTERVAL > 0 - ? Server.KEEPALIVE_CLIENT_INTERVAL - : -1 - ) - ); - const kaCountMax = ( - typeof srvCfg.keepaliveCountMax === 'number' - && isFinite(srvCfg.keepaliveCountMax) - && srvCfg.keepaliveCountMax >= 0 - ? srvCfg.keepaliveCountMax - : ( - typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) - && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 - ? Server.KEEPALIVE_CLIENT_COUNT_MAX - : -1 - ) - ); - let kaCurCount = 0; - if (kaIntvl !== -1 && kaCountMax !== -1) { - this.once('ready', () => { - const onClose = () => { - clearInterval(kaTimer); - }; - this.on('close', onClose).on('end', onClose); - kaTimer = setInterval(() => { - if (++kaCurCount > kaCountMax) { - clearInterval(kaTimer); - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - this.end(); - } else { - // XXX: if the server ever starts sending real global requests to - // the client, we will need to add a dummy callback here to - // keep the correct reply order - proto.ping(); - } - }, kaIntvl); - }); - // TODO: re-verify keepalive behavior with OpenSSH - onPacket = () => { - kaTimer && kaTimer.refresh(); - kaCurCount = 0; - }; - } - - const proto = this._protocol = new Protocol({ - server: true, - hostKeys, - ident, - offer, - onPacket, - greeting: srvCfg.greeting, - banner: srvCfg.banner, - onWrite: (data) => { - if (isWritable(socket)) - socket.write(data); - }, - onError: (err) => { - if (!proto._destruct) - socket.removeAllListeners('data'); - this.emit('error', err); - try { - socket.end(); - } catch {} - }, - onHeader: (header) => { - this.removeListener('error', onClientPreHeaderError); - - const info = { - ip: socket.remoteAddress, - family: socket.remoteFamily, - port: socket.remotePort, - header, - }; - if (!server.emit('connection', this, info)) { - // auto reject - proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); - socket.end(); - return; - } - - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - if (++exchanges > 1) - this.emit('rekey'); - this.emit('handshake', negotiated); - }, - debug, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - socket.end(); - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from client - - // Do early reject in some cases to prevent wasteful channel - // allocation - if ((info.type === 'session' && this.noMoreSessions) - || !this.authenticated) { - const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - return proto.channelOpenFail(info.sender, reasonCode); - } - - let localChan = -1; - let reason; - let replied = false; - - let accept; - const reject = () => { - if (replied) - return; - replied = true; - - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - - proto.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = this._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug) { - debug('Automatic rejection of incoming channel open: ' - + 'no channels available'); - } - } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'session': - if (listenerCount(this, 'session') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const instance = new Session(this, info, localChan); - this._chanMgr.update(localChan, instance); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return instance; - }; - - this.emit('session', accept, reject); - return; - } - break; - case 'direct-tcpip': - if (listenerCount(this, 'tcpip') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; - }; - - this.emit('tcpip', accept, reject, data); - return; - } - break; - case 'direct-streamlocal@openssh.com': - if (listenerCount(this, 'openssh.streamlocal') - && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; - }; - - this.emit('openssh.streamlocal', accept, reject, data); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug) { - debug('Automatic rejection of unsupported incoming channel open' - + ` type: ${info.type}`); - } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug) { - debug('Automatic rejection of unexpected incoming channel open' - + ` for: ${info.type}`); - } - } - - reject(); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const chanInfo = { - type: channel.type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const instance = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - // NOOP -- should not be sent by client - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const session = this._chanMgr.get(recipient); - if (typeof session !== 'object' || session === null) - return; - - let replied = false; - let accept; - let reject; - - if (session.constructor !== Session) { - // normal Channel instance - if (wantReply) - proto.channelFailure(session.outgoing.id); - return; - } - - if (wantReply) { - // "real session" requests will have custom accept behaviors - if (type !== 'shell' - && type !== 'exec' - && type !== 'subsystem') { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelSuccess(session._chanInfo.outgoing.id); - }; - } - - reject = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelFailure(session._chanInfo.outgoing.id); - }; - } - - if (session._ending) { - reject && reject(); - return; - } - - switch (type) { - // "pre-real session start" requests - case 'env': - if (listenerCount(session, 'env')) { - session.emit('env', accept, reject, { - key: data.name, - val: data.value - }); - return; - } - break; - case 'pty-req': - if (listenerCount(session, 'pty')) { - session.emit('pty', accept, reject, data); - return; - } - break; - case 'window-change': - if (listenerCount(session, 'window-change')) - session.emit('window-change', accept, reject, data); - else - reject && reject(); - break; - case 'x11-req': - if (listenerCount(session, 'x11')) { - session.emit('x11', accept, reject, data); - return; - } - break; - // "post-real session start" requests - case 'signal': - if (listenerCount(session, 'signal')) { - session.emit('signal', accept, reject, { - name: data - }); - return; - } - break; - // XXX: is `auth-agent-req@openssh.com` really "post-real session - // start"? - case 'auth-agent-req@openssh.com': - if (listenerCount(session, 'auth-agent')) { - session.emit('auth-agent', accept, reject); - return; - } - break; - // "real session start" requests - case 'shell': - if (listenerCount(session, 'shell')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; - }; - - session.emit('shell', accept, reject); - return; - } - break; - case 'exec': - if (listenerCount(session, 'exec')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; - }; - - session.emit('exec', accept, reject, { - command: data - }); - return; - } - break; - case 'subsystem': { - let useSFTP = (data === 'sftp'); - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - let instance; - if (useSFTP) { - instance = new SFTP(this, session._chanInfo, { - server: true, - debug, - }); - } else { - instance = new Channel( - this, session._chanInfo, { server: true } - ); - instance.subtype = - session.subtype = `${type}:${data}`; - } - session._channel = instance; - - return instance; - }; - - if (data === 'sftp') { - if (listenerCount(session, 'sftp')) { - session.emit('sftp', accept, reject); - return; - } - useSFTP = false; - } - if (listenerCount(session, 'subsystem')) { - session.emit('subsystem', accept, reject, { - name: data - }); - return; - } - break; - } - } - debug && debug( - `Automatic rejection of incoming channel request: ${type}` - ); - reject && reject(); - }, - CHANNEL_EOF: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - if (!channel._ending) { - channel._ending = true; - channel.emit('eof'); - channel.emit('end'); - } - channel = channel._channel; - if (!channel) - return; - } - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel._ending = true; - channel.emit('close'); - channel = channel._channel; - if (!channel) - return; - } - - onCHANNEL_CLOSE(this, recipient, channel); - }, - // Begin service/auth-related ========================================== - SERVICE_REQUEST: (p, service) => { - if (exchanges === 0 - || acceptedAuthSvc - || this.authenticated - || service !== 'ssh-userauth') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - acceptedAuthSvc = true; - proto.serviceAccept(service); - }, - USERAUTH_REQUEST: (p, username, service, method, methodData) => { - if (exchanges === 0 - || this.authenticated - || (authCtx - && (authCtx.username !== username - || authCtx.service !== service)) - // TODO: support hostbased auth - || (method !== 'password' - && method !== 'publickey' - && method !== 'hostbased' - && method !== 'keyboard-interactive' - && method !== 'none') - || pendingAuths.length === MAX_PENDING_AUTHS) { - proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); - socket.end(); - return; - } else if (service !== 'ssh-connection') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - let ctx; - switch (method) { - case 'keyboard-interactive': - ctx = new KeyboardAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'publickey': - ctx = new PKAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'hostbased': - ctx = new HostbasedAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'password': - if (authCtx - && authCtx instanceof PwdAuthContext - && authCtx._changeCb) { - const cb = authCtx._changeCb; - authCtx._changeCb = undefined; - cb(methodData.newPassword); - return; - } - ctx = new PwdAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'none': - ctx = new AuthContext(proto, username, service, method, - onAuthDecide); - break; - } - - if (authCtx) { - if (!authCtx._initialResponse) { - return pendingAuths.push(ctx); - } else if (authCtx._multistep && !authCtx._finalResponse) { - // RFC 4252 says to silently abort the current auth request if a - // new auth request comes in before the final response from an - // auth method that requires additional request/response exchanges - // -- this means keyboard-interactive for now ... - authCtx._cleanup && authCtx._cleanup(); - authCtx.emit('abort'); - } - } - - authCtx = ctx; - - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - }, - USERAUTH_INFO_RESPONSE: (p, responses) => { - if (authCtx && authCtx instanceof KeyboardAuthContext) - authCtx._onInfoResponse(responses); - }, - // End service/auth-related ============================================ - GLOBAL_REQUEST: (p, name, wantReply, data) => { - const reply = { - type: null, - buf: null - }; - - function setReply(type, buf) { - reply.type = type; - reply.buf = buf; - sendReplies(); - } - - if (wantReply) - unsentGlobalRequestsReplies.push(reply); - - if ((name === 'tcpip-forward' - || name === 'cancel-tcpip-forward' - || name === 'no-more-sessions@openssh.com' - || name === 'streamlocal-forward@openssh.com' - || name === 'cancel-streamlocal-forward@openssh.com') - && listenerCount(this, 'request') - && this.authenticated) { - let accept; - let reject; - - if (wantReply) { - let replied = false; - accept = (chosenPort) => { - if (replied) - return; - replied = true; - let bufPort; - if (name === 'tcpip-forward' - && data.bindPort === 0 - && typeof chosenPort === 'number') { - bufPort = Buffer.allocUnsafe(4); - writeUInt32BE(bufPort, chosenPort, 0); - } - setReply('SUCCESS', bufPort); - }; - reject = () => { - if (replied) - return; - replied = true; - setReply('FAILURE'); - }; - } - - if (name === 'no-more-sessions@openssh.com') { - this.noMoreSessions = true; - accept && accept(); - return; - } - - this.emit('request', accept, reject, name, data); - } else if (wantReply) { - setReply('FAILURE'); - } - }, - }, - }); - - socket.pause(); - cryptoInit.then(() => { - socket.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - } - }); - socket.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - }); - socket.on('error', (err) => { - err.level = 'socket'; - this.emit('error', err); - }).once('end', () => { - debug && debug('Socket ended'); - proto.cleanup(); - this.emit('end'); - }).once('close', () => { - debug && debug('Socket closed'); - proto.cleanup(); - this.emit('close'); - - const err = new Error('No response from server'); - - // Simulate error for pending channels and close any open channels - this._chanMgr.cleanup(err); - }); - - const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { - if (authCtx === ctx && !this.authenticated) { - if (allowed) { - authCtx = undefined; - this.authenticated = true; - proto.authSuccess(); - pendingAuths = []; - this.emit('ready'); - } else { - proto.authFailure(methodsLeft, isPartial); - if (pendingAuths.length) { - authCtx = pendingAuths.pop(); - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - } - } - } - }; - - function sendReplies() { - while (unsentGlobalRequestsReplies.length > 0 - && unsentGlobalRequestsReplies[0].type) { - const reply = unsentGlobalRequestsReplies.shift(); - if (reply.type === 'SUCCESS') - proto.requestSuccess(reply.buf); - if (reply.type === 'FAILURE') - proto.requestFailure(); - } - } - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - - x11(originAddr, originPort, cb) { - const opts = { originAddr, originPort }; - openChannel(this, 'x11', opts, cb); - return this; - } - - forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { - const opts = { boundAddr, boundPort, remoteAddr, remotePort }; - openChannel(this, 'forwarded-tcpip', opts, cb); - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - const opts = { socketPath }; - openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); - return this; - } - - rekey(cb) { - let error; - - try { - this._protocol.rekey(); - } catch (ex) { - error = ex; - } - - // TODO: re-throw error if no callback? - - if (typeof cb === 'function') { - if (error) - process.nextTick(cb, error); - else - this.once('rekey', cb); - } - } -} - - -function openChannel(self, type, opts, cb) { - // Ask the client to open a channel for some purpose (e.g. a forwarded TCP - // connection) - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'forwarded-tcpip': - self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'x11': - self._protocol.x11(localChan, initWindow, maxPacket, opts); - break; - case 'forwarded-streamlocal@openssh.com': - self._protocol.openssh_forwardedStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} - -function compareNumbers(a, b) { - return a - b; -} - -module.exports = Server; -module.exports.IncomingClient = Client; diff --git a/reverse_engineering/node_modules/ssh2/lib/utils.js b/reverse_engineering/node_modules/ssh2/lib/utils.js deleted file mode 100644 index 04d4b96..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/utils.js +++ /dev/null @@ -1,332 +0,0 @@ -'use strict'; - -const { SFTP } = require('./protocol/SFTP.js'); - -const MAX_CHANNEL = 2 ** 32 - 1; - -function onChannelOpenFailure(self, recipient, info, cb) { - self._chanMgr.remove(recipient); - if (typeof cb !== 'function') - return; - - let err; - if (info instanceof Error) { - err = info; - } else if (typeof info === 'object' && info !== null) { - err = new Error(`(SSH) Channel open failure: ${info.description}`); - err.reason = info.reason; - } else { - err = new Error( - '(SSH) Channel open failure: server closed channel unexpectedly' - ); - err.reason = ''; - } - - cb(err); -} - -function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { - if (typeof channel === 'function') { - // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when - // requesting to open a channel - onChannelOpenFailure(self, recipient, err, channel); - return; - } - if (typeof channel !== 'object' - || channel === null - || channel.incoming.state === 'closed') { - return; - } - - channel.incoming.state = 'closed'; - - if (channel.readable) - channel.push(null); - if (channel.server) { - if (channel.stderr.writable) - channel.stderr.end(); - } else if (channel.stderr.readable) { - channel.stderr.push(null); - } - - if (channel.constructor !== SFTP - && (channel.outgoing.state === 'open' - || channel.outgoing.state === 'eof') - && !dead) { - channel.close(); - } - if (channel.outgoing.state === 'closing') - channel.outgoing.state = 'closed'; - - self._chanMgr.remove(recipient); - - const readState = channel._readableState; - const writeState = channel._writableState; - if (writeState && !writeState.ending && !writeState.finished && !dead) - channel.end(); - - // Take care of any outstanding channel requests - const chanCallbacks = channel._callbacks; - channel._callbacks = []; - for (let i = 0; i < chanCallbacks.length; ++i) - chanCallbacks[i](true); - - if (channel.server) { - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - channel.emit('close'); - } else { - channel.once('end', () => channel.emit('close')); - } - } else { - let doClose; - switch (channel.type) { - case 'direct-streamlocal@openssh.com': - case 'direct-tcpip': - doClose = () => channel.emit('close'); - break; - default: { - // Align more with node child processes, where the close event gets - // the same arguments as the exit event - const exit = channel._exit; - doClose = () => { - if (exit.code === null) - channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); - else - channel.emit('close', exit.code); - }; - } - } - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - doClose(); - } else { - channel.once('end', doClose); - } - - const errReadState = channel.stderr._readableState; - if (!channel.stderr.readable - || channel.stderr.destroyed - || (errReadState && errReadState.endEmitted)) { - channel.stderr.emit('close'); - } else { - channel.stderr.once('end', () => channel.stderr.emit('close')); - } - } -} - -class ChannelManager { - constructor(client) { - this._client = client; - this._channels = {}; - this._cur = -1; - this._count = 0; - } - add(val) { - // Attempt to reserve an id - - let id; - // Optimized paths - if (this._cur < MAX_CHANNEL) { - id = ++this._cur; - } else if (this._count === 0) { - // Revert and reset back to fast path once we no longer have any channels - // open - this._cur = 0; - id = 0; - } else { - // Slower lookup path - - // This path is triggered we have opened at least MAX_CHANNEL channels - // while having at least one channel open at any given time, so we have - // to search for a free id. - const channels = this._channels; - for (let i = 0; i < MAX_CHANNEL; ++i) { - if (channels[i] === undefined) { - id = i; - break; - } - } - } - - if (id === undefined) - return -1; - - this._channels[id] = (val || true); - ++this._count; - - return id; - } - update(id, val) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (val && this._channels[id]) - this._channels[id] = val; - } - get(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - return this._channels[id]; - } - remove(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (this._channels[id]) { - delete this._channels[id]; - if (this._count) - --this._count; - } - } - cleanup(err) { - const channels = this._channels; - this._channels = {}; - this._cur = -1; - this._count = 0; - - const chanIDs = Object.keys(channels); - const client = this._client; - for (let i = 0; i < chanIDs.length; ++i) { - const id = +chanIDs[i]; - const channel = channels[id]; - onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); - } - } -} - -const isRegExp = (() => { - const toString = Object.prototype.toString; - return (val) => toString.call(val) === '[object RegExp]'; -})(); - -function generateAlgorithmList(algoList, defaultList, supportedList) { - if (Array.isArray(algoList) && algoList.length > 0) { - // Exact list - for (let i = 0; i < algoList.length; ++i) { - if (supportedList.indexOf(algoList[i]) === -1) - throw new Error(`Unsupported algorithm: ${algoList[i]}`); - } - return algoList; - } - - if (typeof algoList === 'object' && algoList !== null) { - // Operations based on the default list - const keys = Object.keys(algoList); - let list = defaultList; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - let val = algoList[key]; - switch (key) { - case 'append': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const append = val[j]; - if (typeof append === 'string') { - if (!append || list.indexOf(append) !== -1) - continue; - if (supportedList.indexOf(append) === -1) - throw new Error(`Unsupported algorithm: ${append}`); - if (list === defaultList) - list = list.slice(); - list.push(append); - } else if (isRegExp(append)) { - for (let k = 0; k < supportedList.length; ++k) { - const algo = supportedList[k]; - if (append.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.push(algo); - } - } - } - } - } - break; - case 'prepend': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = val.length; j >= 0; --j) { - const prepend = val[j]; - if (typeof prepend === 'string') { - if (!prepend || list.indexOf(prepend) !== -1) - continue; - if (supportedList.indexOf(prepend) === -1) - throw new Error(`Unsupported algorithm: ${prepend}`); - if (list === defaultList) - list = list.slice(); - list.unshift(prepend); - } else if (isRegExp(prepend)) { - for (let k = supportedList.length; k >= 0; --k) { - const algo = supportedList[k]; - if (prepend.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.unshift(algo); - } - } - } - } - } - break; - case 'remove': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const search = val[j]; - if (typeof search === 'string') { - if (!search) - continue; - const idx = list.indexOf(search); - if (idx === -1) - continue; - if (list === defaultList) - list = list.slice(); - list.splice(idx, 1); - } else if (isRegExp(search)) { - for (let k = 0; k < list.length; ++k) { - if (search.test(list[k])) { - if (list === defaultList) - list = list.slice(); - list.splice(k, 1); - --k; - } - } - } - } - } - break; - } - } - - return list; - } - - return defaultList; -} - -module.exports = { - ChannelManager, - generateAlgorithmList, - onChannelOpenFailure, - onCHANNEL_CLOSE, - isWritable: (stream) => { - // XXX: hack to workaround regression in node - // See: https://github.com/nodejs/node/issues/36029 - return (stream - && stream.writable - && stream._readableState - && stream._readableState.ended === false); - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/package.json b/reverse_engineering/node_modules/ssh2/package.json deleted file mode 100644 index 1fd1f7e..0000000 --- a/reverse_engineering/node_modules/ssh2/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "ssh2", - "version": "1.4.0", - "author": "Brian White ", - "description": "SSH2 client and server modules written in pure JavaScript for node.js", - "main": "./lib/index.js", - "engines": { - "node": ">=10.16.0" - }, - "dependencies": { - "asn1": "^0.2.4", - "bcrypt-pbkdf": "^1.0.2" - }, - "devDependencies": { - "@mscdex/eslint-config": "^1.0.0", - "eslint": "^7.0.0" - }, - "optionalDependencies": { - "cpu-features": "0.0.2", - "nan": "^2.15.0" - }, - "scripts": { - "install": "node install.js", - "rebuild": "node install.js", - "test": "node test/test.js", - "lint": "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js examples lib test", - "lint:fix": "npm run lint -- --fix" - }, - "keywords": [ - "ssh", - "ssh2", - "sftp", - "secure", - "shell", - "exec", - "remote", - "client" - ], - "licenses": [ - { - "type": "MIT", - "url": "http://github.com/mscdex/ssh2/raw/master/LICENSE" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/mscdex/ssh2.git" - } -} diff --git a/reverse_engineering/node_modules/ssh2/test/common.js b/reverse_engineering/node_modules/ssh2/test/common.js deleted file mode 100644 index a531924..0000000 --- a/reverse_engineering/node_modules/ssh2/test/common.js +++ /dev/null @@ -1,316 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { readFileSync } = require('fs'); -const { join } = require('path'); -const { inspect } = require('util'); - -const Client = require('../lib/client.js'); -const Server = require('../lib/server.js'); -const { parseKey } = require('../lib/protocol/keyParser.js'); - -const mustCallChecks = []; - -const DEFAULT_TEST_TIMEOUT = 30 * 1000; - -function noop() {} - -function runCallChecks(exitCode) { - if (exitCode !== 0) return; - - const failed = mustCallChecks.filter((context) => { - if ('minimum' in context) { - context.messageSegment = `at least ${context.minimum}`; - return context.actual < context.minimum; - } - context.messageSegment = `exactly ${context.exact}`; - return context.actual !== context.exact; - }); - - failed.forEach((context) => { - console.error('Mismatched %s function calls. Expected %s, actual %d.', - context.name, - context.messageSegment, - context.actual); - console.error(context.stack.split('\n').slice(2).join('\n')); - }); - - if (failed.length) - process.exit(1); -} - -function mustCall(fn, exact) { - return _mustCallInner(fn, exact, 'exact'); -} - -function mustCallAtLeast(fn, minimum) { - return _mustCallInner(fn, minimum, 'minimum'); -} - -function _mustCallInner(fn, criteria = 1, field) { - if (process._exiting) - throw new Error('Cannot use common.mustCall*() in process exit handler'); - - if (typeof fn === 'number') { - criteria = fn; - fn = noop; - } else if (fn === undefined) { - fn = noop; - } - - if (typeof criteria !== 'number') - throw new TypeError(`Invalid ${field} value: ${criteria}`); - - const context = { - [field]: criteria, - actual: 0, - stack: inspect(new Error()), - name: fn.name || '' - }; - - // Add the exit listener only once to avoid listener leak warnings - if (mustCallChecks.length === 0) - process.on('exit', runCallChecks); - - mustCallChecks.push(context); - - function wrapped(...args) { - ++context.actual; - return fn.call(this, ...args); - } - // TODO: remove origFn? - wrapped.origFn = fn; - - return wrapped; -} - -function getCallSite(top) { - const originalStackFormatter = Error.prepareStackTrace; - Error.prepareStackTrace = (err, stack) => - `${stack[0].getFileName()}:${stack[0].getLineNumber()}`; - const err = new Error(); - Error.captureStackTrace(err, top); - // With the V8 Error API, the stack is not formatted until it is accessed - // eslint-disable-next-line no-unused-expressions - err.stack; - Error.prepareStackTrace = originalStackFormatter; - return err.stack; -} - -function mustNotCall(msg) { - const callSite = getCallSite(mustNotCall); - return function mustNotCall(...args) { - args = args.map(inspect).join(', '); - const argsInfo = (args.length > 0 - ? `\ncalled with arguments: ${args}` - : ''); - assert.fail( - `${msg || 'function should not have been called'} at ${callSite}` - + argsInfo); - }; -} - -function setup(title, configs) { - const { - client: clientCfg_, - server: serverCfg_, - allReady: allReady_, - timeout: timeout_, - debug, - noForceClientReady, - noForceServerReady, - noClientError, - noServerError, - } = configs; - - // Make shallow copies of client/server configs to avoid mutating them when - // multiple tests share the same config object reference - let clientCfg; - if (clientCfg_) - clientCfg = { ...clientCfg_ }; - let serverCfg; - if (serverCfg_) - serverCfg = { ...serverCfg_ }; - - let clientClose = false; - let clientReady = false; - let serverClose = false; - let serverReady = false; - const msg = (text) => { - return `${title}: ${text}`; - }; - - const timeout = (typeof timeout_ === 'number' - ? timeout_ - : DEFAULT_TEST_TIMEOUT); - - const allReady = (typeof allReady_ === 'function' ? allReady_ : undefined); - - if (debug) { - if (clientCfg) { - clientCfg.debug = (...args) => { - console.log(`[${title}][CLIENT]`, ...args); - }; - } - if (serverCfg) { - serverCfg.debug = (...args) => { - console.log(`[${title}][SERVER]`, ...args); - }; - } - } - - let timer; - let client; - let clientReadyFn; - let server; - let serverReadyFn; - if (clientCfg) { - client = new Client(); - if (!noClientError) - client.on('error', onError); - clientReadyFn = (noForceClientReady ? onReady : mustCall(onReady)); - client.on('ready', clientReadyFn) - .on('close', mustCall(onClose)); - } else { - clientReady = clientClose = true; - } - - if (serverCfg) { - server = new Server(serverCfg); - if (!noServerError) - server.on('error', onError); - serverReadyFn = (noForceServerReady ? onReady : mustCall(onReady)); - server.on('connection', mustCall((conn) => { - if (!noServerError) - conn.on('error', onError); - conn.on('ready', serverReadyFn); - server.close(); - })).on('close', mustCall(onClose)); - } else { - serverReady = serverClose = true; - } - - function onError(err) { - const which = (this === client ? 'client' : 'server'); - assert(false, msg(`Unexpected ${which} error: ${err.stack}\n`)); - } - - function onReady() { - if (this === client) { - assert(!clientReady, - msg('Received multiple ready events for client')); - clientReady = true; - } else { - assert(!serverReady, - msg('Received multiple ready events for server')); - serverReady = true; - } - clientReady && serverReady && allReady && allReady(); - } - - function onClose() { - if (this === client) { - assert(!clientClose, - msg('Received multiple close events for client')); - clientClose = true; - } else { - assert(!serverClose, - msg('Received multiple close events for server')); - serverClose = true; - } - if (clientClose && serverClose) - clearTimeout(timer); - } - - process.nextTick(mustCall(() => { - function connectClient() { - if (clientCfg.sock) { - clientCfg.sock.connect(server.address().port, 'localhost'); - } else { - clientCfg.host = 'localhost'; - clientCfg.port = server.address().port; - } - try { - client.connect(clientCfg); - } catch (ex) { - ex.message = msg(ex.message); - throw ex; - } - } - - if (server) { - server.listen(0, 'localhost', mustCall(() => { - if (timeout >= 0) { - timer = setTimeout(() => { - assert(false, msg('Test timed out')); - }, timeout); - } - if (client) - connectClient(); - })); - } - })); - - return { client, server }; -} - -const FIXTURES_DIR = join(__dirname, 'fixtures'); -const fixture = (() => { - const cache = new Map(); - return (file) => { - const existing = cache.get(file); - if (existing !== undefined) - return existing; - - const result = readFileSync(join(FIXTURES_DIR, file)); - cache.set(file, result); - return result; - }; -})(); -const fixtureKey = (() => { - const cache = new Map(); - return (file, passphrase, bypass) => { - if (typeof passphrase === 'boolean') { - bypass = passphrase; - passphrase = undefined; - } - if (typeof bypass !== 'boolean' || !bypass) { - const existing = cache.get(file); - if (existing !== undefined) - return existing; - } - const fullPath = join(FIXTURES_DIR, file); - const raw = fixture(file); - let key = parseKey(raw, passphrase); - if (Array.isArray(key)) - key = key[0]; - const result = { key, raw, fullPath }; - cache.set(file, result); - return result; - }; -})(); - -function setupSimple(debug, title) { - const { client, server } = setup(title, { - client: { username: 'Password User', password: '12345' }, - server: { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }, - debug, - }); - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })); - })); - return { client, server }; -} - -module.exports = { - fixture, - fixtureKey, - FIXTURES_DIR, - mustCall, - mustCallAtLeast, - mustNotCall, - setup, - setupSimple, -}; diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/bad_rsa_private_key b/reverse_engineering/node_modules/ssh2/test/fixtures/bad_rsa_private_key deleted file mode 100644 index 80fdc87..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/bad_rsa_private_key +++ /dev/null @@ -1,26 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEAz7MF4vhgw6HxNf3KtVf3VULTYgrRSlv+cCZdB1xxI1p/nGyu -/eekUn5C+mGeDS488DX5ulzicxVpL7pamc/tFNcp91MrR7PiIMK2l+bwbZJubbLj -DH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SCqILpOfMvbo57g+ipu7ufDlA/ -7rIFiUDvaVap7j909W+8egsCgYEAsuc/0DBixMmSyHl7QwRcmkC15HVSu32RVIOb -ub01KAtmaH1EWJAMTCW64/mggOtjgI0kgeE/BSFVhsqo7eOdkhEj0db27OxbroRU -zF1xdrpYtRRO7D6a4iLgm3OzuQS72+tASo8pFqDUxG6sq8NAvLOgRJE4ioSoT07w -KvAgXRkCgYEAmWgcsX/BdNcKOteSDtPkys5NRtWCBz7Coxb+xXXoXz1FVegBolpY -wXVePvXTIbU8VJOLunMyH5wpmMUiJbTX9v2o/yfpsH0ci4GaAeVtqpA= ------END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/https_cert.pem b/reverse_engineering/node_modules/ssh2/test/fixtures/https_cert.pem deleted file mode 100644 index 49e1045..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/https_cert.pem +++ /dev/null @@ -1,33 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIFuzCCA6OgAwIBAgIUPtNIRfp8v8RsObCr+9LVosWVD/QwDQYJKoZIhvcNAQEL -BQAwbTELMAkGA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxEjAQBgNVBAcM -CVNvbWUtQ2l0eTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRIw -EAYDVQQDDAlsb2NhbGhvc3QwHhcNMjAxMjIwMDQwNTM1WhcNMzAxMjE4MDQwNTM1 -WjBtMQswCQYDVQQGEwJVUzETMBEGA1UECAwKU29tZS1TdGF0ZTESMBAGA1UEBwwJ -U29tZS1DaXR5MSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQ -BgNVBAMMCWxvY2FsaG9zdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB -AJ/m96/mBMFoUWUOFSvvmJjHj/XxnO89ClCcCIFA6bJNCJMFZV3m853HAhP9g3kF -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nE7HUUqKMAxAf++vmYicDTSv6rsEONxmG9cn0SQWzUnr3G6zZ4uxF -9wlvl5/VN6jT9XtS9rpZfwOVLigmuhMFkUCxTTN0eHOh0u76QSk2nphxumIj1vc+ -I9G/KNk0R3G+7AyjDK2WIxaqUTChpBfytQoiiQCOYEL+KlJboWhYL7mfeBT2flzH -H3/LfF61Y8V2H5pjX1x+e/FghA5OFiHsrgoJVegVYu6v0JyCzNwGaSvnpu8QZcOZ -lT6d4UKS8JmIuq2w7iru6cURBRzMfBZ4qaX3Gm/NSDfi6q/8aL/mogzQHg91lrFz -AXZUkb+WGikJ6TEgL9M4qBHwgssk7ayEejBhIuLxQD654Py8P8diEt/77iY0qsS9 -EEw/onPXr9nLLeIcigQEa2+14msAb2I7a2/RhlUW+Q== ------END CERTIFICATE----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/https_key.pem b/reverse_engineering/node_modules/ssh2/test/fixtures/https_key.pem deleted file mode 100644 index 3be6a97..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/https_key.pem +++ /dev/null @@ -1,52 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQCf5vev5gTBaFFl -DhUr75iYx4/18ZzvPQpQnAiBQOmyTQiTBWVd5vOdxwIT/YN5BTN4S9HPehikuSLE -SYjVDKyFGK1gj4dclCQjX3M8hmwSTXBKEYX6grrs4wOVO4wIpY6i1gT/mSNLSkbk -F1+Gwx6edagxErHMTR2UKdPi4aPOsuF42T509TmHea5dw+g/NgBJTqxjrbI+yph5 -d3mIUKCjQ5QhmuWSvi9Oa7ApVOZvy18hpn+ULTiBdNCaieykuJl92RflxP/t4JFy -ycjgjmBQy4xmO1o7CV891puqZLVvDRqoTGmkXyCDarQkJA4DJIE4xd07RAPzNg7B -lNnnS96pv4m0OM/PHTFZCxmeg1mYOaBsGUdFvI0QGroVjtNUKiUixd0Yb4+FWrBe -B4+rCNh0HIB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u/k -x3OPbh/LUsvVwhhl/CDoobBJc2RsJVG3GgdXu+T+rGfZa/u9ZQ4yFlNcKqWCxzHK -8+c6hypNuWcDZqjSO5KlGW3lmzJs8k4vBM7hvkL6KWoKOM8OaSvNRmmu8E53LjzX -qq0RMsGugP42DtDbTDKqd6qSpFi6ULsh9zBCtwL6OwMrEhRwp/hn3prdKC4f4ilF -Aewcq6bsEBk9DiBWT1oir1KA3FM8euLJEJNe0WUx7r85Cc1eJDWkLR+08QPQKP3T -sCllRwKCAQBQgSFFI65dlLJf/iJrZPuP3sCzZNABe4y7lxZK2Gij4FXzf2KA1SAl -dyxuUU+Hv98l52pJIWmoNYWKEXOorsu+TuadgiK11DSx/ajQ9y8OEbscOVTJwrv3 -aVbaz4f0z2AKRLrBLsln2aVLQVPF5dsPNmsYIUWOrvBJ+DFFeXQG+QWimS2VbS+P -wrDdpVej8sEaUVfCqvCAx8gWtrFtE401BmfNla1xFGHiHhcLrsqKj3uxIojQ0Met -fFCrKqxES0OQ6pY/9VlrBmfihw/Bt1LWMPUo90atFArbwGaUxXLwi4FwRafkW5Di -k77w3OGObcFv4zxCOoFxcXXc3MCyw3r8 ------END PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_dsa b/reverse_engineering/node_modules/ssh2/test/fixtures/id_dsa deleted file mode 100644 index d9c9b5b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_dsa +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -MIIBuwIBAAKBgQC3/2VIGHgqHuxvhPa6rryqqLy6sQmjeSIwyrIW5F/o8W4sz/mE -0noDSW4PaoXjgPQv5egj1EByws6dMOUqLaZHNWNn+Lh/jkKlwKyhbSCAjqoWH3v3 -uI1j58GO/eZ2+REijfyA0XJxdm7kqEexxbg0UpFr1F/eLBUxpLIbhhS1cwIVAKcB -B9DnAObuPJGTwYTCaIIBQDy9AoGAJicW0pIFwgoTYsIeywmUQopJ3FQ4M3eDwQ0U -T33pzWvBZFN2OsUDTFg64PNm9ow09wk042qMg168eKCUTp2iR/Y9R4xTj8dls8iv -aMGMZ/B32eURIjUREGiXYTyG1pfuB2znSvr/5pavhuz5yG9M0AJCiYiexdaQKO3N -oJp6T3ACgYEAsep79p4WljnawrJc928zGq6dLYjs+5apYhqx4vf2l3Z2u26VqVNG -i5zZkUzhWQYV3/qtEOpO43dyZTHW+d9L8ni6HbXFWRVx60WE+5WKkzkimHJ6gox2 -kDvOqPudiS34KJOCEYYLEnJmK8aUZBZzWFORXkN8QgA/h9ts8AU785UCFAVXZMWq -CteWCH2HzcY2x/65dMwL ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_ecdsa b/reverse_engineering/node_modules/ssh2/test/fixtures/id_ecdsa deleted file mode 100644 index 036e3b6..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_ecdsa +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIPMZuWP7fMsZeyC1XXVUALVebJOX7PTwmsPql9qG25SeoAoGCCqGSM49 -AwEHoUQDQgAEB/B6mC5lrekKPWfGEkKpnCk08+dRnzFUg2jUHpaIrOTt4jGdvq6T -yAN57asB+PYmFyVIpi35NcmicF18qX3ayg== ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa deleted file mode 100644 index 90a6f72..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXQIBAAKBgQDL0yFO4W4xbdrJk/i+CW3itPATvhRkS+x+gKmkdH739AqWYP6r -kTFAmFTw9gLJ/c2tN7ow0T0QUR9iUsv/3QzTuwsjBu0feo3CVxwMkaJTo5ks9XBo -OW0R3tyCcOLlAcQ1WjC7cv5Ifn4gXLLM+k8/y/m3u8ERtidNxbRqpQ/gPQIDAQAB -AoGABirSRC/ABNDdIOJQUXe5knWFGiPTPCGr+zvrZiV8PgZtV5WBvzE6e0jgsRXQ -icobMhWQla+PGHJL786vi4NlwuhwKcF7Pd908ofej1eeBOd1u/HQ/qsfxPdxI0zF -dcWPYgAOo9ydOMGcSx4v1zDIgFInELJzKbv64LJQD0/xhoUCQQD7KhJ7M8Nkwsr2 -iKCyWTFM2M8/VKltgaiSmsNKZETashk5tKOrM3EWX4RcB/DnvHe8VNyYpC6Sd1uQ -AHwPDfxDAkEAz7+7hDybH6Cfvmr8kUOlDXiJJWXp5lP37FLzMDU6a9wTKZFnh57F -e91zRmKlQTegFet93MXaFYljRkI+4lMpfwJBAPPLbNEF973Qjq4rBMDZbs9HDDRO -+35+AqD7dGC7X1Jg2bd3rf66GiU7ZgDm/GIUQK0gOlg31bT6AniO39zFGH0CQFBh -Yd9HR8nT7xrQ8EoQPzNYGNBUf0xz3rAcZCWZ4rHK48sojEMoBkbnputrzX7PU+xH -QlqCXuAIWVXc2dHd1WcCQQDIUJHPOsgeAfTLoRRRURp/m8zZ9IpbaPTyDstPVNYe -zARW3Oa/tzPqdO6NWaetCp17u7Kb6X9np7Vz17i/4KED ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa.ppk b/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa.ppk deleted file mode 100644 index 4504f18..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa.ppk +++ /dev/null @@ -1,26 +0,0 @@ -PuTTY-User-Key-File-2: ssh-rsa -Encryption: none -Comment: rsa-key-20150522 -Public-Lines: 6 -AAAAB3NzaC1yc2EAAAABJQAAAQB1quqP0rhl78NOLD4lj+1x5FGAqZ3aqo6GiEPz -KOaQmy86FuJMK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47YrynCOcJEEnpqvbArc8M -xMWuUnTUMrjvokGDOBBiQu4UAE4bybpgXkNHJf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fFIqCa0+n1D6RzvDqs1QIu+PGSp0K6vHOOS5fP0ZpuT025E= -Private-MAC: 4ca26008c85b901f4d2766b0924c25e527678d7e diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa_enc deleted file mode 100644 index 75a1e95..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa_enc +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,CCE70744FB28F2EFB1D74377281A780C - -1WiGnqpSGXFIg+WYr7T2XN72C1YrNQ1jmRISb32TB/Rh2Zo47fjyQnv9impz8b6m -91R/qF7uCLI0fswvT5oqwn1L0vUAA0YtW/E2IQJEx5GPiaexoDJYYfu2yy036Kca -e9VtCajgrV+kycg1CknCxQKMcKXNq8Czvq66PM4Bzknek5hhdmxHxOl0QAE+8EXt -pnasOGz3szTUKkD6givwWgvDXY3BnVG46fXff99Xqgb6fx5IDbAkVKaxWIN/c81E -b0rcfyoLb7yjPgNYn9vUI6Z+24NMYUYARzb3dG5geaeX0BYb/VlCtJUsP0Rp2P2P -jl+cdvBKaeOvA9gPo/jAtSOFexQRs7AzKzoOLYU1fokd8HhqxOKAljn9ujmEqif7 -qcimk2s7ff6tSSlxtRzDP+Uq9d1u5tyaONRV2lwj+GdP1gRoOmdZL5chdvoAi0I8 -5eMf58hEuN2d4h4FryO6z7K+XQ9oo6/N/xHU0U/t2Pco9oY2L6oWMDxKwbfPhaD5 -CcoEElsK4XFArYDielEq9Y1sXaEuwR5I0ksDDsANp74r9Bhcqz60gJa6hVz0ouEU -QA67wV9+TRmulKRxwANvqxQwqPuxqcTPeJjXSUN/ZCaDwYmI+d1poxMx2fQzT82M -onlgOWq+3HbCotyoeFpCameymwDQzmrYdMBr7oWLgnOrxmJ89zDc6+jkHFgQJvnU -atyeVDqe866ZvvIGWS+r/EsDjV3cTW/cJvdsC+5BpnoXoVF4LqxE3LFbEbQBvqio -4enCZpspQSMOJra37vSofbD+DyI5Wd+y8SBmfDLjyDFhT0spW9aN99uFqSc3UElA -SAmnFmpYBFEQrRGpvpu5sC0c/YjZeRXr0/F1xPpIT1SWzpRsbcsWRBDzWjLOKWQx -8ytwc2QS7eKedfqkPWpYKW0Qtps+XgnGWA6PBX42IYhLsKANRfhFXQv5LPqLNNOn -3EsG9pd+0dBpfxFQfyyAKAUuvpJNgJ6kNx8VSj8Ppj8lyUdGa9YucgB02m7gHC9U -A4YyJsIcjo6IcrjM+ez1govRRS0nE8AUb8ups9tn8mdBwqcPCrgcJhV7JkOYNJYh -NAh0vgmneOq8LSVs2SRaL3uuLNbjh1LR9iViwbIY8kMQXkiXa2/V+PFwt5oqeX5f -2x3yzCeGBiQW10InyBBnKutbPD85R4YJhQ55bOMDSFfGGqwOU1QURiO1NUzf9n/2 -+E8VE7J/IQoO0TrJpC+EV0ROKME9W6+AvEFdmdIigbq3bkdEgSixyLnrhV8V8T4N -nbKlLoqfXt8DmT+h8XPzgsu0Fq/PNi6xBaiUsaN9tK6OP2ZVjr9ihbeLTI0rcKDr -XX2cWPvTcboRLt+S4wmqchMf7Kxa2PfX5Tf+KCcdZNQO4YqS23wQZgk61kuOQCsS -uOop+ICI7yWZkjqCOzGOeHLl/7FyFeprsFDIwD1g20y9bzibbJlbQPhwXSalqDQT -MWLH3rdFuvgLH7ujtjxSakES+VzkOhbnmb/Wypbl1D7P7GT2seau16EEGQDhDzcJ -Q4d/BjR2WqqxmC79MOAvUWAu6fZQjPD30/gYPGpMaEuiLrDlzDqvf+oi4A9+EtRL ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa deleted file mode 100644 index a8722ab..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +++ /dev/null @@ -1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ZSHcNj+Ur+AiFErtY -PRwMAAAACALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP -8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYW -wIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0AAAAVAIoWASGAfFqckLwvtPRNCzow -TTl1AAAAEm5ldyBvcGVuc3NoIGZvcm1hdAECAwQFBgc= ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub deleted file mode 100644 index d5b662d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8KqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUDl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZLmrQwZqHNeE2RAAAAFQCfUBJFJFwhWxaqutm5sVCrilQ6UwAAAIEAtwohEtO1gbn43+/MRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2CB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVDz1aALZSHcNj+Ur+AiFErtYPRwMAAAACALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0= new openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result deleted file mode 100644 index 7b8d66e..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASwGByqGSM44BAEwggEfAoGBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8K\nqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUD\nl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZL\nmrQwZqHNeE2RAhUAn1ASRSRcIVsWqrrZubFQq4pUOlMCgYEAtwohEtO1gbn43+/M\nRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2C\nB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVD\nz1aALZSHcNj+Ur+AiFErtYPRwMADgYQAAoGALzzZZQQSKDjwNXKNs2LXF/ysay/L\nKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PK\nBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnse\noNpPVbsBKDaylP0=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8KqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUDl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZLmrQwZqHNeE2RAAAAFQCfUBJFJFwhWxaqutm5sVCrilQ6UwAAAIEAtwohEtO1gbn43+/MRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2CB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVDz1aALZSHcNj+Ur+AiFErtYPRwMAAAACALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result deleted file mode 100644 index 0d93248..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASwGByqGSM44BAEwggEfAoGBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8K\nqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUD\nl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZL\nmrQwZqHNeE2RAhUAn1ASRSRcIVsWqrrZubFQq4pUOlMCgYEAtwohEtO1gbn43+/M\nRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2C\nB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVD\nz1aALZSHcNj+Ur+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LTtYG5+N/vzEULdsXSGToDRth6X5Yj\nb7c0UotAmy9VGrnmN5IO+//1em2USHeSoO+5shRq92zdggdQwNaXXzU301huIETz\ntfRwGHOfUGZbzJmIqdzLhdziFhneAzaNzVeUFyIqvWL1Q89WgC2Uh3DY/lK/gIhR\nK7WD0cDAAoGALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAop\nTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3V\nyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0CFQCKFgEh\ngHxanJC8L7T0TQs6ME05dQ==\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc deleted file mode 100644 index 392f214..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABBgJ5gXYn -/2IFE2+CrAxYR8AAAAEAAAAAEAAAGxAAAAB3NzaC1kc3MAAACBAPKhVnFGWb0KLibdYnJz -0RwFy/mt98KMIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0 -w+ZYfVHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vy -k1bw7ske+ImLAAAAFQDnXsk6hdenasLyE8ylLHSE+0XR3QAAAIBsMerhmMT0/416hJV/pr -s7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/IjU62Sz6n -/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK6eRJfrZuaq0Yue -nUa9AuFwnjPAAAAIBwjDUjp9jaJu46eobNK8CWJL/Noi2fXTtFZFgUFRwkr/FXLLsOckQT -mYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuCx6dIgiOf2gRClQU5OlqhrnMW2BQXlR -hBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/C2XBGgEuRdgyqQAAAgDIGP0oYyi7sTk0HdU9 -uWZLaDhHpW4Z8xTzfgUDbxoTYQ2igO90O32vSqW/cC2QKWTFuPCFnsCerHAIGzX/eyxlCQ -VyNa7VrhbNjIKAHBF3XMcRVRbW2SdYq8tHSkeZHr5EuO5dRfJ7wsR8flkPb4O4viNlIbvF -Ake8dsZEOhcnVNiv+NMR9mTq8l91wR60tr3XiWzCMkEYrJiWOfQuZSvzYi7dUmFxQuEZfQ -vIPkZD3L6XdaAz/r6YAONFAbtUMAOaUxOGV9puSsunSosAvmi+NcJ9iUM2FpAu561gp+Tv -RRcgXHxLGuzTNASiMaTN3M+HenqUh3RWmWauL5wSR7DbrH7Vq47YTnVjtg8xcZnMCfOx2D -Wz775hD6uyLwbkxKMaNMf8p4sOcXsSpHNqKmfkUxQBpNRp6Vg5W+AVaAkyXQng2LRt6txJ -Xv5zBiSFdsobkrWko/ONfGKfG+zVP+LIVcghLpp71GZQX6Ci02vB55pvk8k0G91H3INn/c -t6Q5zY5pK9VZwxjZ29psm7V+FdeD1g8VQ1Rp9muq6zDXHKKyqkBK/oGCM9UhBHFjki0gBR -v6LY/iXsz/eG14svhLjM5zYFSX7jUOI9b/PnhhL7Mos4wguHN2EjfGWuC07PkkqDPoqSwn -cC91OKhub6yqZsqvBz9BcV+2FxVNPNKzRdzA== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub deleted file mode 100644 index c2b1190..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KMIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfVHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vyk1bw7ske+ImLAAAAFQDnXsk6hdenasLyE8ylLHSE+0XR3QAAAIBsMerhmMT0/416hJV/prs7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/IjU62Sz6n/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK6eRJfrZuaq0YuenUa9AuFwnjPAAAAIBwjDUjp9jaJu46eobNK8CWJL/Noi2fXTtFZFgUFRwkr/FXLLsOckQTmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuCx6dIgiOf2gRClQU5OlqhrnMW2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/C2XBGgEuRdgyqQ== diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result deleted file mode 100644 index d15133a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtjCCASsGByqGSM44BAEwggEeAoGBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KM\nIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfV\n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yqQ==", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result deleted file mode 100644 index 2271c47..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format encrypted", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtjCCASsGByqGSM44BAEwggEeAoGBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KM\nIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfV\nHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vy\nk1bw7ske+ImLAhUA517JOoXXp2rC8hPMpSx0hPtF0d0CgYBsMerhmMT0/416hJV/\nprs7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/I\njU62Sz6n/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK\n6eRJfrZuaq0YuenUa9AuFwnjPAOBhAACgYBwjDUjp9jaJu46eobNK8CWJL/Noi2f\nXTtFZFgUFRwkr/FXLLsOckQTmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuC\nx6dIgiOf2gRClQU5OlqhrnMW2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/\nC2XBGgEuRdgyqQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KMIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfVHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2Ps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ATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm deleted file mode 100644 index 38566b4..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAAFmFlczEyOC1nY21Ab3BlbnNzaC5jb20AAAAGYmNyeXB0AA -AAGAAAABD01pNY1+DTCAHuI6mcjB0YAAAAEAAAAAEAAAGyAAAAB3NzaC1kc3MAAACBAPLA -N0jFExSJiCvw7p2W2v5tqvXIG4YwCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJ -iP98Vz0XTHIW6DpkE9DcC5GGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79s -ZPOEg/bMExWJlB5AosJr7v5twVftAAAAFQC5AGsioHKAc2Cd2QwKLUZSmDZAVwAAAIBxYf -EThMIXPQkSer3snKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrL -OnIbqU1XApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/q -MsMu2RSKkK6f08J0vsESnKU4nmnwAAAIEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pS -UiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjL -qLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxsAAAIA -PDupGK4wMtROtFZqo7vduzkHJuDrE/tAwGqiD2pKMova7WaKM0EUznwcl3gtmhHvFeY+NJ -3Uc9sQcX/9n3y6NAYsC+eZeqe7Sy2GWVyqxOUJHpZqfsKYJidG61TBgKgx+JXAeidYdz4L -4cEapwwocOptbY3ZRFmszekq5xPomnkP9DeSQG6l4eYSv7OpeAHlFj2KCmJMVEZDOl6RyJ -KCqOpfEJIIVoCmna/hQdd9ptLVFmbX/VShgLjvUwfBggJtZNPb5jx+PMy+I0ylywaCIG5K -JQAqust6dzFBx3mBoO4kZPBHlb8XwQ4HYLYph0Ur/lINsHrpLxgmtEw7zzs73Nshl6go2V -uvBtcZ5ywAMk+8CLP5ZgpiGBxlMtFGowp/5zuJxRpc9FgdfxnnVWDyzcQ/YvX9lwzb6cNz -bXeLPsKjOSLPV7G/RFIiuCAOa97ZCM8Ho4FhdNYOGilmjuxV7FJiTc7KP2r+Wh3oxsV7AB -Q6Thj06b2mX3iE4hqLaMKIVE1zs22nMlUtFJv8YY1ZWBihUVlnR9vWgIH7ODoZOwNWBlLd -Qfyfi8w3KgJWj5oVNAM7WniNFQjfNxEbrPklfYg93deVE/LhPghs9I7fsIeHY/p8GtsO/S -amTcjkYi6pUuT8m7IeFYQ8cWvGnbaYz6/9+ni+0aoUL93GKHQw1+mBUVuswVZXBF1WVCf+ -LMgZ ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub deleted file mode 100644 index d9eb1a5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4YwCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5GGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5AosJr7v5twVftAAAAFQC5AGsioHKAc2Cd2QwKLUZSmDZAVwAAAIBxYfEThMIXPQkSer3snKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1XApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMsMu2RSKkK6f08J0vsESnKU4nmnwAAAIEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxs= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result deleted file mode 100644 index 6a918a8..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASsGByqGSM44BAEwggEeAoGBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4Yw\nCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5\nGGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5A\nosJr7v5twVftAhUAuQBrIqBygHNgndkMCi1GUpg2QFcCgYBxYfEThMIXPQkSer3s\nnKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1X\nApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMs\nMu2RSKkK6f08J0vsESnKU4nmnwOBhQACgYEAxH8NZyntzihIAHnx1Lbo7h1sPi4R\nhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3q\nhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi\n7GdZG8Q0tuyfXxs=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4YwCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5GGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5AosJr7v5twVftAAAAFQC5AGsioHKAc2Cd2QwKLUZSmDZAVwAAAIBxYfEThMIXPQkSer3snKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1XApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMsMu2RSKkK6f08J0vsESnKU4nmnwAAAIEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxs=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result deleted file mode 100644 index 27ae40b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format encrypted gcm", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASsGByqGSM44BAEwggEeAoGBAPLAN0jFExSJ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xuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxs=", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBuwIBAAKBgQDywDdIxRMUiYgr8O6dltr+bar1yBuGMAoJa5dsJxjjARpn2niH\nMWRK81tNITsavjbwyJSuN5CYj/fFc9F0xyFug6ZBPQ3AuRhgOpw2Z/S/gUqwS/DY\nbgZc9npIFjkwqpwwuyJf4slAjIu/bGTzhIP2zBMViZQeQKLCa+7+bcFX7QIVALkA\nayKgcoBzYJ3ZDAotRlKYNkBXAoGAcWHxE4TCFz0JEnq97JyiXw89Lr3Ncv+obbI1\ny5Pd0wAIty0g9nRqmLObNFn8zuEZxbKNBKL6yzpyG6lNVwKa+gjygFV9kRLFxVlh\nd1YsRByBBdUPYCLx3WIAMUsbcGLzj6QMA5mj8Vnlef6jLDLtkUipCun9PCdL7BEp\nylOJ5p8CgYEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pSUiaKoWxkjseqUsyW\nENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4u\nn8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxsCFG8ERflm\nOIBFUymTHP8ZeVOgNm/1\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa deleted file mode 100644 index 114e078..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS -1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQTjIb0On/AzYDLFRi+g3fGdAIF72KFG -iZBpP8oKZ8bsncH9ULtVV9517cNcRNuDETQtvLqoCdIn7TipYo8Jv/lKAAAAsA6ULqEOlC -6hAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVG -L6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+U -oAAAAfVd3jjve28r7FhY6Uo//cKIM1rBeWZG16b8bjyVyFswAAABJuZXcgb3BlbnNzaCBm -b3JtYXQBAgMEBQYH ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub deleted file mode 100644 index 8ebee0f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVGL6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+Uo= new openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result deleted file mode 100644 index b430d73..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4yG9Dp/wM2AyxUYvoN3xnQCBe9ih\nRomQaT/KCmfG7J3B/VC7VVfede3DXETbgxE0Lby6qAnSJ+04qWKPCb/5Sg==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVGL6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+Uo=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result deleted file mode 100644 index 4affa3e..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4yG9Dp/wM2AyxUYvoN3xnQCBe9ih\nRomQaT/KCmfG7J3B/VC7VVfede3DXETbgxE0Lby6qAnSJ+04qWKPCb/5Sg==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVGL6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+Uo=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHYCAQEEH1Xd4473tvK+xYWOlKP/3CiDNawXlmRtem/G48lchbOgCgYIKoZIzj0D\nAQehRANCAATjIb0On/AzYDLFRi+g3fGdAIF72KFGiZBpP8oKZ8bsncH9ULtVV951\n7cNcRNuDETQtvLqoCdIn7TipYo8Jv/lK\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc deleted file mode 100644 index 08fe2d1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +++ /dev/null @@ -1,10 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABBqNbb13W -CKfO7B1vpwJDwbAAAAEAAAAAEAAABoAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlz -dHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTp -r+04Ebm1fkyp8RgpFsmvLXLt/dKU0AAADA86k3lHnP6pfD977mwEtKxHOJm44wx8NsdBwN -mNLqxlxUE520nsXjDgpgNU0MF9JDnc1kdhSy8PcdTAAH5+k6bpf3gotPrltPUBMFQdPqst -5kVS7zOgaxv1qZnlyhOqEdNR3Hee09gJByRrAojtcs+sPI7Nba879NPMb5c5K+gKhONHsa -wLAnz66eFQH5iLjd2MwrV4gJe0x6NGCSI2kyzNlxFsoIl7IcHlJHyyuaSlEOFWQJB8cbB4 -BVZB+/8yAx ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub deleted file mode 100644 index 3d87cb2..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result deleted file mode 100644 index dcca403..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEmJuPPvO8/8SExmtb8kN0q9iCIQBM\n1Qox+DY05XEqV/755NHKksVzV2hOmv7TgRubV+TKnxGCkWya8tcu390pTQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result deleted file mode 100644 index 9fe2c73..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format encrypted", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEmJuPPvO8/8SExmtb8kN0q9iCIQBM\n1Qox+DY05XEqV/755NHKksVzV2hOmv7TgRubV+TKnxGCkWya8tcu390pTQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHgCAQEEIQDG2nALLBBmkBnw1QvdW4ClRfF3Zl3CcRHujsYz9CLvf6AKBggqhkjO\nPQMBB6FEA0IABJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLF\nc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0=\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm deleted file mode 100644 index 84178ba..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +++ /dev/null @@ -1,10 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAAFmFlczEyOC1nY21Ab3BlbnNzaC5jb20AAAAGYmNyeXB0AA -AAGAAAABAHURyWtYwqVbjholNpL6opAAAAEAAAAAEAAABoAAAAE2VjZHNhLXNoYTItbmlz -dHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDx -XcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsUAAADAFqKM/ylVkJ/ZA40ZROrW -LNgrttf2+lpVkADwXWzhuESFPPzERKlbHVsVtbiiYmPkLnY1s5VM4zXIj7xyO9YNA9KcM5 -GHOKUL2/NmDaTyGgc9s3BGu/ibpjSeOd1rtGAB4cw1s9ifbXBQd3qDbqzaEmovs3MGaGHD -c3VagdxhsppjrPjZ+B40Pzs9QkSGutsSJDpH9wVIu4OLr89TquTU3PVACDRU03lPPENVbt -rh2IMJeEQyNINQHtfVwordj8LMOEsBjyQ1aqHNva/iKyTBiw== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub deleted file mode 100644 index 61b0b99..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDxXcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsU= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result deleted file mode 100644 index 1078648..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz6mlrA3G+R0ds5oHfKCxG55N0gqJ\nP45CQAf/kukPFdwPqLkBHxP++sKxn3/L7wbFTyCa+DhSzOvosN9pAFmexQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDxXcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsU=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result deleted file mode 100644 index 626aedf..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format encrypted gcm", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz6mlrA3G+R0ds5oHfKCxG55N0gqJ\nP45CQAf/kukPFdwPqLkBHxP++sKxn3/L7wbFTyCa+DhSzOvosN9pAFmexQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDxXcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsU=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIHQfJ+4ZNcwSBaCR5kwrR6HjUsTF//R1F983RSTR8vbJoAoGCCqGSM49\nAwEHoUQDQgAEz6mlrA3G+R0ds5oHfKCxG55N0gqJP45CQAf/kukPFdwPqLkBHxP+\n+sKxn3/L7wbFTyCa+DhSzOvosN9pAFmexQ==\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 deleted file mode 100644 index 7ae3165..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +++ /dev/null @@ -1,7 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW -QyNTUxOQAAACCyOMGts0WaAdug9NeXbGn2Jrt4wwiO64dumxV2a1IgKQAAAJBOfs+eTn7P -ngAAAAtzc2gtZWQyNTUxOQAAACCyOMGts0WaAdug9NeXbGn2Jrt4wwiO64dumxV2a1IgKQ -AAAEBgQKxJoToGE/Xi4UkYR+FXfin4jG8NTcZ13rJ4CDnCfLI4wa2zRZoB26D015dsafYm -u3jDCI7rh26bFXZrUiApAAAAB3Rlc3RpbmcBAgMEBQY= ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub deleted file mode 100644 index c85c7d1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILI4wa2zRZoB26D015dsafYmu3jDCI7rh26bFXZrUiAp testing diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result deleted file mode 100644 index 3c9ca29..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-ed25519", - "comment": "testing", - "public": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAsjjBrbNFmgHboPTXl2xp9ia7eMMIjuuHbpsVdmtSICk=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAC3NzaC1lZDI1NTE5AAAAILI4wa2zRZoB26D015dsafYmu3jDCI7rh26bFXZrUiAp", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result deleted file mode 100644 index 705fa99..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-ed25519", - "comment": "testing", - "public": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAsjjBrbNFmgHboPTXl2xp9ia7eMMIjuuHbpsVdmtSICk=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAC3NzaC1lZDI1NTE5AAAAILI4wa2zRZoB26D015dsafYmu3jDCI7rh26bFXZrUiAp", - "private": "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIGBArEmhOgYT9eLhSRhH4Vd+KfiMbw1NxnXesngIOcJ8\n-----END PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa deleted file mode 100644 index ccded2a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn -NhAAAAAwEAAQAAAQEA4q6eZdx7LYh46PcZNcS3CnO7GuYsEJZeTj5LQSgp21IyTelaBPpr -ijnMwKa+pLQt5TEobpKFFNecPdT6oPoOKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHM -BNkoTFeGrursPkqYRJ0HL4CqYqRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKb -zibJc64JFM7tUoK6Vl64YiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs -8zjxsf6c6N2tKXkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38 -KvTx3wjNQwAAA8hLhVBxS4VQcQAAAAdzc2gtcnNhAAABAQDirp5l3HstiHjo9xk1xLcKc7 -sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+l -fQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg6 -4MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u -2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28 -uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1DAAAAAwEAAQAAAQAmShSbZBiyYkD6KPLr -MCUy8MWED6kVzDB1yvPvN5eKYmH44xe/i4UqvgSl7gR50a2G7zzDIKC2Go1brGQBWPuXRa -ZtOjQygeD4rMHBiH/b7zfy4pQyKDfITTHOFXWE8ERiyL00bAZt09icCy92rQaq8IY/+U56 -sPPJH9UAYG9nEev8opFjAWToFDu0U2+dC+lbqLlXDqDRo75NlnDFmgUoja3y2eFr9A0Cc+ -hjecrdxyJFsCJfEfaLWtBnZb886gqzzvfbHImSQtBAKERcSxuki7uxMoP67g3iQOXa65uz -8kFWRNmbQTGQttakoUaybh1t9eLpBqvVON/4Kg0THShRAAAAgFBTz2ajBK/R/crOSL9VK1 -f7oQv2iJTRVfnUs0r+qPGgf/a/5UwkGRj0KfEWBp3qYD+keShnPr6PDPFrm8UmIdUX8AY7 -3tWT2K/JQVlzJNuINsw+DNjn4M17Z25q0LPmReRWL0nRc2w6W/hmQ/Jmqz6w8Qc4+xpeqS -/HG5feliVnAAAAgQD90a+5Ky3o/2YtueqRf/3dKoiMgGB7JAOzye4dDKGABSlWuQ4N4xEI -CW5MSTp7i/uobTF/tyFO3tTSyb5b2Xwbn/kLO0vgvFCdUGR2BQfN3mcT92T0Gn3JDF3Wym -i2mgU6qnPf+eu+RKZQ9IiyNGny61ROUQa0R0z0pgiAfA89xwAAAIEA5KE9i6hHmigJwfD7 -/AGI4ujyWIVpNyrTdXG3HAPhsdoFuG5ggHggrPuuBF9wNcosrhL20VNOQGHg15gWZIVudu -0qxky4ivQs67Sk9XUjuvTnf+VubM51rIsmh4atKJFSSZo78DEcTRt8aXLrSNvGQ4WPRweM -2Z0YGfMMDM9KJKUAAAASbmV3IG9wZW5zc2ggZm9ybWF0AQ== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub deleted file mode 100644 index 133afc9..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D new openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result deleted file mode 100644 index dd8a8b4..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result deleted file mode 100644 index d1ada9c..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV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/dk9Bp9\nyQxd1spotpoFOqpz3/nrvkSmUPSIsjRp8utUTlEGtEdM9KYIgHwPPccCgYEA5KE9\ni6hHmigJwfD7/AGI4ujyWIVpNyrTdXG3HAPhsdoFuG5ggHggrPuuBF9wNcosrhL2\n0VNOQGHg15gWZIVudu0qxky4ivQs67Sk9XUjuvTnf+VubM51rIsmh4atKJFSSZo7\n8DEcTRt8aXLrSNvGQ4WPRweM2Z0YGfMMDM9KJKUCgYB7Yh0b1EOjCdQv0jqWtDNB\n+dUbB6Te92jdUwHvGR7AzsGDqL2OPp0e3QbDCq3lNO0GuN3hCbKlVmj6dpuUpqpP\n+3ni3dZKzwAZGOVdAaEDkGNnL1Hh36bZvqs3KHmymjiEhiuB60mP2mtG2zg/+H6w\nWXlIANdTd32PR87GNohqLQKBgA36ic/LJy2Wuxn/iPicg2kUQxUEey1jUfCBVmfB\nGQCNywG+xem07pKFBNvBlhPD27187VhZFpS7J0snQl89BUcCMzZSpIniagizT86u\nLdQVez4HohvG98zn6SAqLNYpJHXZl0aVShywzIeJ/jbDMTkZpmv6WzNG9p1HjfoO\nhoL9AoGAUFPPZqMEr9H9ys5Iv1UrV/uhC/aIlNFV+dSzSv6o8aB/9r/lTCQZGPQp\n8RYGnepgP6R5KGc+vo8M8WubxSYh1RfwBjve1ZPYr8lBWXMk24g2zD4M2OfgzXtn\nbmrQs+ZF5FYvSdFzbDpb+GZD8marPrDxBzj7Gl6pL8cbl96WJWc=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc deleted file mode 100644 index 09aa65d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYm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uQbe/tK14W35VjtL9aGKsz9Ubio029 -O23HJXMxM9Dd6EYXAR9xMLFDTcLT03kjRlL/4XFS4fJqbTGDtuQNqRO3QK/myVAYjgnXwz -X1s77WeIK3sOMwTIXaHReUiQ1Cw+WmkXOhefePT+HrkyDlJk3ikgPUy2s5QW5/d6Lmolwb -mcS9JUfaai0ysP3v1bew8go/IHiUD/X9AkjkKM2kfS1NcPSi18r2721e6RqZiIHxSoyKvq -yUmwiS1kUklSuhlTORBvbclbv4HTwp1iJfu/6zsMqVJc2E8H6WUw3kTeh9fhDMpTY5NArF -KD2aRIYHFvOKav+0vSbQ/KqmKeiTvyZaV7q6giRxVLxBddl4+ucD+FybPJZSebRQ+0QT1j -aUDSpp541zW0rX7sCiZ6sFUybCPVDM1uA5gTAP015OD/FS342gi+Y04K0jBSjlApuy6BQx -sMEQbR3weMmnodbhCtbcgDZDagSFNPlDud0GJl9IWV4hO/K1f9a+Ox3G27Jq4YC2PFgTDb -aYib4xAXPUHJpoWsstSjpMnfgKcS3AGRdJ/jxlKRWV/NXFf4DYIwpzITqFMF+4VqXCa2AS -JWOcSxOK92UqCcZEs8RED3x9dF9E2yBBwHeuwDvH3c9x/nsM/cjDY+EE9VcEUOxF6qMOhO -CiRtEihEAYM46XeFzcSOQrwWPcKu3WTv3IpnzTaofBxV065CUn ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub deleted file mode 100644 index 0e80f0f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8hCiCPnRs0ucZeyn3pNYKN63dVoxbMB4Yzjs7gvo7XKDby/6GXoU/CFQ/Q9zXRxRZmFglMYh2pOD8iWdwpLBdd+GmHb4a6xxKtoPpz1+yCPYvi6nXzKPO3B9Wbg8dtTpV23l8MZDxSRUQ9HIkYHQOoOjJx/AaMdZyHZP+eYK7UqmX1+dtCzr5vvLyEABxrsoFxH/oW/iKO6cDmTxoMyFl9DfUhDTS7cL1OVBulSBav3aJPxjsCEIs6OE94wLJfFtZAPe4GqWWcC7uG1uUL5Muy2N+SfXHOHLaI5n1vozt7lIO5TqvykcqTxipKblMW4Y7Iwlhh0YKJxzH3KJ+Qkn7 diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result deleted file mode 100644 index ee0fd94..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvIQogj50bNLnGXsp96TW\nCjet3VaMWzAeGM47O4L6O1yg28v+hl6FPwhUP0Pc10cUWZhYJTGIdqTg/IlncKSw\nXXfhph2+GuscSraD6c9fsgj2L4up18yjztwfVm4PHbU6Vdt5fDGQ8UkVEPRyJGB0\nDqDoycfwGjHWch2T/nmCu1Kpl9fnbQs6+b7y8hAAca7KBcR/6Fv4ijunA5k8aDMh\nZfQ31IQ00u3C9TlQbpUgWr92iT8Y7AhCLOjhPeMCyXxbWQD3uBqllnAu7htblC+T\nLstjfkn1xzhy2iOZ9b6M7e5SDuU6r8pHKk8YqSm5TFuGOyMJYYdGCiccx9yifkJJ\n+wIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQC8hCiCPnRs0ucZeyn3pNYKN63dVoxbMB4Yzjs7gvo7XKDby/6GXoU/CFQ/Q9zXRxRZmFglMYh2pOD8iWdwpLBdd+GmHb4a6xxKtoPpz1+yCPYvi6nXzKPO3B9Wbg8dtTpV23l8MZDxSRUQ9HIkYHQOoOjJx/AaMdZyHZP+eYK7UqmX1+dtCzr5vvLyEABxrsoFxH/oW/iKO6cDmTxoMyFl9DfUhDTS7cL1OVBulSBav3aJPxjsCEIs6OE94wLJfFtZAPe4GqWWcC7uG1uUL5Muy2N+SfXHOHLaI5n1vozt7lIO5TqvykcqTxipKblMW4Y7Iwlhh0YKJxzH3KJ+Qkn7", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result deleted file mode 100644 index a0f0fed..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format encrypted", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvIQogj50bNLnGXsp96TW\nCjet3VaMWzAeGM47O4L6O1yg28v+hl6FPwhUP0Pc10cUWZhYJTGIdqTg/IlncKSw\nXXfhph2+GuscSraD6c9fsgj2L4up18yjztwfVm4PHbU6Vdt5fDGQ8UkVEPRyJGB0\nDqDoycfwGjHWch2T/nmCu1Kpl9fnbQs6+b7y8hAAca7KBcR/6Fv4ijunA5k8aDMh\nZfQ31IQ00u3C9TlQbpUgWr92iT8Y7AhCLOjhPeMCyXxbWQD3uBqllnAu7htblC+T\nLstjfkn1xzhy2iOZ9b6M7e5SDuU6r8pHKk8YqSm5TFuGOyMJYYdGCiccx9yifkJJ\n+wIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQC8hCiCPnRs0ucZeyn3pNYKN63dVoxbMB4Yzjs7gvo7XKDby/6GXoU/CFQ/Q9zXRxRZmFglMYh2pOD8iWdw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uRxZ4a7stE/t8n\nM5UxxkqeD8rtRAQJyFDGPAhFeeOpIfzEVPG+5s72pI69+9aE/gCGA91+sOSnLoiJ\nPW1I7SouZfCeaaRQxSSIMjsCea2s6yraujGZJyPEWSkG5TijY8+vzDsCgYEAyMxX\nCYvqlRTaT5lAkRTFLqf0/NSpRoCnG7qSPUyJjxJsVfYFLv1FZCyyrA+SaIyufjoT\nKutKE31r7wre5bkjRRenIcTkR/tdNRdkWsB/ysZ9Cp43FIPTXS5gxTQxOaJyRGvJ\n9MW0m8N1pMvPIsagzoxxvzgU9ZOejs2NQ69qXUECgYBq7DxOgp7+0zhdsto4ZLqc\nXinQ/2CKiWiYw6kD3KiJZkFNIxla2iQyiplOQjv3gqvzqmg/uc+3PWbLR0EjYbRm\npfXr8P9BTk+vDky0Q79bUNrgD5lg1lVYApqDCFUD/Pw8u2FDk3EUB7SeNWnMZZBR\nbWdZRkw/7kSnDX+DFA59qQKBgG9v0AHxT4/LEdlJEOczYrcg6TqDfyosbhFaepxg\nZJstO0h9j6TjVGZi1AnfXn59TL2q10ZjbCni2krAerF9DNDkbpG0Joi4PKMhR0WC\nPam4fF6vLZxKCLxW58epzoPQ3p+QPnWEX1ZupFR/84W2PDpFAT+BDUi40y8nbnWY\n3WvBAoGADjh0hEkq3sy6oWt0m1NjGU1yxKV+geg48BFnu2LVSFv1rw1V7X8XFEYl\nP1B3sEpOOpPGuoz+r2E9PrsdMuYNOmVlRFRpe7pm7zyhzdFYBvLE2btJqv1PmxFu\ncEkrXJS/ETxkKdMaoUbYHcKiTIMi2pDrdJtg6oHcipm0yTBZkKs=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm deleted file mode 100644 index 442a4f5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +++ /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mqPQ+/VdsOSP5fJcXN+oKoL7jPr2WlmtFjo8PKc -rpgKC3DhUzvRXnNYotG7trbPOGJbBRgoxTQ06rlChoaBp7kUKqNNBxXhFQCeN0sCb90fHV -c+X3Yy8oUsAIxxmCymuVV8gRzLD6OdqQRBthEUQktNJLhv4mSufwSfsLDluEc7YEOrsJhx -jk57TmkFFyLj++IAKi80FnSkRfSBQF3dTSrBZ4BIHWnek8V6goxhy6lRMaFoTow2foknvr -VHgiNGvimOM3ESYVcOwt3YQqbUG/7b4jRlY3nNBJcsbxGe54B8zaoLt5pQNRxUuHc3fR4R -haWHR6IWsfey7jAlRzrJAVVEEj4d6yvJ4bLqWGmoim5QlrePRuRFyV4FNb8N6hJ9gvWY9f -HUT9TwxArDIMzu4T1khwRoFU45XN0U6xHEPcT/pZ2C5jJSSQ5W/SyBudexjMMPRKf2EIeD -gjv8vIhdtkmxHv7bapaaYeYX5gtKYl+McRollDxVC8Kr48RmOVJnK4aFBQ99Wu7SXDbwas -vcvVHI+zUiRGjU01/CU/Tf4GTodAlmZIuqKmBTX/KvVj6ZiK0BsZuEl9qom+l4rlazaahY -FdL5M4u0qt7rVirWJWgWzmPXZ+MCK0Fs70ORvqRGxVMilhQcWsng3ZXnHaYiBRhk31KqF+ -BEPEh79OknD0okKed2YYfg8vdUR+noENybrsIleP1aKBBmQCNbKU04N/9Su+wxX8YfGhYU -kPST35Wg45zER9gZGsREnON4sQTng9LHB5CrJCo/MowcZG/ycqL1mxemApZ9nYUrjA8HJi -zDwRHHUtkkLNG8Cmyg== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub deleted file mode 100644 index d5c7685..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDMemjkha1c+2s58qzx4968svvvpbxt6EiLlyRHuqXCouTdBZeXGtVRlxpkqnnOE0ETMSQSqm1d5k1EMa7VVcTeXFQaBIc2XF0S1uIoEvNV0JXpDjiIdPmjUFuUf9oGGLKKQQMfzpymqoiHYQNhuarYd1mSb0+a+UwKxAxGeCPd95o/JfWjKO0JTr3nnEj1eTjtu0pofmchab9HC9YbJ3JsvbdRq7Z2ZHp8uu16SflPpP2A9l+F4HN+gPOLcGxbVkVZHsLI07OpkWdxMPBUrzPF9OnCntRWoBhQ4LFHYHllTtd+/E90QXXhe1pxj8FktJiaitiz09GU5h4IWi3isNr/ diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result deleted file mode 100644 index 0f00545..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzHpo5IWtXPtrOfKs8ePe\nvLL776W8behIi5ckR7qlwqLk3QWXlxrVUZcaZKp5zhNBEzEkEqptXeZNRDGu1VXE\n3lxUGgSHNlxdEtbiKBLzVdCV6Q44iHT5o1BblH/aBhiyikEDH86cpqqIh2EDYbmq\n2HdZkm9PmvlMCsQMRngj3feaPyX1oyjtCU6955xI9Xk47btKaH5nIWm/RwvWGydy\nbL23Uau2dmR6fLrtekn5T6T9gPZfheBzfoDzi3BsW1ZFWR7CyNOzqZFncTDwVK8z\nxfTpwp7UVqAYUOCxR2B5ZU7XfvxPdEF14XtacY/BZLSYmorYs9PRlOYeCFot4rDa\n/wIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMemjkha1c+2s58qzx4968svvvpbxt6EiLlyRHuqXCouTdBZeXGtVRlxpkqnnOE0ETMSQSqm1d5k1EMa7VVcTeXFQaBIc2XF0S1uIoEvNV0JXpDjiIdPmjUFuUf9oGGLKKQQMfzpymqoiHYQNhuarYd1mSb0+a+UwKxAxGeCPd95o/JfWjKO0JTr3nnEj1eTjtu0pofmchab9HC9YbJ3JsvbdRq7Z2ZHp8uu16SflPpP2A9l+F4HN+gPOLcGxbVkVZHsLI07OpkWdxMPBUrzPF9OnCntRWoBhQ4LFHYHllTtd+/E90QXXhe1pxj8FktJiaitiz09GU5h4IWi3isNr/", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result deleted file mode 100644 index 127ce3d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format encrypted gcm", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzHpo5IWtXPtrOfKs8ePe\nvLL776W8behIi5ckR7qlwqLk3QWXlxrVUZcaZKp5zhNBEzEkEqptXeZNRDGu1VXE\n3lxUGgSHNlxdEtbiKBLzVdCV6Q44iHT5o1BblH/aBhiyikEDH86cpqqIh2EDYbmq\n2HdZkm9PmvlMCsQMRngj3feaPyX1oyjtCU6955xI9Xk47btKaH5nIWm/RwvWGydy\nbL23Uau2dmR6fLrtekn5T6T9gPZfheBzfoDzi3BsW1ZFWR7CyNOzqZFncTDwVK8z\nxfTpwp7UVqAYUOCxR2B5ZU7XfvxPdEF14XtacY/BZLSYmorYs9PRlOYeCFot4rDa\n/wIDAQAB\n-----END PUBLIC KEY-----", - "publicSS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KY8MFNBbqqp0eKhatRNA8q9O23jADDp3fubKV0aUQSrRZz0y9\nPmmEJnTRAoGBAPZoL+p+AbI5yTg01LdsaQL2f3Ieb3CGudesmjAVnI3QEoC6gxGX\n4cbmBSCY+vBzh2RJNJcS+Rq6VmJZA930Tb0npHiQYOohB7BFOCbBJ2L18g/JdNpi\nVb3wqFs9NG1GFOOV6iGtV/6t4CRTKtAbd695YZAJ5S6DDvMrH9pTnAKrAoGBANRw\nVuLfBTFhSKvFz+0W0yy6Sn0koXjpp1ifC0BWLwHiA/IZjAY7qmsNQZxWdleWLP28\nRNaac3vMJO/HFD4IyL59Zli+kREGKazvZM1dvOs0mgdVMTPMsT57wcJr5OSxqCvJ\nD3NkcgFuA1e3jVC5p/wUJCi/lhyFPx3z1C5vRqj9AoGBANeyYmd5wFBcp1ktXhvm\nqZIvZ2blX5X4ScyTSjHXaUD2qIvJORz4gGqVRl2/rMM5zoYqUwAAWtFb1mynEWyF\nBFwVzLLBaCTrnwhdv4alRK4rL6dEKadVt0ra1PVxgWg6leSXgenTDRli6bfCmdKs\niLuxnIbzMozhqv+Qe4Sp9gKbAoGBALWBThsEpXEtR2PL3P0atU7P0/jcJUIjkCF9\nsaVEfWFEdE6TWTmyHMbeSqKClRX8b3BTPRWGXQj2wNBE7Zya8LkgdyN3noZHF7Bz\n0VJNtq3XAYsmVKWHTCCwqDmu6aAj0iWm4ZabyXRDRIPbhdfk6AvOQZ63IlA34Fd9\nDlqmJF8ZAoGAIJzfMDT2LvlMOHqpKgelS4ZTHEmqqJZM5rXdsZwYqcyekjz25COE\nTJwme3xIt3kSZEcOauGHCgUVeBcE6GwZbQ1WoNIvazhnUXeErOeoxQ+ZqdfC8iyT\nUn/P27yx/FcwDdubQhbgxZ5M+pu+0OQ1WPu02LQZQrX7x4a6isYtTDo=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa deleted file mode 100644 index f2ae4d4..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -MIIBvQIBAAKBgQDs+n9ZKhwYNr1V2uGn0C/2MSTM4KB4puy4jR5ubRTT1yq5SbzK -RQlCjfplDN//Eqa6aiFmvGKA3RKUtPtBmD96EHW1mvr7O+Pc8z8L/4zg9tkVQR6V -WBKgBhVwZHDzzs5+Ag2j54BZfcaGMcNGhTE9DcZYeI/t6FhOxgpID3EA/QIVAMyI -czBU74xB48IMoamlEhc5Lh+3AoGBAMuy2h9K9+oQIPcTcsD/mtmhOYlw2ZPCJV2b -WFeZ3QxAujenBzEp0oqht8tdj+BE7Er+CWT2Ab/A92MrjYUaGaPjdF5+K6CSPMUX -rK8nBabSBJ+ELqTo/8vHJ2eVWIUJBwCzbw3ryitH7LD3gyEr2NuQQJE++wyWPBHK -M3SFOft6AoGBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFycz -bUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/ -xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvWAhUAr/vy -ahuEz4UFGhB8IIeLWQUO5FA= ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub deleted file mode 100644 index a7fd375..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs749zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3oWE7GCkgPcQD9AAAAFQDMiHMwVO+MQePCDKGppRIXOS4ftwAAAIEAy7LaH0r36hAg9xNywP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuNhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeDISvY25BAkT77DJY8EcozdIU5+3oAAACBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvW old openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result deleted file mode 100644 index 05f8140..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "old openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBuDCCASwGByqGSM44BAEwggEfAoGBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim\n7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs7\n49zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3o\nWE7GCkgPcQD9AhUAzIhzMFTvjEHjwgyhqaUSFzkuH7cCgYEAy7LaH0r36hAg9xNy\nwP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuN\nhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeD\nISvY25BAkT77DJY8EcozdIU5+3oDgYUAAoGBAOdrYUJ38yjc9tnrvLWsB1KlkYhc\n+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMn\nOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5c\niuO0ltu90L9+2YvW\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs749zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3oWE7GCkgPcQD9AAAAFQDMiHMwVO+MQePCDKGppRIXOS4ftwAAAIEAy7LaH0r36hAg9xNywP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuNhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeDISvY25BAkT77DJY8EcozdIU5+3oAAACBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvW", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result deleted file mode 100644 index d21d1cb..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +++ /d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vDevKK0fssPeDISvY25BAkT77DJY8EcozdIU5+3oAAACBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvW", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBvQIBAAKBgQDs+n9ZKhwYNr1V2uGn0C/2MSTM4KB4puy4jR5ubRTT1yq5SbzK\nRQlCjfplDN//Eqa6aiFmvGKA3RKUtPtBmD96EHW1mvr7O+Pc8z8L/4zg9tkVQR6V\nWBKgBhVwZHDzzs5+Ag2j54BZfcaGMcNGhTE9DcZYeI/t6FhOxgpID3EA/QIVAMyI\nczBU74xB48IMoamlEhc5Lh+3AoGBAMuy2h9K9+oQIPcTcsD/mtmhOYlw2ZPCJV2b\nWFeZ3QxAujenBzEp0oqht8tdj+BE7Er+CWT2Ab/A92MrjYUaGaPjdF5+K6CSPMUX\nrK8nBabSBJ+ELqTo/8vHJ2eVWIUJBwCzbw3ryitH7LD3gyEr2NuQQJE++wyWPBHK\nM3SFOft6AoGBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFycz\nbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/\nxXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvWAhUAr/vy\nahuEz4UFGhB8IIeLWQUO5FA=\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc deleted file mode 100644 index 57064cd..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,3239878D1E2D496289CE9CD2CB639BE8 - -k8/4Ax6UcnImNvEuybHwa9OHZHeCpKmq3Cu/q29a9AkTnktAWVmU9rQFch5CweDH -TEuRN+ZHecHrrMPR0fTpjXzZTxmU3549BQ2DfMSAdikPNKtBvhJwpT2se0rJ9M98 -p2xJQNhpxXT6f4Hy8m6QvjP5iTmlnQrrVBjV05ih9TLLQb4Y4NlydC08OyEcEoJV -w43G69sv2ws/tUVr7XSUtv8l+51ywSm42Pw6YOVlMZ7y+XB/uWmFNMz5gLN17tkc -wikhgvNnMWGLqb/AruuKPp5FrGRIC19DKRzDSPF5WlzLBdd2TQKDltknDj08AQMJ -bDsImbePteqhU+D7GiN2pVAD2b5kCZlFzYG43/Q8R3+O2l0Lvq5VBIqNB7LyJfTy -DL8XX0gzHk7FgG5MfLYin/qp7upnDXeSnIm8A2tlBYh9YzG3q/a53c5V2NomWjX0 -zvS+C7+w5NDwDRT5t+kecMhmHWNBuE/Pbvy0DaZQ/nnsC6TlkcaROJ0fiY3Da8E6 -EYvM4uKaZudsOOapwx0ZXHu2GZgLnly0p2Cd0Yf9t2UX9uySfwdL2TNw8nLVNVkh -aBE/x9LkKPWqOBV8tg/9ITGys/qgZh0A1r+RGmj/tII= ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub deleted file mode 100644 index 18f5804..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAP25RC69mW4t09jpaine5ZRHmOtqNJa2nbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAiQDKMD/ikWqq/AAAAFQC/rPmzFozpCeLbFQykOaDGFZaqaQAAAIEAw1hJAYQzn/ZboF/xXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29JJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SOlVxxEkYneg7RH9Seh+U3rRacrh4AAACAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAo= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result deleted file mode 100644 index ad14260..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASwGByqGSM44BAEwggEfAoGBAP25RC69mW4t09jpaine5ZRHmOtqNJa2\nnbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T\n+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAi\nQDKMD/ikWqq/AhUAv6z5sxaM6Qni2xUMpDmgxhWWqmkCgYEAw1hJAYQzn/ZboF/x\nXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29\nJJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SO\nlVxxEkYneg7RH9Seh+U3rRacrh4DgYQAAoGAOX41OCxx8mTuxpON/uZn6GwvK/m0\nK9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7p\nLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n\n/IO5uUbWoPK5iAo=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAP25RC69mW4t09jpaine5ZRHmOtqNJa2nbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAiQDKMD/ikWqq/AAAAFQC/rPmzFozpCeLbFQykOaDGFZaqaQAAAIEAw1hJAYQzn/ZboF/xXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29JJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SOlVxxEkYneg7RH9Seh+U3rRacrh4AAACAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAo=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result deleted file mode 100644 index 18c5271..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +++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SkdcW3hZ0ai0SOlVxxEkYneg7RH9Seh+U3rRacrh4AAACAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAo=", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBvAIBAAKBgQD9uUQuvZluLdPY6Wop3uWUR5jrajSWtp27Ea0rGZLxl8Wye6I8\nbMm1n+JAACOBqbBjM5axa5TBKR0H3myQJ/sycBkvpaEe0/oDc/CaFSIDxfXWm11c\npnMoJeBQf7DQJleFytzo70ltTQinUpMGWa/4M+SQaNagIkAyjA/4pFqqvwIVAL+s\n+bMWjOkJ4tsVDKQ5oMYVlqppAoGBAMNYSQGEM5/2W6Bf8Vwx8z+PbkaSCKMmkn1M\n+Vt/i6YvwgZDiBmhjrorcHKU38wUmSA2fTkbPX6uaAYdvSSXAHQTYFV3804Uohrw\nYFOFCI+NTJRuDxukrfPFVwstJ4hF1po0pHXFt4WdGotEjpVccRJGJ3oO0R/Unofl\nN60WnK4eAoGAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71A\nOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6\nbEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAoCFQCdYU1l\nO1pCZ3Jhf/YDAAnfQHAtMxAQEBAQEBAQEBAQEBAQEBA=\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa deleted file mode 100644 index f4170ac..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIJx7zPcbJg1zUAsBhKbmN0eOjbr+/W2qGSZTCP/c0mz4oAoGCCqGSM49 -AwEHoUQDQgAELN85t86lbEONGsyPNDxD/P2f9D9/ePBT3ZpAeVYUdyrVO00jO4JE -FPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ== ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub deleted file mode 100644 index 8f39dd6..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCzfObfOpWxDjRrMjzQ8Q/z9n/Q/f3jwU92aQHlWFHcq1TtNIzuCRBT3ypVXOIbQvaGWw2jXltbLACG5+Ls4oDE= old openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result deleted file mode 100644 index 68f3c14..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "old openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELN85t86lbEONGsyPNDxD/P2f9D9/\nePBT3ZpAeVYUdyrVO00jO4JEFPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCzfObfOpWxDjRrMjzQ8Q/z9n/Q/f3jwU92aQHlWFHcq1TtNIzuCRBT3ypVXOIbQvaGWw2jXltbLACG5+Ls4oDE=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result deleted file mode 100644 index cfabd13..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELN85t86lbEONGsyPNDxD/P2f9D9/\nePBT3ZpAeVYUdyrVO00jO4JEFPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCzfObfOpWxDjRrMjzQ8Q/z9n/Q/f3jwU92aQHlWFHcq1TtNIzuCRBT3ypVXOIbQvaGWw2jXltbLACG5+Ls4oDE=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIJx7zPcbJg1zUAsBhKbmN0eOjbr+/W2qGSZTCP/c0mz4oAoGCCqGSM49\nAwEHoUQDQgAELN85t86lbEONGsyPNDxD/P2f9D9/ePBT3ZpAeVYUdyrVO00jO4JE\nFPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ==\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc deleted file mode 100644 index 7e118d8..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,4BE217089AE8B7311672C159E0690AB4 - -AkqjOP53cDHrdkJFRVLHYS7fSPVcIa4BgKegLwqRUqJOvEOnn5j6RYCh2CMdPjwN -rdw26Gc0V++xeMISAbrX4TGAQPWyDyiuoCffTIAfbkNq8YQR/sNJjNmZEgtCs6+O -4iBQ8TMXO+7oWRC221FDbTIhB6k4lXXph/HzdW0/Y2A= ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub deleted file mode 100644 index 8efc1fe..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4KgjqWJj9PR55PeF7t7PTXdx7cvMDqNkq4UTMjoXA5WtQYdoC2sxJnI5Psqvtrfa13C31gY8TlFAZ1cClnoBk= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result deleted file mode 100644 index 3b3064f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDgqCOpYmP09Hnk94Xu3s9Nd3Hty8\nwOo2SrhRMyOhcDla1Bh2gLazEmcjk+yq+2t9rXcLfWBjxOUUBnVwKWegGQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4KgjqWJj9PR55PeF7t7PTXdx7cvMDqNkq4UTMjoXA5WtQYdoC2sxJnI5Psqvtrfa13C31gY8TlFAZ1cClnoBk=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result deleted file mode 100644 index 423f6e2..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDgqCOpYmP09Hnk94Xu3s9Nd3Hty8\nwOo2SrhRMyOhcDla1Bh2gLazEmcjk+yq+2t9rXcLfWBjxOUUBnVwKWegGQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4KgjqWJj9PR55PeF7t7PTXdx7cvMDqNkq4UTMjoXA5WtQYdoC2sxJnI5Psqvtrfa13C31gY8TlFAZ1cClnoBk=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIA7fGKE3wZkXb6jMcMriZujktUQ6FTC0SoTAa6fKDXY8oAoGCCqGSM49\nAwEHoUQDQgAEDgqCOpYmP09Hnk94Xu3s9Nd3Hty8wOo2SrhRMyOhcDla1Bh2gLaz\nEmcjk+yq+2t9rXcLfWBjxOUUBnVwKWegGQcHBwcHBwc=\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa deleted file mode 100644 index 2eadbb0..0000000 --- a/reverse_eng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VFhCkfRjwVHV8qdIJc+Q4mjnjOeNfvqnzWOlSfZFegyWvOPW7hTX0/jZYGOb4I -7fzYyUPHnlu73twmshJMTzE1Ju7RdJXyLtg8xpRfAoGBAKjlyELXTWjZfP4Jnd3H -NHr+gSRGHp5A0RGe9zsdVGNz0xteA/mBR9JB1grJ2K8jsXmDlIMmHskKIPGhJetQ -mcr9qcRy9Yx1rZ08ZbYa2N9JllV/+hDLeII77jlh3y8CN5Ov81u0ExReaWxQmjXu -YgODix4TLLboae4Q6+7Rxu/PAoGAOZ04N7kqX/ygb+qUE1Crgde7I51i93pKp5C4 -baMKrFhtt9UTGfcdfkuG31+lnsMSxEo/npp5KUzq319+cA+P6sh2aXguvu32cO8g -O0cJK6HDAKPTjpKcD7QWR5xXL1X3KeJErI6vUnWoPsuchsiHqcVtFhKVEujpDPZ3 -MFY1D/8CgYBvv5mBb2kBf2/2JHp3lP/Q6LepEBkZk9dvoEU6/5xLvA5gEXR0MUj8 -g97Z1duGdXD/uEVRuRuOJkk4p8YmSM7t34st3lF06wdJUGcKvmZpp2ee+CdLwESi -GDCwcP5pcii56TVr09uHITWei4jFm+3Ye3h092dvPyNoEiJOgk2lsg== ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub deleted file mode 100644 index 1eaa7e0..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDzAhKfHbFah5m6vzKf/w0/KRRjaZjLGfWfSYTlYlKj6ZyUUVKac3TxYK3znoA7w8w+4Cf1zDSPeol7RIpOegxhKn7h8Gyrpgc4Ym+VEBMX1ImRIjHAEJiwxP5x/vy/OEpEmtcB8n8tbNXtvmBOEfGP4lvL58T/J4+Lz4xvf1TBhYYQV/65HFxAh64Nf9WM8200pA+474dGLrtY1c8WhQ2YVe/ViafrVLl269ULEvxd0dcd2dmAgnzsJOUsEY9X9T0esYl+XQBD+O8yy8BXgiExkyVXlBLZCKAruuR8FV7uTQ0hZDtXCTmK6dSmZQ1WEoBF3Oe9vwIkmbRkTHgXafxx old openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result deleted file mode 100644 index 720438a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "old openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8wISnx2xWoeZur8yn/8N\nPykUY2mYyxn1n0mE5WJSo+mclFFSmnN08WCt856AO8PMPuAn9cw0j3qJe0SKTnoM\nYSp+4fBsq6YHOGJvlRATF9SJkSIxwBCYsMT+cf78vzhKRJrXAfJ/LWzV7b5gThHx\nj+Jby+fE/yePi8+Mb39UwYWGEFf+uRxcQIeuDX/VjPNtNKQPuO+HRi67WNXPFoUN\nmFXv1Ymn61S5duvVCxL8XdHXHdnZgIJ87CTlLBGPV/U9HrGJfl0AQ/jvMsvAV4Ih\nMZMlV5QS2QigK7rkfBVe7k0NIWQ7Vwk5iunUpmUNVhKARdznvb8CJJm0ZEx4F2n8\ncQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDzAhKfHbFah5m6vzKf/w0/KRRjaZjLGfWfSYTlYlKj6ZyUUVKac3TxYK3znoA7w8w+4Cf1zDSPeol7RIpOegxhKn7h8Gyrpgc4Ym+VEBMX1ImRIjHAEJiwxP5x/vy/OEpEmtcB8n8tbNXtvmBOEfGP4lvL58T/J4+Lz4xvf1TBhYYQV/65HFxAh64Nf9WM8200pA+474dGLrtY1c8WhQ2YVe/ViafrVLl269ULEvxd0dcd2dmAgnzsJOUsEY9X9T0esYl+XQBD+O8yy8BXgiExkyVXlBLZCKAruuR8FV7uTQ0hZDtXCTmK6dSmZQ1WEoBF3Oe9vwIkmbRkTHgXafxx", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result deleted file mode 100644 index affc996..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8wISnx2xWoeZur8yn/8N\nPykUY2mYyxn1n0mE5WJSo+mclFFSmnN08WCt856AO8PMPuAn9cw0j3qJe0SKTnoM\nYSp+4fBsq6YHOGJvlRATF9SJkSIxwBCYsMT+cf78vzhKRJrXAfJ/LWzV7b5gThHx\nj+Jby+fE/yePi8+Mb39UwYWGEFf+uRxcQIeuDX/VjPNtNKQPuO+HRi67WNXPFoUN\nmFXv1Ymn61S5duvVCxL8XdHXHdnZgIJ87CTlLBGPV/U9HrGJfl0AQ/jvMsvAV4Ih\nMZMlV5QS2QigK7rkfBVe7k0NIWQ7Vwk5iunUpmUNVhKARdznvb8CJJm0ZEx4F2n8\ncQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDzAhKfHbFah5m6vzKf/w0/KRRjaZjLGfWfSYTlYlKj6ZyUUVKac3TxYK3znoA7w8w+4Cf1zDSPeol7RIpOegxhKn7h8Gyrpgc4Ym+VEBMX1ImRIjHAEJiwxP5x/vy/OEpEmtcB8n8tbNXtvmBOEfGP4lvL58T/J4+Lz4xvf1TBhYYQV/65HFxAh64Nf9WM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YlhbRkBL1ryx1LgIvC0TkWR+e6EvAoGBAPku\npHcpi3t2wewmP6f1krxtOLyvVt5RKaRjZ/2gNtzLPXL6ulQR5hufYlLKgyyyf2gJ\nHxVFhCkfRjwVHV8qdIJc+Q4mjnjOeNfvqnzWOlSfZFegyWvOPW7hTX0/jZYGOb4I\n7fzYyUPHnlu73twmshJMTzE1Ju7RdJXyLtg8xpRfAoGBAKjlyELXTWjZfP4Jnd3H\nNHr+gSRGHp5A0RGe9zsdVGNz0xteA/mBR9JB1grJ2K8jsXmDlIMmHskKIPGhJetQ\nmcr9qcRy9Yx1rZ08ZbYa2N9JllV/+hDLeII77jlh3y8CN5Ov81u0ExReaWxQmjXu\nYgODix4TLLboae4Q6+7Rxu/PAoGAOZ04N7kqX/ygb+qUE1Crgde7I51i93pKp5C4\nbaMKrFhtt9UTGfcdfkuG31+lnsMSxEo/npp5KUzq319+cA+P6sh2aXguvu32cO8g\nO0cJK6HDAKPTjpKcD7QWR5xXL1X3KeJErI6vUnWoPsuchsiHqcVtFhKVEujpDPZ3\nMFY1D/8CgYBvv5mBb2kBf2/2JHp3lP/Q6LepEBkZk9dvoEU6/5xLvA5gEXR0MUj8\ng97Z1duGdXD/uEVRuRuOJkk4p8YmSM7t34st3lF06wdJUGcKvmZpp2ee+CdLwESi\nGDCwcP5pcii56TVr09uHITWei4jFm+3Ye3h092dvPyNoEiJOgk2lsg==\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc deleted file mode 100644 index e5b6398..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,1380F5ADA0E0B636860A6BF78D47D6B2 - -ICLCebZN4+91mTQwBy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MQRmoM0RJ626re51IT2ikk -gB4f3Ms1VbB176it2L/zbXUAaxeE7Cbdcp/5058ksbuE0yA7JB+a2vQHFqw8Xxsb -qdKc4m4jkCdvaA5oNnGoG4milYukp1WVCGJeLD7gspTHR5dDYsOQgHvkxu+Ukor+ -0+1yvf8R6pRJWMoV0VvNkuSBUqcx94A+xLaEYCkB78Koum8xlPA1OA7VVkMVjQSk -r6c/iANbNV20IVz1TBpg9J1rQOGisbE43yRkH+aMgHnAnhk+UgK584QOH6eJpGZT -yBwes57P1kgT5VubavoJbeZLL6B70Sn/sKoLzxxruzPKmsmufJNK9klB7lu5f4gj -lvKtuNaiWbux1+fQmU+05nM1WW7s5Nm9MVUCfS5RxUq8SRqC7W17ouHEssW6mJT1 -jHK1xhoxX05X/T0NfdPzbG7S7+DG18Q6jnyHb28LeKLXv33sEUrT5z7+Nx4JS4XM -ZeMzPdRgYJw9vLQSYdksj0cNBb8UpAiG410lICrbPGWJh9d2KzhNKlfk/vLHia1V ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub deleted file mode 100644 index 806ab91..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDHLfm98g0aHjbQJcjbamutwkWTMY426a4IdwGrpAOv806h6wBXNcOj2VJbgeQ2/XkQ0RY78fGrHSacaadGsT9E5sRGyvkr/WtDpBokXrgpP15OvhfTaSMVTcty6qknndpu7P5nmSipdn9fQR9TyNRyAajhn+UINuquGfxyLL30W4IBqSISOcXKc0pScTdMOIOmkxxY+vQFydQpWF0a3TopKKa4b3sQJgqc0MJkREllT6U+0U4+YufoW6zZyMNIS2gxWUlGUiA5XveWSaYIXCaPQmps4WoO9AlrM7z1sTcG5yXn0kEUvTmBYUOUlffiBgXzArt4Pmm8gVklR5UH98y5 diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result deleted file mode 100644 index b4aad7b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxy35vfINGh420CXI22pr\nrcJFkzGONumuCHcBq6QDr/NOoesAVzXDo9lSW4HkNv15ENEWO/Hxqx0mnGmnRrE/\nRObERsr5K/1rQ6QaJF64KT9eTr4X02kjFU3LcuqpJ53abuz+Z5koqXZ/X0EfU8jU\ncgGo4Z/lCDbqrhn8ciy99FuCAakiEjnFynNKUnE3TDiDppMcWPr0BcnUKVhdGt06\nKSimuG97ECYKnNDCZERJZU+lPtFOPmLn6Fus2cjDSEtoMVlJRlIgOV73lkmmCFwm\nj0JqbOFqDvQJazO89bE3Bucl59JBFL05gWFDlJX34gYF8wK7eD5pvIFZJUeVB/fM\nuQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDHLfm98g0aHjbQJcjbamutwkWTMY426a4IdwGrpAOv806h6wBXNcOj2VJbgeQ2/XkQ0RY78fGrHSacaadGsT9E5sRGyvkr/WtDpBokXrgpP15OvhfTaSMVTcty6qknndpu7P5nmSipdn9fQR9TyNRyAajhn+UINuquGfxyLL30W4IBqSISOcXKc0pScTdMOIOmkxxY+vQFydQpWF0a3TopKKa4b3sQJgqc0MJkREllT6U+0U4+YufoW6zZyMNIS2gxWUlGUiA5XveWSaYIXCaPQmps4WoO9AlrM7z1sTcG5yXn0kEUvTmBYUOUlffiBgXzArt4Pmm8gVklR5UH98y5", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result deleted file mode 100644 index fddff0f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxy35vfINGh420CXI22pr\nrcJFkzGONumuCHcBq6QDr/NOoesAVzXDo9lSW4HkNv15ENEWO/Hxqx0mnGmnRrE/\nRObERsr5K/1rQ6QaJF64KT9eTr4X02kjFU3LcuqpJ53abuz+Z5koqXZ/X0EfU8jU\ncgGo4Z/lCDbqrhn8ciy99FuCAakiEjnFynNKUnE3TDiDppMcWPr0BcnUKVhdGt06\nKSimuG97ECYKnNDCZERJZU+lPtFOPmLn6Fus2cjDSEtoMVlJRlIgOV73lkmmCFwm\nj0JqbOFqDvQJazO89bE3Bucl59JBFL05gWFDlJX34gYF8wK7eD5pvIFZJUeVB/fM\nuQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDHLfm98g0aHjbQJcjbamutwkWTMY426a4IdwGrpAOv806h6wBXNcOj2VJbgeQ2/XkQ0RY78fGrHSacaadGsT9E5sRGyvkr/WtDpBokXrgpP15OvhfTaSMVTcty6qknndpu7P5nmSipdn9fQR9TyNRyAajhn+UINuquGfxyLL30W4IBqSISOcXKc0pScTdMOIOmkxxY+vQFydQpWF0a3TopKKa4b3sQJgqc0MJkREllT6U+0U4+YufoW6zZyMNIS2gxWUlGUiA5XveWSaYIXCaPQmps4WoO9AlrM7z1sTcG5yXn0kEUvTmBYUOUlffiBgXzArt4Pmm8gVklR5UH98y5", - "private": "-----BEGIN RSA PRIVATE KE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CWAcyKn8jBh1cDo5VMCgYBe3iMQnjnI9YCK2wb/LZ6o\n6Aqj7HK+7k44gUYN7vXtbwEzVTWmj/tN9DryL9kAI7IIhc+i1kPxnrkGFK3v7wJv\njSRzz/rH/SS9YU3BSQmZgNgLHhd7Rq4lhid4Xt/PR61HFDCd9gj8FyvTcMFUrD4x\nxqwLx92jL49OGs/rFueXPwKBgBi46jJQ/sCTj4/wc2AXVqfT+nKa8yedK/oNhX3Y\n7pHfy2wc4jimt1JzDSza6V6JahbxR1agGv0L6j7nkt9e7UgDQUEbfRDYVpFfEAnY\nhEC1MRIDRNV3MIOpilkwOoo5WF+mcV5f2C3ouqjcFgkxTZmiHWswkYeXb4g9owqi\n2wG5AoGAb6/btpj3Ql+qYXRUH/cWPlLeFbKiGaAJ+Kn5RwlEW8D//FjKuV7fL7BN\nhvaDJUpwP9klNRny3IK6FWuFI0KDup0nyrIbS07h2rOCl/+g2erDuS5sofpu2zWU\nZDArpSmpU9EF6S8CvbbZmYvWzYUhYD/sEqIR+KSowNM4PA7g7fwKCgoKCgoKCgoK\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 deleted file mode 100644 index ceed070..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +++ /dev/null @@ -1,54 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-256-CBC,5C3291414FA514EE9647898A2D5315FD - -PaIGvR7qnyhxjz7RI4YEeua59B0XJm6cTW6xv2tbSVIC/njwljgo+UzXJLPUH1gv -suhNs8X+U9n0aCME6vFQvSJcloo6B1NLhGL1DVNhMAiGu+byCSJtq4cTFR5+7YUQ -HGB0a5vGBtHhL86TBeaBcKYfgCE4jo6/FAvzfk/eyy3S/oHXjMM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eNAK0USG/h/L -TRop17tZjsg2O6R9/aS0SnyANBJ8xgxRAneWuX6ry7t9IDYOH1Ybcn4riLe+tgCM -YPpxTOCUw49dqdkTU6/n2vEXXIRPXIefxBhIk1bKelX/owIwe+3kNSL96HzEDvI9 -GwaLRxNgMLi5diI3yJmevantJJWIKUFhz3ud2viaSWNWdAvfVmEcb7APs67cJAr9 -4oKnhF4TuD2oowFnH3nykczXRqAqHn+N/XynH0QJrQDJYwnYWH/+5YFWaYwHACSK -ppOnWNqQ28zjA7w5GLI//rHRT0NBbFbVF7s0TQlBu0Rukc042eW692BX/2qVSCpZ -8aVjhBFFbnt4YmRSYlj/X7ICnddWqHSiRNy5RMokdMlZD1ELxYf2XkkZionTlT/E -hHSsA2c4HgP5Ep9svM7EWtFO7Melk2vjgXZxyELbLPZUQuYImuK2ziKqL05YH/lc -/yfAdXOKLWjrUgVBk8r6QqoAWP0iCTZDOmB7IwVu9nLClpnJDfT3kRrai2GIpg/D -1+eBAcr6aoRfpLTduW3EAit7SNzLZSkcBvaLkkqJ3tCPTq9GR05DzOaTGCf+vyve -kRNdTMSX5E6IH3xomKTIPZrEgOMEJpdsJ4wBCt2ginYZvHOFsn+YiLL212+rLOTH -qqSKZb0O5lxgQNjl62PJ9bzDEJkiuUinz83OlLAe7fSZiT3wwKG2x8PsZugRSk6K -txDqENJGzcDsX/MLNYdy6y2MnAWRYKNsmp0luX5Exw7L8ls8jUAMnd0DS0RFB0gN -14UzNa+ZO35Xr4vj8n2URnX9O2vs+A9jcDQU7TOp1/ejq3ISATrIAjeyqUHNZ+Xq ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub deleted file mode 100644 index 0df674a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDOHBVYZ041e+MqbjY+oSRiNNO1nDK1l0P6blyAyi4gwWfEOGSkqBZr+vCGnSj3/BNWsCcECbsG2TBMkoxCmXLc32rgQRz76/vON0gRaAzm+oi4N1hSSN7S/xX3XEwkH5OM/g9WKJvzerGejIExT9C6jzCvznlRdSTnntJrgwuf8ubyOfffXht66X/klC5+XeDI8SORiIr/E7q8QUpjcYYjgRgJHTjjh47xDGQOkcL+ceZb1/ufbU+4r7m8Ume/+fQuOTXcD13yKd1Na7auXMHL8Orh8YHvgwbFCVPOFDDEyReNgLLEaGGHJOuWaf55N+7J4CSDRkRqjz1tFqdqqHwdRr0/pJP77mjEe89Cx4iu+BDrT72/SPKo5bwDoXBa2TxSdoVHT9idjsUPDfwshD4eHtwyhrZkEiNY8Qp+F57I9MSgRT62zdO/vZ5wzEYDJC3DBXPw3owvpGdJEjSOhTD0rOFctNs/dKlwAXnU6QUAE1qgd9P+O3GIhYiPkrw3XsbF39VeouroYIbljv4KyDb+wQMk2U2wzUE/ZV/AVjV0OK/3colr43uxEhl6D48pWejzpQ6DMFKuL5pcxzZzIlBVmwwNsNb3DoWQ+a1gepyimp1ocUlv28JPqMMiarm/Kka86KY+fzcHUUPQXpz8R4edOLA2hQSudYdTcNmcAOpwMw== diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result deleted file mode 100644 index 3f23304..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +++ /dev/null @@ -1,6 +0,0 @@ -{ "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAzhwVWGdONXvjKm42PqEk\nYjTTtZwytZdD+m5cgMouI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cx4iu+BDrT72/SPKo5bwDoXBa2TxSdoVHT9idjsUPDfwshD4eHtwyhrZkEiNY8Qp+F57I9MSgRT62zdO/vZ5wzEYDJC3DBXPw3owvpGdJEjSOhTD0rOFctNs/dKlwAXnU6QUAE1qgd9P+O3GIhYiPkrw3XsbF39VeouroYIbljv4KyDb+wQMk2U2wzUE/ZV/AVjV0OK/3colr43uxEhl6D48pWejzpQ6DMFKuL5pcxzZzIlBVmwwNsNb3DoWQ+a1gepyimp1ocUlv28JPqMMiarm/Kka86KY+fzcHUUPQXpz8R4edOLA2hQSudYdTcNmcAOpwMw==", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result deleted file mode 100644 index 8cf3c91..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +++ /dev/null @@ -1,6 +0,0 @@ -{ "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAzhwVWGdONXvjKm42PqEk\nYjTTtZwytZdD+m5cgMouIMFnxDhkpKgWa/rwhp0o9/wTVrAnBAm7BtkwTJKMQply\n3N9q4EEc++v7zjdIEWgM5vqIuDdYUkje0v8V91xMJB+TjP4PViib83qxnoyBMU/Q\nuo8wr855UXUk557Sa4MLn/Lm8jn3314beul/5JQufl3gyPEjkYiK/xO6vEFKY3GG\nI4EYCR0444eO8QxkDpHC/nHmW9f7n21PuK+5vFJnv/n0Ljk13A9d8indTWu2rlzB\ny/Dq4fGB74MGxQlTzhQwxMkXjYCyxGhhhyTrlmn+eTfuyeAkg0ZEao89bRanaqh8\nHUa9P6ST++5oxHvPQseIrvgQ60+9v0jyqOW8A6FwWtk8UnaFR0/YnY7FDw38LIQ+\nHh7cMoa2ZBIjWPEKfheeyPTE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ssh2/test/fixtures/keyParser/ppk_dsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc deleted file mode 100644 index 915508b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +++ /dev/null @@ -1,17 +0,0 @@ -PuTTY-User-Key-File-2: ssh-dss -Encryption: aes256-cbc -Comment: dsa-key-20141202 -Public-Lines: 10 -AAAAB3NzaC1kc3MAAACBAJn2I8YefRo3BsEeinQt8KQ4cEyArAs7Y/W733oRSYOI -zWF1Ju124ysKrmg2okv+05CYcjV3Yp4AzQeomYAlgmB/7xCEnWaEnxCwAxmrrJMm -PrkwNjHOIi7yM5QOE90IM/Q+IJA4EPBfSb+Xr8fYhrp53KNHVSnc2KkOqpo2FsIj -AAAAFQC4NlP50GqyUqq2B82Vh/w5j3TzwQAAAIAeSGom9LLNdzcwCHnGfxKNnEz3 -55KITADTxiIpBvnQW+eDHwQvIw6V2Oc73bKCu5ZirZmIMW5w6KjQVwkuQBoF9Koq -/2u6VeevtL9pD6TBzSLMVw5pV3PmE4/C/eLiaUxZLIHdbzpqPkAvAUBrXKkj0ijz -cNzCp1fuF8H0pvR8yQAAAIAmvV+kqWhUgDYwNNz1qDaoS8XdsOponutZ/0stRQ66 -mKAy8kNVNNQ6oUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666WgnxB/Ud4GAx -/BPQTghOJJOL00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2lTh7ntrli8mCk -5g== -Private-Lines: 1 -BytvbK+jNyMjiVxCO5lcE4YbW7q293oC+LZjkZ8Ajlw= -Private-MAC: c3da536ea28851fc32d5d1ff01498c8fcebc1170 diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result deleted file mode 100644 index 68edda7..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "dsa-key-20141202", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtjCCASsGByqGSM44BAEwggEeAoGBAJn2I8YefRo3BsEeinQt8KQ4cEyArAs7\nY/W733oRSYOIzWF1Ju124ysKrmg2okv+05CYcjV3Yp4AzQeomYAlgmB/7xCEnWaE\nnxCwAxmrrJMmPrkwNjHOIi7yM5QOE90IM/Q+IJA4EPBfSb+Xr8fYhrp53KNHVSnc\n2KkOqpo2FsIjAhUAuDZT+dBqslKqtgfNlYf8OY9088ECgYAeSGom9LLNdzcwCHnG\nfxKNnEz355KITADTxiIpBvnQW+eDHwQvIw6V2Oc73bKCu5ZirZmIMW5w6KjQVwku\nQBoF9Koq/2u6VeevtL9pD6TBzSLMVw5pV3PmE4/C/eLiaUxZLIHdbzpqPkAvAUBr\nXKkj0ijzcNzCp1fuF8H0pvR8yQOBhAACgYAmvV+kqWhUgDYwNNz1qDaoS8XdsOpo\nnutZ/0stRQ66mKAy8kNVNNQ6oUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666\nWgnxB/Ud4GAx/BPQTghOJJOL00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2l\nTh7ntrli8mCk5g==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAJn2I8YefRo3BsEeinQt8KQ4cEyArAs7Y/W733oRSYOIzWF1Ju124ysKrmg2okv+05CYcjV3Yp4AzQeomYAlgmB/7xCEnWaEnxCwAxmrrJMmPrkwNjHOIi7yM5QOE90IM/Q+IJA4EPBfSb+Xr8fYhrp53KNHVSnc2KkOqpo2FsIjAAAAFQC4NlP50GqyUqq2B82Vh/w5j3TzwQAAAIAeSGom9LLNdzcwCHnGfxKNnEz355KITADTxiIpBvnQW+eDHwQvIw6V2Oc73bKCu5ZirZmIMW5w6KjQVwkuQBoF9Koq/2u6VeevtL9pD6TBzSLMVw5pV3PmE4/C/eLiaUxZLIHdbzpqPkAvAUBrXKkj0ijzcNzCp1fuF8H0pvR8yQAAAIAmvV+kqWhUgDYwNNz1qDaoS8XdsOponutZ/0stRQ66mKAy8kNVNNQ6oUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666WgnxB/Ud4GAx/BPQTghOJJOL00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2lTh7ntrli8mCk5g==", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBugIBAAKBgQCZ9iPGHn0aNwbBHop0LfCkOHBMgKwLO2P1u996EUmDiM1hdSbt\nduMrCq5oNqJL/tOQmHI1d2KeAM0HqJmAJYJgf+8QhJ1mhJ8QsAMZq6yTJj65MDYx\nziIu8jOUDhPdCDP0PiCQOBDwX0m/l6/H2Ia6edyjR1Up3NipDqqaNhbCIwIVALg2\nU/nQarJSqrYHzZWH/DmPdPPBAoGAHkhqJvSyzXc3MAh5xn8SjZxM9+eSiEwA08Yi\nKQb50Fvngx8ELyMOldjnO92ygruWYq2ZiDFucOio0FcJLkAaBfSqKv9rulXnr7S/\naQ+kwc0izFcOaVdz5hOPwv3i4mlMWSyB3W86aj5ALwFAa1ypI9Io83DcwqdX7hfB\n9Kb0fMkCgYAmvV+kqWhUgDYwNNz1qDaoS8XdsOponutZ/0stRQ66mKAy8kNVNNQ6\noUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666WgnxB/Ud4GAx/BPQTghOJJOL\n00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2lTh7ntrli8mCk5gIUCJZKAMAz\nkyr2vl2Pe48adi8Vs9s=\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa deleted file mode 100644 index 4504f18..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +++ /dev/null @@ -1,26 +0,0 @@ -PuTTY-User-Key-File-2: ssh-rsa -Encryption: none -Comment: rsa-key-20150522 -Public-Lines: 6 -AAAAB3NzaC1yc2EAAAABJQAAAQB1quqP0rhl78NOLD4lj+1x5FGAqZ3aqo6GiEPz -KOaQmy86FuJMK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47YrynCOcJEEnpqvbArc8M -xMWuUnTUMrjvokGDOBBiQu4UAE4bybpgXkNHJfbrcDVgivmv3Ikn8PVIZ1rLBMLZ -6Lzn0rjPjFD0X4WqsAJW2SFiZnsjMZtVL2TWadNTyyfjjm2NCRBvd32VLohkSe9Q -BZBD6MW8YQyBKUnEF/7WNY0eehDVrfx1YqPOV1bDwFUhRaAYpLDLDR0KCAPvx7qb -8G5Cq0TIBsEr3H8ztNRcOTQoaKgn0T18M7cyS4ykoNLYW4Zx -Private-Lines: 14 -AAABACyF3DZraF3sBLXLjSL4MFSblHXfUHxAiPSiQzlpa/9dUCPRTrUJddzOgHZU -yJtcXU9mLm4VDRe7wZyxbSs6Hd5WZUGzIuLLEUH8k4hKdE/MLDSdkhV7qhX5iaij -tAeRaammRoVUGXTd7rnzGx2cXnnkvkZ22VmqkQ6MLg1DTmWNfOO9cdwFGdQawf/n -yUV0nTkWsHXy5Qrozq9wRFk8eyw+pFllxqavsNftZX8VDiQt27JLZPTU4LGkH660 -3gq1KhNS/l05TlXnMZGjlcPN8UEaBzmCWRezhJSttjs5Kgp1K3yDf4ozMR/HWOCj -Jq8fd3VIgli6ML8yjr/c0A0T9MUAAACBAL1/byxHiCvY/2C+/L5T+ZZq13jdZuYK -MmOFaNITgEdNGWSIFYRzhLKGXj7awQWOIW6chj470GNOfQjFL1TvXhbwfqW6esDa -kETOYQPYQHZijABcn7uurMUm/bu5x/z9gYkAfniOCI5vmvMvJ09JcZ0iUmFWDZZY -fAutBvrt+n/vAAAAgQCe9jrA51wn1/wzKmWF+2+OWFUG9usheIcEbHB8mxLguLfU -+x4i+2vLo0FtXEPAw+Bt7Tge4t0m6USiVZXtW/QKsh0kMj4mNVHFz+XXw4l1QOYv -n5TjnLepiP7majXv4GHI2eOcHkyly4sIkj4jNLYqvT86hMxW4IC+jtJEWhn/nwAA -AIEAlJ8cExu2WrWukTDJQHrVegtvdJUhNjol2wLucPuWwSxKuB8FHYwaPRYRkf3d -DkZ53hhjJZ0BVkAaQ28uqM09xKD+q1H4/r0nnbtlV4uHLl3cCD5mGrH8I/iDPJX4 -fFIqCa0+n1D6RzvDqs1QIu+PGSp0K6vHOOS5fP0ZpuT025E= -Private-MAC: 4ca26008c85b901f4d2766b0924c25e527678d7e diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result deleted file mode 100644 index 9ac4d2f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "rsa-key-20150522", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBHzANBgkqhkiG9w0BAQEFAAOCAQwAMIIBBwKCAQB1quqP0rhl78NOLD4lj+1x\n5FGAqZ3aqo6GiEPzKOaQmy86FuJMK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47Yryn\nCOcJEEnpqvbArc8MxMWuUnTUMrjvokGDOBBiQu4UAE4bybpgXkNHJfbrcDVgivmv\n3Ikn8PVIZ1rLBMLZ6Lzn0rjPjFD0X4WqsAJW2SFiZnsjMZtVL2TWadNTyyfjjm2N\nCRBvd32VLohkSe9QBZBD6MW8YQyBKUnEF/7WNY0eehDVrfx1YqPOV1bDwFUhRaAY\npLDLDR0KCAPvx7qb8G5Cq0TIBsEr3H8ztNRcOTQoaKgn0T18M7cyS4ykoNLYW4Zx\nAgEl\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAABJQAAAQB1quqP0rhl78NOLD4lj+1x5FGAqZ3aq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yjr/c0A0T\n9MUCgYEAvX9vLEeIK9j/YL78vlP5lmrXeN1m5goyY4Vo0hOAR00ZZIgVhHOEsoZe\nPtrBBY4hbpyGPjvQY059CMUvVO9eFvB+pbp6wNqQRM5hA9hAdmKMAFyfu66sxSb9\nu7nH/P2BiQB+eI4Ijm+a8y8nT0lxnSJSYVYNllh8C60G+u36f+8CgYEAnvY6wOdc\nJ9f8MyplhftvjlhVBvbrIXiHBGxwfJsS4Li31PseIvtry6NBbVxDwMPgbe04HuLd\nJulEolWV7Vv0CrIdJDI+JjVRxc/l18OJdUDmL5+U45y3qYj+5mo17+BhyNnjnB5M\npcuLCJI+IzS2Kr0/OoTMVuCAvo7SRFoZ/58CgYBM0sw0i7O+v8F6P5blYFBtaZWf\ns7QYEfjAkAfmdpvJ4Px03Tkn284DL439zk5AhbqGydWO2fqJH9HTH4HkKbCF1x6W\nNtfRpLcHIzwWUMAv/nAb0oXyJDg0QD1Z8V7qBehn+UgHXCz7eVp+Q4x6FtsIWgW4\nwgWCI99DAPT98cZrNwKBgBEvYEw0sAROs3snLZHxqzH7tipENRhgDpixxvi20ZvA\n8Ud1GAPIJ1RJACd/mJ83xTxQ/yXvAybNHC05r1fuQ+V7ChHAPhH37SokUDMAYeMp\nnFgs7YBj+C4A+PZQq+KUzE0Qovwe84eLoFP0ImSrwKqsrOO7VFxrTDBGyp+bCbrF\nAoGBAJSfHBMbtlq1rpEwyUB61XoLb3SVITY6JdsC7nD7lsEsSrgfBR2MGj0WEZH9\n3Q5Ged4YYyWdAVZAGkNvLqjNPcSg/qtR+P69J527ZVeLhy5d3Ag+Zhqx/CP4gzyV\n+HxSKgmtPp9Q+kc7w6rNUCLvjxkqdCurxzjkuXz9Gabk9NuR\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc deleted file mode 100644 index 6f2f7f7..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +++ /dev/null @@ -1,18 +0,0 @@ -PuTTY-User-Key-File-2: ssh-rsa -Encryption: aes256-cbc -Comment: rsa-key-20141119 -Public-Lines: 4 -AAAAB3NzaC1yc2EAAAABJQAAAIBrBWETAVAyJmuNG53jwTNDlbIcH5lrEvcx6lx5 -bM6EKg0XmOIH96VqUjS7eRRTTD9lpBA8hYhkrOjOx93/JWB/pcVN8/B3DYHshT9O -BW1DCkrNwut2pbJ2oZOBirhhAr+xqWFr3551FqbzaCIXpOKubr4EcIwCipBl6PxL -USfHgw== -Private-Lines: 8 -8O3NrBePR4+4RHHys8wrRKCmgx3Gsdz1cKoRJJDgnnrQxuAxBTVUlVTC2vzSOXrP -jlKdRP9DbtrL5YF8g9HkMPpzzTdgpiEAGikpIc+L0sJhN+S9VvMoXRRKqyuB7o1C -xZhAeRaZ68izdUUbFd7ajUwBNpGoFppOznGXyf/3/Ao9FfoTKReZzeBd/e2/JFhc -nsYkSbtWfKQBVXF1Fhr10UwRWSMaVJSDkcSuk8ghICoKBBCgRBnZFap0SR77oIJh -DKgmNFktoKzEqh111vYPhQyEEyGNxpD0aEPaGUJEjPEd3C5a46n7mIiqrNX7QJoo -xxZtkueGdXWaoe5mBf1tFc+nCA1l72nUlghJZooQhnO9NPpieu6NNZ8X+tFQ1Rq/ -xvOZHzpDOOeOgWdV7oAmRDbDjYPh0H67z2OKCFaP0Z9kgmnwqV2IJvTDrexj1VwY -6kFaPldnK+ohXl37oVIlWA== -Private-MAC: 9d09a15a122e48955682ba969d33c75ba8e4be2c diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result deleted file mode 100644 index f9ff958..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "rsa-key-20141119", - "public": "-----BEGIN PUBLIC KEY-----\nMIGcMA0GCSqGSIb3DQEBAQUAA4GKADCBhgKBgGsFYRMBUDIma40bnePBM0OVshwf\nmWsS9zHqXHlszoQqDReY4gf3pWpSNLt5FFNMP2WkEDyFiGSs6M7H3f8lYH+lxU3z\n8HcNgeyFP04FbUMKSs3C63alsnahk4GKuGECv7GpYWvfnnUWpvNoIhek4q5uvgRw\njAKKkGXo/EtRJ8eDAgEl\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAABJQAAAIBrBWETAVAyJmuNG53jwTNDlbIcH5lrEvcx6lx5bM6EKg0XmOIH96VqUjS7eRRTTD9lpBA8hYhkrOjOx93/JWB/pcVN8/B3DYHshT9OBW1DCkrNwut2pbJ2oZOBirhhAr+xqWFr3551FqbzaCIXpOKubr4EcIwCipBl6PxLUSfHgw==", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIICWQIBAAKBgGsFYRMBUDIma40bnePBM0OVshwfmWsS9zHqXHlszoQqDReY4gf3\npWpSNLt5FFNMP2WkEDyFiGSs6M7H3f8lYH+lxU3z8HcNgeyFP04FbUMKSs3C63al\nsnahk4GKuGECv7GpYWvfnnUWpvNoIhek4q5uvgRwjAKKkGXo/EtRJ8eDAgElAoGA\nU+GfHLvXEozQ1mHA8MfcEmCShL7SMVQN2wPL8HfgImYl7+aHpWE8de1nmdtwy6p2\n4PY2PUYQ9PY57i3zL8NZd8WQ7Rg0RBHDlndaFeF4Ef0uLboqYd/xN0rzfy55z7hW\nOL+8VhoxTrBUvveOhZwBPkOeHfxmkVz3xbbrg3kNlo0CQQDJYPKtCs/l46KJmN3l\nUANdI4QIuWQ+Zllz7p94FfdotnkvqG++Bp1wOqJSCih6UViwLfvpNZtGMCtk46WN\nhc0zAkEAiAyN4WUs/0x4WovG956J1A+uSEKeWzuqfpGGbWgZ9XfnPnk+1Al8FOW1\ntu9WWrMPIavQnZW/dXxhkeNWTH78cQJBALkM+qzZgMVpZO0ksDqA4H8Zt5lQafQm\nsxCWFf+le5CnraFqWNghwRsFcpCTtn486bamy89hsUdqiL2S6ygaFoECQFDk3r1e\nwM8mjMA3b2LM+AGMyH3+GPf59qwfLVXPMgeTZubgTt7w4f6WbAvoQS8Crw0aDVbH\nvfLUVbCwr9p1BM0CQFSBjCa/fzeICVkPFBaKQUmXjQ3IcPTOr90mSAiPnAAppSwT\nj5SYSfE9rSVb+EhQ0hk2VKWIfocNHBD1MAN9zb4=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub deleted file mode 100644 index 3bfd6e8..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +++ /dev/null @@ -1,9 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: "2048-bit RSA" -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result deleted file mode 100644 index fcc0553..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "2048-bit RSA", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub deleted file mode 100644 index e42f5c1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +++ /dev/null @@ -1,10 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: 2048-bit RSA -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result deleted file mode 100644 index fcc0553..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "2048-bit RSA", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub deleted file mode 100644 index 24a107b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +++ /dev/null @@ -1,11 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: this is a special \ -multi-line comment\ - how cool is that not? -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result deleted file mode 100644 index 25dae67..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "this is a special multi-line comment how cool is that not?", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub deleted file mode 100644 index 0454a85..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +++ /dev/null @@ -1,11 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: "this is a special \ -multi-line comment\ - how cool is that not?" -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result deleted file mode 100644 index 25dae67..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "this is a special multi-line comment how cool is that not?", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub deleted file mode 100644 index 14608c1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +++ /dev/null @@ -1,8 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result deleted file mode 100644 index a61d779..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub deleted file mode 100644 index 24a2261..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +++ /dev/null @@ -1,13 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Subject: "nodejs" -x-foo: something\ -completely\ -different -Comment: "Foo bar baz" -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result deleted file mode 100644 index ed7a4f5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "Foo bar baz", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/openssh_new_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/openssh_new_rsa deleted file mode 100644 index ccded2a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/openssh_new_rsa +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn -NhAAAAAwEAAQAAAQEA4q6eZdx7LYh46PcZNcS3CnO7GuYsEJZeTj5LQSgp21IyTelaBPpr -ijnMwKa+pLQt5TEobpKFFNecPdT6oPoOKKMe6oH/pX0BNyAE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2K/JQVlzJNuINsw+DNjn4M17Z25q0LPmReRWL0nRc2w6W/hmQ/Jmqz6w8Qc4+xpeqS -/HG5feliVnAAAAgQD90a+5Ky3o/2YtueqRf/3dKoiMgGB7JAOzye4dDKGABSlWuQ4N4xEI -CW5MSTp7i/uobTF/tyFO3tTSyb5b2Xwbn/kLO0vgvFCdUGR2BQfN3mcT92T0Gn3JDF3Wym -i2mgU6qnPf+eu+RKZQ9IiyNGny61ROUQa0R0z0pgiAfA89xwAAAIEA5KE9i6hHmigJwfD7 -/AGI4ujyWIVpNyrTdXG3HAPhsdoFuG5ggHggrPuuBF9wNcosrhL20VNOQGHg15gWZIVudu -0qxky4ivQs67Sk9XUjuvTnf+VubM51rIsmh4atKJFSSZo78DEcTRt8aXLrSNvGQ4WPRweM -2Z0YGfMMDM9KJKUAAAASbmV3IG9wZW5zc2ggZm9ybWF0AQ== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_dsa_key b/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_dsa_key deleted file mode 100644 index 5448947..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -MIIBuwIBAAKBgQDEK+daQ7RuajwxkmBmogb0iUSi/w2RYKuvC2EiviBu3S2s9Bfq -gROKscAnURrxpTOa+iYeI7hRzfuX0qFmnFwXIjKJBjqBdg9r76UR5UNytnWQkJ5x -lxsZThMeAMw38SvmRMw15kkgxycKGqu4yvNLGyVwN02bPVjLcEVLWLCM1wIVAK50 -5JqF0nmGXFkcmNtxR24/mNXTAoGBAIc2p8C8b08OTQPmfZI+Wq8a+CuEr5R36bMW -TAs5etqmO2aVo5zvR0MnTjoS2ZDbuznDG9RiSuIB+ivr/daEwi+K+Ha8pZfYjXCG -ldzvmr5I4x8rkH3zyn7BADnc+/q3pa8AnZvTme5eNsxn1Pu/rmC/8KKnhmzRggqP -N8ORhoQQAoGAMCvoMcsDAui2d/WVpgHZZEFlxfbf4dPUPYb5zf2xOiMG9OK+Cbv3 -NaLZwk/Hd2g4L3nwTKDASxfmRcrbuaOg/d7aDjQ2mJz18Js4IjY34QpgLspGCNX/ -6rJSQ+ov1Z2Etr95N4Tzm3qpxW5BH9TTgaC/ntb9NRqIzNPCvAHXmlcCFBxgZpyb -4GUgmqhTOMtmBkJ7QpL9 ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key b/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key deleted file mode 100644 index 0476442..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEICrdbIIYmW/XTK9hxaQZZ56IGwG0NhqD2eppYUJNZsECoAoGCCqGSM49 -AwEHoUQDQgAEa+MuLv++3ft5HPFIsM2hQnmHPF12q08/MaHoGud4yqp3evyomjZN -xbsSb39fv8t6XX1u1rm5oHQcBV5Mqomaeg== ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_rsa_key b/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_rsa_key deleted file mode 100644 index 9c2cc6f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXAIBAAKBgQC57UB/5H0M+t+mopksrltCCIXghryzofJjau+8tuMT9CG6ta3S -O9aKApJUUG/xtc88giVhB7HFABX/oob+jrkSthR8s/whULC8E+GhvOBjHydRUZIs -aPYOMBb42HcbOsgq3li/hwOcDk0vY00hZDKCum9BgvRAb7dPEkw2dmiCQQIDAQAB -AoGAMG+HOwoaLbR5aR64yrQNYBF6Vvii1iUdURr9o2r9kygpVUuZIcim5kMvPbnK -v+w+NaQt+q4XeJvCH1uG0W/69FwnphfaOVmCCUtsoJ6sU3fWr9x59MtKL2Llh8xR -50lz6R+eDXoYRDq245hG9BFn/bu0vtqQqx06mlZJcjaRocECQQDjdYFmr+DSww3x -VNx0G0DUkaQZZ+iqZiT3Zund2pcBB4aLiewOrqj0GFct4+YNzgxIXPejmS0eSokN -N2lC3NxZAkEA0UGjN5TG5/LEK3zcYtx2kpXryenrYORo1n2L/WPMZ0mjLQyd4LJr -ibfgVUfwX/kV3vgGYLwjpgcaTiMsecv4KQJAYMmMgZSPdz+WvD1e/WznXkyG5mSn -xXJngnrhQw0TulVodBIBR5IcxJli510VdIRcB6K/oXa5ky0mOmB8wv3WKQJBAKEF -PxE//KbzWhyUogm4180IbD4dMDCI0ltqlFRRfTJlqZi6wqnq4XFB+u/kwYU4aKoA -dPfvDgduI8HIsyqt17ECQDI/HC8PiYsDIOyVpQuQdIAsbGmoavK7X1MVEWR2nj9t -7BbUVFSnVKynL4TWIJZ6xP8WQwkDBQc5WjognHDaUTQ= ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/test-exec.js b/reverse_engineering/node_modules/ssh2/test/test-exec.js deleted file mode 100644 index 86b2e31..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-exec.js +++ /dev/null @@ -1,578 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - mustCall, - mustCallAtLeast, - setupSimple, -} = require('./common.js'); - -const DEBUG = false; - -const setup = setupSimple.bind(undefined, DEBUG); - -{ - const { client, server } = setup('Simple exec()'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.on('data', mustCallAtLeast((d) => { - out += d; - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Simple exec() (exit signal)'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - assert.throws(() => stream.exit('SIGFAKE')); - stream.exit('SIGKILL'); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ null, 'SIGKILL', false, '' ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.on('data', mustCallAtLeast((d) => { - out += d; - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Simple exec() (exit signal -- no "SIG")'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - assert.throws(() => stream.exit('FAKE')); - stream.exit('KILL'); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ null, 'SIGKILL', false, '' ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.on('data', mustCallAtLeast((d) => { - out += d; - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Exec with signal()'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let stream; - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - })).on('signal', mustCall((accept, reject, info) => { - assert(info.name === 'INT', `Wrong client signal name: ${info.name}`); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - const sendSignal = (() => { - let sent = false; - return () => { - if (sent) - return; - sent = true; - assert.throws(() => stream.signal('FAKE')); - assert.throws(() => stream.signal('SIGFAKE')); - stream.signal('SIGINT'); - }; - })(); - stream.on('data', mustCallAtLeast((d) => { - out += d; - sendSignal(); - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Exec with signal() -- no "SIG"'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let stream; - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - })).on('signal', mustCall((accept, reject, info) => { - assert(info.name === 'INT', `Wrong client signal name: ${info.name}`); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - const sendSignal = (() => { - let sent = false; - return () => { - if (sent) - return; - sent = true; - stream.signal('INT'); - }; - })(); - stream.on('data', mustCallAtLeast((d) => { - out += d; - sendSignal(); - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Exec with environment set'); - - const env = { SSH2NODETEST: 'foo' }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('env', mustCall((accept, reject, info) => { - accept && accept(); - assert(info.key === Object.keys(env)[0], - 'Wrong env key'); - assert(info.val === Object.values(env)[0], - 'Wrong env value'); - })).on('exec', mustCall((accept, reject, info) => { - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', { env }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup('Exec with setWindow()'); - - const dimensions = { - rows: 60, - cols: 115, - height: 480, - width: 640, - }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('window-change', mustCall((accept, reject, info) => { - accept && accept(); - assert.deepStrictEqual(info, dimensions, 'Wrong dimensions'); - })).on('exec', mustCall((accept, reject, info) => { - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.setWindow(...Object.values(dimensions)); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup('Exec with pty set'); - - const pty = { - rows: 2, - cols: 4, - width: 0, - height: 0, - term: 'vt220', - modes: {}, - }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawPty = false; - accept().on('pty', mustCall((accept, reject, info) => { - assert.deepStrictEqual(info, pty, 'Wrong pty info'); - sawPty = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawPty, 'Expected pty to be set up'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', { pty }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup('Exec with X11 forwarding'); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawX11 = false; - accept().on('x11', mustCall((accept, reject, info) => { - assert.strictEqual(info.single, - false, - `Wrong x11 single: ${info.single}`); - assert.strictEqual(info.screen, - 0, - `Wrong x11 screen: ${info.screen}`); - assert.strictEqual(info.protocol, - 'MIT-MAGIC-COOKIE-1', - `Wrong x11 protocol: ${info.protocol}`); - assert(Buffer.isBuffer(info.cookie), 'Expected cookie Buffer'); - assert.strictEqual( - info.cookie.length, - 32, - `Invalid x11 cookie length: ${info.cookie.length}` - ); - sawX11 = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawX11, 'Expected x11 before exec'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - conn.x11('127.0.0.1', 4321, mustCall((err, xstream) => { - assert(!err, `Unexpected x11() error: ${err}`); - xstream.resume(); - xstream.on('end', mustCall(() => { - stream.exit(100); - stream.end(); - conn.end(); - })).end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.on('x11', mustCall((info, accept, reject) => { - assert.strictEqual(info.srcIP, - '127.0.0.1', - `Invalid x11 srcIP: ${info.srcIP}`); - assert.strictEqual(info.srcPort, - 4321, - `Invalid x11 srcPort: ${info.srcPort}`); - accept(); - })).exec('foo --bar', { x11: true }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup( - 'Exec with X11 forwarding (custom X11 settings)' - ); - - const x11 = { - single: true, - screen: 1234, - protocol: 'YUMMY-MAGIC-COOKIE-1', - cookie: '00112233445566778899001122334455', - }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawX11 = false; - accept().on('x11', mustCall((accept, reject, info) => { - assert.strictEqual(info.single, - x11.single, - `Wrong x11 single: ${info.single}`); - assert.strictEqual(info.screen, - x11.screen, - `Wrong x11 screen: ${info.screen}`); - assert.strictEqual(info.protocol, - x11.protocol, - `Wrong x11 protocol: ${info.protocol}`); - assert(Buffer.isBuffer(info.cookie), 'Expected cookie Buffer'); - assert.strictEqual(info.cookie.toString(), - x11.cookie, - `Wrong x11 cookie: ${info.cookie}`); - sawX11 = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawX11, 'Expected x11 before exec'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - conn.x11('127.0.0.1', 4321, mustCall((err, xstream) => { - assert(!err, `Unexpected x11() error: ${err}`); - xstream.resume(); - xstream.on('end', mustCall(() => { - stream.exit(100); - stream.end(); - conn.end(); - })).end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.on('x11', mustCall((info, accept, reject) => { - assert.strictEqual(info.srcIP, - '127.0.0.1', - `Invalid x11 srcIP: ${info.srcIP}`); - assert.strictEqual(info.srcPort, - 4321, - `Invalid x11 srcPort: ${info.srcPort}`); - accept(); - })).exec('foo --bar', { x11 }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-integration-openssh.js b/reverse_engineering/node_modules/ssh2/test/test-integration-openssh.js deleted file mode 100644 index 2baf682..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-integration-openssh.js +++ /dev/null @@ -1,481 +0,0 @@ -// TODO: add more rekey tests that at least include switching from no -// compression to compression and vice versa -'use strict'; - -const assert = require('assert'); -const { spawn, spawnSync } = require('child_process'); -const { chmodSync, readdirSync } = require('fs'); -const { join } = require('path'); -const readline = require('readline'); - -const Server = require('../lib/server.js'); - -const { - fixture, - fixtureKey, - FIXTURES_DIR, - mustCall, - mustCallAtLeast, -} = require('./common.js'); - -const SPAWN_OPTS = { windowsHide: true }; -const CLIENT_TIMEOUT = 5000; - -const debug = false; -const opensshPath = 'ssh'; -let opensshVer; - -// TODO: figure out why this test is failing on Windows -if (process.platform === 'win32') { - console.log('Skipping OpenSSH integration tests on Windows'); - process.exit(0); -} - -// Fix file modes to avoid OpenSSH client complaints about keys' permissions -for (const file of readdirSync(FIXTURES_DIR, { withFileTypes: true })) { - if (file.isFile()) - chmodSync(join(FIXTURES_DIR, file.name), 0o600); -} - -{ - // Get OpenSSH client version first - const { - error, stderr, stdout - } = spawnSync(opensshPath, ['-V'], SPAWN_OPTS); - - if (error) { - console.error('OpenSSH client is required for these tests'); - process.exitCode = 5; - return; - } - - const re = /^OpenSSH_([\d.]+)/; - let m = re.exec(stdout.toString()); - if (!m || !m[1]) { - m = re.exec(stderr.toString()); - if (!m || !m[1]) { - console.error('OpenSSH client is required for these tests'); - process.exitCode = 5; - return; - } - } - - opensshVer = m[1]; - console.log(`Testing with OpenSSH version: ${opensshVer}`); -} - - -// Key-based authentication -[ - { desc: 'RSA user key (old OpenSSH)', - clientKey: fixtureKey('id_rsa') }, - { desc: 'RSA user key (new OpenSSH)', - clientKey: fixtureKey('openssh_new_rsa') }, - { desc: 'DSA user key', - clientKey: fixtureKey('id_dsa') }, - { desc: 'ECDSA user key', - clientKey: fixtureKey('id_ecdsa') }, -].forEach((test) => { - const { desc, clientKey } = test; - const username = 'KeyUser'; - const { server } = setup( - desc, - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); -}); - - -// Different host key types -[ - { desc: 'RSA host key (old OpenSSH)', - hostKey: fixture('id_rsa') }, - { desc: 'RSA host key (new OpenSSH)', - hostKey: fixture('openssh_new_rsa') }, - { desc: 'DSA host key', - hostKey: fixture('ssh_host_dsa_key') }, - { desc: 'ECDSA host key', - hostKey: fixture('ssh_host_ecdsa_key') }, - { desc: 'PPK', - hostKey: fixture('id_rsa.ppk') }, -].forEach((test) => { - const { desc, hostKey } = test; - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - desc, - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ hostKey ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); -}); - - -// Various edge cases -{ - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - 'Server closes stdin too early', - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - debug, - } - ); - - server.on('_child', mustCall((childProc) => { - childProc.stderr.once('data', mustCall((data) => { - childProc.stdin.end(); - })); - childProc.stdin.write('ping'); - })).on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.stdin.on('data', mustCallAtLeast((data) => { - stream.stdout.write('pong on stdout'); - stream.stderr.write('pong on stderr'); - })).on('end', mustCall(() => { - stream.stdout.write('pong on stdout'); - stream.stderr.write('pong on stderr'); - stream.exit(0); - stream.close(); - })); - })); - })); - })); - })); -} -{ - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - 'Rekey', - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - conn.rekey(); - session.on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); -} - - -function setup(title, configs) { - const { - client: clientCfg, - server: serverCfg, - allReady: allReady_, - timeout: timeout_, - debug, - noForceServerReady, - } = configs; - let clientClose = false; - let serverClose = false; - let serverReady = false; - let client; - const msg = (text) => { - return `${title}: ${text}`; - }; - - const timeout = (typeof timeout_ === 'number' - ? timeout_ - : CLIENT_TIMEOUT); - - const allReady = (typeof allReady_ === 'function' ? allReady_ : undefined); - - if (debug) { - serverCfg.debug = (...args) => { - console.log(`[${title}][SERVER]`, ...args); - }; - } - - const serverReadyFn = (noForceServerReady ? onReady : mustCall(onReady)); - const server = new Server(serverCfg); - - server.on('error', onError) - .on('connection', mustCall((conn) => { - conn.on('error', onError) - .on('ready', serverReadyFn); - server.close(); - })) - .on('close', mustCall(onClose)); - - function onError(err) { - const which = (arguments.length >= 3 ? 'client' : 'server'); - assert(false, msg(`Unexpected ${which} error: ${err}`)); - } - - function onReady() { - assert(!serverReady, msg('Received multiple ready events for server')); - serverReady = true; - allReady && allReady(); - } - - function onClose() { - if (arguments.length >= 3) { - assert(!clientClose, msg('Received multiple close events for client')); - clientClose = true; - } else { - assert(!serverClose, msg('Received multiple close events for server')); - serverClose = true; - } - } - - process.nextTick(mustCall(() => { - server.listen(0, 'localhost', mustCall(() => { - const args = [ - '-o', 'UserKnownHostsFile=/dev/null', - '-o', 'StrictHostKeyChecking=no', - '-o', 'CheckHostIP=no', - '-o', 'ConnectTimeout=3', - '-o', 'GlobalKnownHostsFile=/dev/null', - '-o', 'GSSAPIAuthentication=no', - '-o', 'IdentitiesOnly=yes', - '-o', 'BatchMode=yes', - '-o', 'VerifyHostKeyDNS=no', - - '-vvvvvv', - '-T', - '-o', 'KbdInteractiveAuthentication=no', - '-o', 'HostbasedAuthentication=no', - '-o', 'PasswordAuthentication=no', - '-o', 'PubkeyAuthentication=yes', - '-o', 'PreferredAuthentications=publickey' - ]; - - if (clientCfg.privateKeyPath) - args.push('-o', `IdentityFile=${clientCfg.privateKeyPath}`); - - if (!/^[0-6]\./.test(opensshVer)) { - // OpenSSH 7.0+ disables DSS/DSA host (and user) key support by - // default, so we explicitly enable it here - args.push('-o', 'HostKeyAlgorithms=+ssh-dss'); - args.push('-o', 'PubkeyAcceptedKeyTypes=+ssh-dss'); - } - - args.push('-p', server.address().port.toString(), - '-l', clientCfg.username, - 'localhost', - 'uptime'); - - client = spawn(opensshPath, args, SPAWN_OPTS); - server.emit('_child', client); - - if (debug) { - readline.createInterface({ - input: client.stdout - }).on('line', (line) => { - console.log(`[${title}][CLIENT][STDOUT]`, line); - }); - readline.createInterface({ - input: client.stderr - }).on('line', (line) => { - console.error(`[${title}][CLIENT][STDERR]`, line); - }); - } else { - client.stdout.resume(); - client.stderr.resume(); - } - - client.on('error', (err) => { - onError(err, null, null); - }).on('exit', (code) => { - clearTimeout(client.timer); - if (code !== 0) - return onError(new Error(`Non-zero exit code ${code}`), null, null); - onClose(null, null, null); - }); - - client.timer = setTimeout(() => { - assert(false, msg('Client timeout')); - }, timeout); - })); - })); - - return { server }; -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-misc-client-server.js b/reverse_engineering/node_modules/ssh2/test/test-misc-client-server.js deleted file mode 100644 index f875a7d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-misc-client-server.js +++ /dev/null @@ -1,1428 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { createHash } = require('crypto'); -const http = require('http'); -const https = require('https'); -const net = require('net'); -const { Transform } = require('stream'); -const { inspect } = require('util'); - -const Client = require('../lib/client.js'); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = require('../lib/http-agents.js'); -const Server = require('../lib/server.js'); -const { KexInit } = require('../lib/protocol/kex.js'); - -const { - fixture, - mustCall, - mustCallAtLeast, - mustNotCall, - setup: setup_, - setupSimple, -} = require('./common.js'); - -const KEY_RSA_BAD = fixture('bad_rsa_private_key'); -const HOST_RSA_MD5 = '64254520742d3d0792e918f3ce945a64'; -const clientCfg = { username: 'foo', password: 'bar' }; -const serverCfg = { hostKeys: [ fixture('ssh_host_rsa_key') ] }; - -const debug = false; - -const setup = setupSimple.bind(undefined, debug); - - -{ - const { server } = setup_( - 'Verify host fingerprint (sync success, hostHash set)', - { - client: { - ...clientCfg, - hostHash: 'md5', - hostVerifier: mustCall((hash) => { - assert(hash === HOST_RSA_MD5, 'Host fingerprint mismatch'); - return true; - }), - }, - server: serverCfg, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - -{ - const { server } = setup_( - 'Verify host fingerprint (sync success, hostHash not set)', - { - client: { - ...clientCfg, - hostVerifier: mustCall((key) => { - assert(Buffer.isBuffer(key), 'Expected buffer'); - let hash = createHash('md5'); - hash.update(key); - hash = hash.digest('hex'); - assert(hash === HOST_RSA_MD5, 'Host fingerprint mismatch'); - return true; - }), - }, - server: serverCfg, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - -{ - const { server } = setup_( - 'Verify host fingerprint (async success)', - { - client: { - ...clientCfg, - hostVerifier: mustCall((key, cb) => { - assert(Buffer.isBuffer(key), 'Expected buffer'); - let hash = createHash('md5'); - hash.update(key); - hash = hash.digest('hex'); - assert(hash === HOST_RSA_MD5, 'Host fingerprint mismatch'); - process.nextTick(cb, true); - }), - }, - server: serverCfg, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - -{ - const { client, server } = setup_( - 'Verify host fingerprint (sync failure)', - { - client: { - ...clientCfg, - hostVerifier: mustCall((key) => { - return false; - }), - }, - server: serverCfg, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - client.on('ready', mustNotCall()) - .on('error', mustCall((err) => { - assert(/verification failed/.test(err.message), - 'Wrong client error message'); - })); - - server.on('connection', mustCall((conn) => { - conn.removeAllListeners('error'); - - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()) - .on('error', mustCall((err) => { - assert(/KEY_EXCHANGE_FAILED/.test(err.message), - 'Wrong server error message'); - })); - })); -} - -{ - // connect() on connected client - - const clientCfg_ = { ...clientCfg }; - const client = new Client(); - const server = new Server(serverCfg); - - server.listen(0, 'localhost', mustCall(() => { - clientCfg_.host = 'localhost'; - clientCfg_.port = server.address().port; - client.connect(clientCfg_); - })); - - let connections = 0; - server.on('connection', mustCall((conn) => { - if (++connections === 2) - server.close(); - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => {})); - }, 2)).on('close', mustCall(() => {})); - - let reconnect = false; - client.on('ready', mustCall(() => { - if (reconnect) { - client.end(); - } else { - reconnect = true; - client.connect(clientCfg_); - } - }, 2)).on('close', mustCall(() => {}, 2)); -} - -{ - // Throw when not connected - - const client = new Client({ - username: 'foo', - password: 'bar', - }); - - assert.throws(mustCall(() => { - client.exec('uptime', mustNotCall()); - })); -} - -{ - const { client, server } = setup( - 'Outstanding callbacks called on disconnect' - ); - - server.on('connection', mustCall((conn) => { - conn.on('session', mustCall(() => {}, 3)); - })); - - client.on('ready', mustCall(() => { - function callback(err, stream) { - assert(err, 'Expected error'); - assert(err.message === 'No response from server', - `Wrong error message: ${err.message}`); - } - client.exec('uptime', mustCall(callback)); - client.shell(mustCall(callback)); - client.sftp(mustCall(callback)); - client.end(); - })); -} - -{ - const { client, server } = setup('Pipelined requests'); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }, 3)); - })); - })); - - client.on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup( - 'Pipelined requests with intermediate rekeying' - ); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - client.on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup('Ignore outgoing after stream close'); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo', mustCall((err, stream) => { - assert(!err, `Unexpected error: ${err}`); - stream.on('exit', mustCall((code, signal) => { - client.end(); - })); - })); - })); -} - -{ - const { client, server } = setup_( - 'Double pipe on unconnected, passed in net.Socket', - { - client: { - ...clientCfg, - sock: new net.Socket(), - }, - server: serverCfg, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => {})); - })); - client.on('ready', mustCall(() => { - client.end(); - })); -} - -{ - const { client, server } = setup( - 'Client auto-rejects inbound connections to unknown bound address' - ); - - const assignedPort = 31337; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', 'Wrong request name'); - assert.deepStrictEqual( - info, - { bindAddr: 'good', bindPort: 0 }, - 'Wrong request info' - ); - accept(assignedPort); - conn.forwardOut(info.bindAddr, - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - conn.forwardOut('bad', - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(err, 'Should receive error'); - client.end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn('good', 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === assignedPort, 'Wrong assigned port'); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - { destIP: 'good', - destPort: assignedPort, - srcIP: 'remote', - srcPort: 12345 - }, - 'Wrong connection details' - ); - accept(); - })); -} - -{ - const { client, server } = setup( - 'Client auto-rejects inbound connections to unknown bound port' - ); - - const assignedPort = 31337; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', 'Wrong request name'); - assert.deepStrictEqual( - info, - { bindAddr: 'good', bindPort: 0 }, - 'Wrong request info' - ); - accept(assignedPort); - conn.forwardOut(info.bindAddr, - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - conn.forwardOut(info.bindAddr, - 99999, - 'remote', - 12345, - mustCall((err, ch) => { - assert(err, 'Should receive error'); - client.end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn('good', 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === assignedPort, 'Wrong assigned port'); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - { destIP: 'good', - destPort: assignedPort, - srcIP: 'remote', - srcPort: 12345 - }, - 'Wrong connection details' - ); - accept(); - })); -} - -{ - const GREETING = 'Hello world!'; - - const { client, server } = setup_( - 'Server greeting', - { - client: { - ...clientCfg, - ident: 'node.js rules', - }, - server: { - ...serverCfg, - greeting: GREETING, - } - }, - ); - - let sawGreeting = false; - - server.on('connection', mustCall((conn, info) => { - assert.deepStrictEqual(info.header, { - identRaw: 'SSH-2.0-node.js rules', - greeting: '', - versions: { - protocol: '2.0', - software: 'node.js' - }, - comments: 'rules' - }); - conn.on('handshake', mustCall((details) => { - assert(sawGreeting, 'Client did not see greeting before handshake'); - })).on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('greeting', mustCall((greeting) => { - assert.strictEqual(greeting, `${GREETING}\r\n`); - sawGreeting = true; - })).on('banner', mustNotCall()); -} - -{ - const { client, server } = setup_( - 'Correct ident parsing', - { - client: { - ...clientCfg, - ident: 'node.js rules\n', - }, - server: serverCfg, - - noServerError: true, - noClientError: true, - noForceServerReady: true, - noForceClientReady: true, - }, - ); - - server.on('connection', mustCall((conn, info) => { - assert.deepStrictEqual(info.header, { - identRaw: 'SSH-2.0-node.js rules', - greeting: '', - versions: { - protocol: '2.0', - software: 'node.js' - }, - comments: 'rules' - }); - conn.once('error', mustCall((err) => { - assert(/bad packet length/i.test(err.message), 'Wrong error message'); - })); - conn.on('handshake', mustNotCall()) - .on('authentication', mustNotCall()) - .on('ready', mustNotCall()); - })); - - client.on('greeting', mustNotCall()) - .on('banner', mustNotCall()) - .on('ready', mustNotCall()); -} - -{ - const BANNER = 'Hello world!'; - - const { client, server } = setup_( - 'Server banner', - { - client: clientCfg, - server: { - ...serverCfg, - banner: BANNER, - } - }, - ); - - let sawBanner = false; - - server.on('connection', mustCall((conn) => { - conn.on('handshake', mustCall((details) => { - assert(!sawBanner, 'Client saw banner too early'); - })).on('authentication', mustCall((ctx) => { - assert(sawBanner, 'Client did not see banner before auth'); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('greeting', mustNotCall()) - .on('banner', mustCall((message) => { - assert.strictEqual(message, 'Hello world!\r\n'); - sawBanner = true; - })); -} - -{ - const { client, server } = setup( - 'Server responds to global requests in the right order' - ); - - function sendAcceptLater(accept) { - if (fastRejectSent) - accept(); - else - setImmediate(sendAcceptLater, accept); - } - - let fastRejectSent = false; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - if (info.bindAddr === 'fastReject') { - // Will call reject on 'fastReject' soon ... - reject(); - fastRejectSent = true; - } else { - // ... but accept on 'slowAccept' later - sendAcceptLater(accept); - } - }, 2)); - })); - })); - - client.on('ready', mustCall(() => { - let replyCnt = 0; - - client.forwardIn('slowAccept', 0, mustCall((err) => { - assert(!err, `Unexpected error: ${err}`); - if (++replyCnt === 2) - client.end(); - })); - - client.forwardIn('fastReject', 0, mustCall((err) => { - assert(err, 'Expected error'); - if (++replyCnt === 2) - client.end(); - })); - })); -} - -{ - const { client, server } = setup( - 'Cleanup outstanding channel requests on channel close' - ); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('subsystem', mustCall((accept, reject, info) => { - assert(info.name === 'netconf', `Wrong subsystem name: ${info.name}`); - - // XXX: hack to prevent success reply from being sent - conn._protocol.channelSuccess = () => {}; - - accept().close(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.subsys('netconf', mustCall((err, stream) => { - assert(err, 'Expected error'); - client.end(); - })); - })); -} - -{ - const { client, server } = setup_( - 'Handshake errors are emitted', - { - client: { - ...clientCfg, - algorithms: { cipher: [ 'aes128-cbc' ] }, - }, - server: { - ...serverCfg, - algorithms: { cipher: [ 'aes128-ctr' ] }, - }, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - - function onError(err) { - assert.strictEqual(err.level, 'handshake'); - assert(/handshake failed/i.test(err.message), 'Wrong error message'); - } - - server.on('connection', mustCall((conn) => { - conn.removeAllListeners('error'); - - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()) - .on('handshake', mustNotCall()) - .on('error', mustCall(onError)) - .on('close', mustCall(() => {})); - })); - - client.on('ready', mustNotCall()) - .on('error', mustCall(onError)) - .on('close', mustCall(() => {})); -} - -{ - const { client, server } = setup_( - 'Client signing errors are caught and emitted', - { - client: { - username: 'foo', - privateKey: KEY_RSA_BAD, - }, - server: serverCfg, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(!ctx.signature, 'Unexpected signature'); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - ctx.accept(); - break; - } - }, 2)).on('ready', mustNotCall()).on('close', mustCall(() => {})); - })); - - let cliError; - client.on('ready', mustNotCall()).on('error', mustCall((err) => { - if (cliError) { - assert(/all configured/i.test(err.message), 'Wrong error message'); - } else { - cliError = err; - assert(/signing/i.test(err.message), 'Wrong error message'); - } - }, 2)).on('close', mustCall(() => {})); -} - -{ - const { client, server } = setup_( - 'Server signing errors are caught and emitted', - { - client: clientCfg, - server: { hostKeys: [KEY_RSA_BAD] }, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - - server.on('connection', mustCall((conn) => { - conn.removeAllListeners('error'); - - conn.on('error', mustCall((err) => { - assert(/signature generation failed/i.test(err.message), - 'Wrong error message'); - })).on('authentication', mustNotCall()) - .on('ready', mustNotCall()) - .on('close', mustCall(() => {})); - })); - - client.on('ready', mustNotCall()).on('error', mustCall((err) => { - assert(/KEY_EXCHANGE_FAILED/.test(err.message), 'Wrong error message'); - })).on('close', mustCall(() => {})); -} - -{ - const { client, server } = setup_( - 'Rekeying with AES-GCM', - { - client: { - ...clientCfg, - algorithms: { cipher: [ 'aes128-gcm@openssh.com' ] }, - }, - server: { - ...serverCfg, - algorithms: { cipher: [ 'aes128-gcm@openssh.com' ] }, - }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - client.on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup_( - 'Switch from no compression to compression', - { - client: { - ...clientCfg, - algorithms: { compress: [ 'none' ] }, - }, - server: { - ...serverCfg, - algorithms: { compress: [ 'none', 'zlib@openssh.com' ] }, - }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - // XXX: hack to change algorithms after initial handshake - client._protocol._offer = new KexInit({ - kex: [ 'ecdh-sha2-nistp256' ], - serverHostKey: [ 'rsa-sha2-256' ], - cs: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'zlib@openssh.com' ], - lang: [], - }, - sc: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'zlib@openssh.com' ], - lang: [], - }, - }); - - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - let handshakes = 0; - client.on('handshake', mustCall((info) => { - switch (++handshakes) { - case 1: - assert(info.cs.compress === 'none', 'wrong compress value'); - assert(info.sc.compress === 'none', 'wrong compress value'); - break; - case 2: - assert(info.cs.compress === 'zlib@openssh.com', - 'wrong compress value'); - assert(info.sc.compress === 'zlib@openssh.com', - 'wrong compress value'); - break; - } - }, 2)).on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup_( - 'Switch from compression to no compression', - { - client: { - ...clientCfg, - algorithms: { compress: [ 'zlib' ] }, - }, - server: { - ...serverCfg, - algorithms: { compress: [ 'zlib', 'none' ] }, - } - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - // XXX: hack to change algorithms after initial handshake - client._protocol._offer = new KexInit({ - kex: [ 'ecdh-sha2-nistp256' ], - serverHostKey: [ 'rsa-sha2-256' ], - cs: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'none' ], - lang: [], - }, - sc: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'none' ], - lang: [], - }, - }); - - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - let handshakes = 0; - client.on('handshake', mustCall((info) => { - switch (++handshakes) { - case 1: - assert(info.cs.compress === 'zlib', 'wrong compress value'); - assert(info.sc.compress === 'zlib', 'wrong compress value'); - break; - case 2: - assert(info.cs.compress === 'none', 'wrong compress value'); - assert(info.sc.compress === 'none', 'wrong compress value'); - break; - } - }, 2)).on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup_( - 'Large data compression', - { - client: { - ...clientCfg, - algorithms: { compress: [ 'zlib' ] }, - }, - server: { - ...serverCfg, - algorithms: { compress: [ 'zlib' ] }, - } - }, - ); - - const chunk = Buffer.alloc(1024 * 1024, 'a'); - const chunkCount = 10; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - for (let i = 0; i < chunkCount; ++i) - stream.write(chunk); - stream.exit(0); - stream.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo', mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - let nb = 0; - stream.on('data', mustCallAtLeast((data) => { - nb += data.length; - })).on('end', mustCall(() => { - assert(nb === (chunkCount * chunk.length), - `Wrong stream byte count: ${nb}`); - client.end(); - })); - })); - })); -} - -{ - const { client, server } = setup_( - 'Debug output', - { - client: { - ...clientCfg, - debug: mustCallAtLeast((msg) => { - assert(typeof msg === 'string', - `Wrong debug argument type: ${typeof msg}`); - assert(msg.length > 0, 'Unexpected empty debug message'); - }), - }, - server: { - ...serverCfg, - debug: mustCallAtLeast((msg) => { - assert(typeof msg === 'string', - `Wrong debug argument type: ${typeof msg}`); - assert(msg.length > 0, 'Unexpected empty debug message'); - }), - }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { server } = setup_( - 'HTTP agent', - { - // No automatic client, the agent will create one - - server: serverCfg, - - debug, - }, - ); - - let httpServer; - server.on('listening', () => { - httpServer = http.createServer((req, res) => { - httpServer.close(); - res.end('hello world!'); - }); - httpServer.listen(0, 'localhost', () => { - const agent = new HTTPAgent({ - host: 'localhost', - port: server.address().port, - username: 'foo', - password: 'bar', - }); - http.get({ - host: 'localhost', - port: httpServer.address().port, - agent, - headers: { Connection: 'close' }, - }, (res) => { - assert(res.statusCode === 200, - `Wrong http status code: ${res.statusCode}`); - let buf = ''; - res.on('data', mustCallAtLeast((chunk) => { - buf += chunk; - })).on('end', mustCall(() => { - assert(buf === 'hello world!', - `Wrong http response body: ${inspect(buf)}`); - })); - }); - }); - }); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('tcpip', mustCall((accept, reject, info) => { - assert(info.destIP === 'localhost', `Wrong destIP: ${info.destIP}`); - assert(info.destPort === httpServer.address().port, - `Wrong destPort: ${info.destPort}`); - assert(info.srcIP === 'localhost', `Wrong srcIP: ${info.srcIP}`); - - const stream = accept(); - const tcp = new net.Socket(); - tcp.pipe(stream).pipe(tcp); - tcp.connect(httpServer.address().port, 'localhost'); - })); - })); - })); -} - -{ - const { server } = setup_( - 'HTTPS agent', - { - // No automatic client, the agent will create one - - server: serverCfg, - - debug, - }, - ); - - let httpsServer; - server.on('listening', () => { - httpsServer = https.createServer({ - key: fixture('https_key.pem'), - cert: fixture('https_cert.pem'), - }, (req, res) => { - httpsServer.close(); - res.end('hello world!'); - }); - httpsServer.listen(0, 'localhost', () => { - const agent = new HTTPSAgent({ - host: 'localhost', - port: server.address().port, - username: 'foo', - password: 'bar', - }); - https.get({ - host: 'localhost', - port: httpsServer.address().port, - agent, - headers: { Connection: 'close' }, - ca: fixture('https_cert.pem'), - }, (res) => { - assert(res.statusCode === 200, - `Wrong http status code: ${res.statusCode}`); - let buf = ''; - res.on('data', mustCallAtLeast((chunk) => { - buf += chunk; - })).on('end', mustCall(() => { - assert(buf === 'hello world!', - `Wrong http response body: ${inspect(buf)}`); - })); - }).on('error', (err) => { - // This workaround is necessary for some reason on node < v14.x - if (!/write after end/i.test(err.message)) - throw err; - }); - }); - }); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('tcpip', mustCall((accept, reject, info) => { - assert(info.destIP === 'localhost', `Wrong destIP: ${info.destIP}`); - assert(info.destPort === httpsServer.address().port, - `Wrong destPort: ${info.destPort}`); - assert(info.srcIP === 'localhost', `Wrong srcIP: ${info.srcIP}`); - - const stream = accept(); - const tcp = new net.Socket(); - tcp.pipe(stream).pipe(tcp); - tcp.connect(httpsServer.address().port, 'localhost'); - })); - })); - })); -} - -[ - { desc: 'remove/append/prepend (regexps)', - config: { - remove: /.*/, - append: /gcm/, - prepend: /ctr/, - }, - expected: [ - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', - 'aes128-gcm', - 'aes128-gcm@openssh.com', - 'aes256-gcm', - 'aes256-gcm@openssh.com', - ], - }, - { desc: 'remove/append/prepend (strings)', - config: { - remove: /.*/, - append: 'aes256-ctr', - prepend: [ 'aes256-gcm', 'aes128-gcm' ], - }, - expected: [ - 'aes256-gcm', - 'aes128-gcm', - 'aes256-ctr', - ], - }, -].forEach((info) => { - const { client, server } = setup_( - `Client algorithms option (${info.desc})`, - { - client: { - ...clientCfg, - algorithms: { cipher: info.config }, - }, - server: serverCfg, - - debug, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); - client.on('ready', mustCall(() => { - // XXX: hack to easily verify computed offer - const offer = client._protocol._offer.lists; - assert.deepStrictEqual( - offer.cs.cipher.array, - info.expected, - `Wrong algorithm list: ${offer.cs.cipher.array}` - ); - })); -}); - -{ - const { client } = setup_( - `Safely end() from Client 'error' event handler`, - { - client: clientCfg, - noClientError: true, - noForceClientReady: true, - }, - ); - - const badServer = net.createServer((s) => {}); - badServer.listen(0, 'localhost', mustCall(() => { - badServer.unref(); - - client.on('error', mustCallAtLeast((err) => { - client.end(); - })).on('ready', mustNotCall()).on('close', mustCall(() => {})); - client.connect({ - host: 'localhost', - port: badServer.address().port, - user: 'foo', - password: 'bar', - readyTimeout: 1, - }); - })); -} - -{ - const { client } = setup_( - 'Client error should be emitted on bad/nonexistent greeting', - { - client: clientCfg, - noClientError: true, - noForceClientReady: true, - }, - ); - - const badServer = net.createServer(mustCall((s) => { - badServer.close(); - s.end(); - })).listen(0, 'localhost', mustCall(() => { - client.on('error', mustCall((err) => { - client.end(); - })).on('ready', mustNotCall()).on('close', mustCall(() => {})); - client.connect({ - host: 'localhost', - port: badServer.address().port, - user: 'foo', - password: 'bar', - }); - })); -} - -{ - const { client } = setup_( - 'Only one client error on connection failure', - { - client: clientCfg, - noClientError: true, - noForceClientReady: true, - }, - ); - - client.on('error', mustCall((err) => { - assert.strictEqual(err.syscall, 'getaddrinfo'); - })); - client.connect({ - host: 'blerbblubblubblerb', - port: 9999, - user: 'foo', - password: 'bar' - }); -} - -{ - const { client, server } = setup( - 'Client should remove reserved channels on incoming channel rejection' - ); - - const assignedPort = 31337; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', 'Wrong request name'); - assert.deepStrictEqual( - info, - { bindAddr: 'good', bindPort: 0 }, - 'Wrong request info' - ); - accept(assignedPort); - conn.forwardOut(info.bindAddr, - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(err, 'Should receive error'); - client.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn('good', 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === assignedPort, 'Wrong assigned port'); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - { destIP: 'good', - destPort: assignedPort, - srcIP: 'remote', - srcPort: 12345 - }, - 'Wrong connection details' - ); - assert.strictEqual(Object.keys(client._chanMgr._channels).length, 1); - assert.strictEqual(client._chanMgr._count, 1); - reject(); - assert.strictEqual(Object.keys(client._chanMgr._channels).length, 0); - assert.strictEqual(client._chanMgr._count, 0); - })); -} - -{ - // Allow injected sockets - - const socket = new Transform({ - emitClose: true, - autoDestroy: true, - transform: (chunk, encoding, cb) => { - cb(); - }, - }); - socket.remoteAddress = '127.0.0.1'; - socket.remotePort = '12345'; - socket.remoteFamily = 'IPv4'; - socket.push(Buffer.from('SSH-2.0-foo\r\n')); - - const server = new Server(serverCfg); - server.on('connection', mustCall((conn, info) => { - assert.strictEqual(info.header.versions.software, 'foo'); - assert.strictEqual(info.ip, '127.0.0.1'); - assert.strictEqual(info.port, '12345'); - assert.strictEqual(info.family, 'IPv4'); - conn.on('ready', mustNotCall()); - conn.on('close', mustCall()); - socket.end(); - })); - server.injectSocket(socket); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-openssh.js b/reverse_engineering/node_modules/ssh2/test/test-openssh.js deleted file mode 100644 index 67e1b86..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-openssh.js +++ /dev/null @@ -1,261 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - fixture, - mustCall, - mustCallAtLeast, - setup: setup_, -} = require('./common.js'); - -const debug = false; - -const clientCfg = { username: 'foo', password: 'bar' }; -const serverCfg = { hostKeys: [ fixture('ssh_host_rsa_key') ] }; - -{ - const { client, server } = setup_( - 'Exec with OpenSSH agent forwarding', - { - client: { - ...clientCfg, - agent: '/path/to/agent', - }, - server: serverCfg, - - debug, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawAuthAgent = false; - accept().on('auth-agent', mustCall((accept, reject) => { - sawAuthAgent = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawAuthAgent, 'Expected auth-agent before exec'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', { agentForward: true }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup_( - 'OpenSSH forwarded UNIX socket connection', - { - client: clientCfg, - server: { - ...serverCfg, - ident: 'OpenSSH_7.1', - }, - - debug, - }, - ); - - const socketPath = '/foo'; - const events = []; - const expected = [ - ['client', 'openssh_forwardInStreamLocal'], - ['server', 'streamlocal-forward@openssh.com', { socketPath }], - ['client', 'forward callback'], - ['client', 'unix connection', { socketPath }], - ['client', 'socket data', '1'], - ['server', 'socket data', '2'], - ['client', 'socket end'], - ['server', 'cancel-streamlocal-forward@openssh.com', { socketPath }], - ['client', 'cancel callback'] - ]; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.once('request', mustCall((accept, reject, name, info) => { - events.push(['server', name, info]); - assert(name === 'streamlocal-forward@openssh.com', - `Wrong request name: ${name}`); - accept(); - conn.openssh_forwardOutStreamLocal(socketPath, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - ch.write('1'); - ch.on('data', mustCallAtLeast((data) => { - events.push(['server', 'socket data', data.toString()]); - ch.close(); - })); - })); - - conn.on('request', mustCall((accept, reject, name, info) => { - events.push(['server', name, info]); - assert(name === 'cancel-streamlocal-forward@openssh.com', - `Wrong request name: ${name}`); - accept(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - events.push(['client', 'openssh_forwardInStreamLocal']); - client.openssh_forwardInStreamLocal(socketPath, mustCall((err) => { - assert(!err, `Unexpected error: ${err}`); - events.push(['client', 'forward callback']); - })); - client.on('unix connection', mustCall((info, accept, reject) => { - events.push(['client', 'unix connection', info]); - const stream = accept(); - stream.on('data', mustCallAtLeast((data) => { - events.push(['client', 'socket data', data.toString()]); - stream.write('2'); - })).on('end', mustCall(() => { - events.push(['client', 'socket end']); - client.openssh_unforwardInStreamLocal(socketPath, - mustCall((err) => { - assert(!err, `Unexpected error: ${err}`); - events.push(['client', 'cancel callback']); - client.end(); - })); - })); - })); - })).on('close', mustCall(() => { - assert.deepStrictEqual( - events, - expected, - 'Events mismatch\n' - + `Actual:\n${inspect(events)}\n` - + `Expected:\n${inspect(expected)}` - ); - })); -} - -{ - const { client, server } = setup_( - 'OpenSSH UNIX socket connection', - { - client: clientCfg, - server: { - ...serverCfg, - ident: 'OpenSSH_8.0', - }, - - debug, - }, - ); - - const socketPath = '/foo/bar/baz'; - const response = 'Hello World'; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('openssh.streamlocal', mustCall((accept, reject, info) => { - assert.deepStrictEqual( - info, - { socketPath }, - `Wrong info: ${inspect(info)}` - ); - - const stream = accept(); - stream.on('close', mustCall(() => { - client.end(); - })).end(response); - stream.resume(); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.openssh_forwardOutStreamLocal(socketPath, mustCall((err, stream) => { - assert(!err, `Unexpected error: ${err}`); - let buf = ''; - stream.on('data', mustCallAtLeast((data) => { - buf += data; - })).on('close', mustCall(() => { - assert(buf === response, `Wrong response: ${inspect(buf)}`); - })); - })); - })); -} - -{ - const { client, server } = setup_( - 'OpenSSH 5.x workaround for binding on port 0', - { - client: clientCfg, - server: { - ...serverCfg, - ident: 'OpenSSH_5.3', - }, - - debug, - }, - ); - - const boundAddr = 'good'; - const boundPort = 1337; - const tcpInfo = { - destIP: boundAddr, - destPort: boundPort, - srcIP: 'remote', - srcPort: 12345, - }; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', `Unexpected request: ${name}`); - assert(info.bindAddr === boundAddr, `Wrong addr: ${info.bindAddr}`); - assert(info.bindPort === 0, `Wrong port: ${info.bindPort}`); - accept(boundPort); - conn.forwardOut(boundAddr, - 0, - tcpInfo.srcIP, - tcpInfo.srcPort, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - client.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn(boundAddr, 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === boundPort, `Bad bound port: ${port}`); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - tcpInfo, - `Wrong tcp details: ${inspect(details)}` - ); - accept(); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-protocol-crypto.js b/reverse_engineering/node_modules/ssh2/test/test-protocol-crypto.js deleted file mode 100644 index 8cae94c..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-protocol-crypto.js +++ /dev/null @@ -1,609 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { randomBytes } = require('crypto'); - -const { - CIPHER_INFO, - MAC_INFO, - bindingAvailable, - NullCipher, - createCipher, - NullDecipher, - createDecipher, - init: cryptoInit, -} = require('../lib/protocol/crypto.js'); - -(async () => { - await cryptoInit; - - console.log(`Crypto binding ${bindingAvailable ? '' : 'not '}available`); - { - const PAIRS = [ - // cipher, decipher - ['native', 'native'], - ['binding', 'native'], - ['native', 'binding'], - ['binding', 'binding'], - ].slice(0, bindingAvailable ? 4 : 1); - - [ - { cipher: null }, - { cipher: 'chacha20-poly1305@openssh.com' }, - { cipher: 'aes128-gcm@openssh.com' }, - { cipher: 'aes128-cbc', mac: 'hmac-sha1-etm@openssh.com' }, - { cipher: 'aes128-ctr', mac: 'hmac-sha1' }, - { cipher: 'arcfour', mac: 'hmac-sha2-256-96' }, - ].forEach((testConfig) => { - for (const pair of PAIRS) { - function onCipherData(data) { - ciphered = Buffer.concat([ciphered, data]); - } - - function onDecipherPayload(payload) { - deciphered.push(payload); - } - - function reset() { - ciphered = Buffer.alloc(0); - deciphered = []; - } - - function reinit() { - if (testConfig.cipher === null) { - cipher = new NullCipher(1, onCipherData); - decipher = new NullDecipher(1, onDecipherPayload); - } else { - cipher = createCipher(config); - decipher = createDecipher(config); - } - } - - let ciphered; - let deciphered; - let cipher; - let decipher; - let macSize; - let packet; - let payload; - let cipherInfo; - let config; - - console.log('Testing cipher: %s, mac: %s (%s encrypt, %s decrypt) ...', - testConfig.cipher, - testConfig.mac - || (testConfig.cipher === null ? '' : ''), - pair[0], - pair[1]); - - if (testConfig.cipher === null) { - cipher = new NullCipher(1, onCipherData); - decipher = new NullDecipher(1, onDecipherPayload); - macSize = 0; - } else { - cipherInfo = CIPHER_INFO[testConfig.cipher]; - let macInfo; - let macKey; - if (testConfig.mac) { - macInfo = MAC_INFO[testConfig.mac]; - macKey = randomBytes(macInfo.len); - macSize = macInfo.actualLen; - } else if (cipherInfo.authLen) { - macSize = cipherInfo.authLen; - } else { - throw new Error('Missing MAC for cipher'); - } - const key = randomBytes(cipherInfo.keyLen); - const iv = (cipherInfo.ivLen - ? randomBytes(cipherInfo.ivLen) - : Buffer.alloc(0)); - config = { - outbound: { - onWrite: onCipherData, - cipherInfo, - cipherKey: Buffer.from(key), - cipherIV: Buffer.from(iv), - seqno: 1, - macInfo, - macKey: (macKey && Buffer.from(macKey)), - forceNative: (pair[0] === 'native'), - }, - inbound: { - onPayload: onDecipherPayload, - decipherInfo: cipherInfo, - decipherKey: Buffer.from(key), - decipherIV: Buffer.from(iv), - seqno: 1, - macInfo, - macKey: (macKey && Buffer.from(macKey)), - forceNative: (pair[1] === 'native'), - }, - }; - cipher = createCipher(config); - decipher = createDecipher(config); - - if (pair[0] === 'binding') - assert(/binding/i.test(cipher.constructor.name)); - else - assert(/native/i.test(cipher.constructor.name)); - if (pair[1] === 'binding') - assert(/binding/i.test(decipher.constructor.name)); - else - assert(/native/i.test(decipher.constructor.name)); - } - - let expectedSeqno; - // Test zero-length payload ============================================ - payload = Buffer.alloc(0); - expectedSeqno = 2; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test single byte payload ============================================ - payload = Buffer.from([ 0xEF ]); - expectedSeqno = 3; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, 3); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test large payload ================================================== - payload = randomBytes(32 * 1024); - expectedSeqno = 4; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test sequnce number rollover ======================================== - payload = randomBytes(4); - expectedSeqno = 0; - cipher.outSeqno = decipher.inSeqno = (2 ** 32) - 1; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test chunked input -- split length bytes ============================ - payload = randomBytes(32 * 768); - expectedSeqno = 1; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, 2), undefined); - assert.strictEqual(decipher.decrypt(ciphered, 2, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test chunked input -- split length from payload ===================== - payload = randomBytes(32 * 768); - expectedSeqno = 2; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, 4), undefined); - assert.strictEqual(decipher.decrypt(ciphered, 4, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test chunked input -- split length and payload from MAC ============= - payload = randomBytes(32 * 768); - expectedSeqno = 3; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual( - decipher.decrypt(ciphered, 0, ciphered.length - macSize), - undefined - ); - assert.strictEqual( - decipher.decrypt(ciphered, - ciphered.length - macSize, - ciphered.length), - undefined - ); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test packet length checks =========================================== - [0, 2 ** 32 - 1].forEach((n) => { - reset(); - packet = cipher.allocPacket(0); - packet.writeUInt32BE(n, 0); // Overwrite packet length field - cipher.encrypt(packet); - let threw = false; - try { - decipher.decrypt(ciphered, 0, ciphered.length); - } catch (ex) { - threw = true; - assert(ex instanceof Error); - assert(/packet length/i.test(ex.message)); - } - if (!threw) - throw new Error('Expected error'); - - // Recreate deciphers since errors leave them in an unusable state. - // We recreate the ciphers as well so that internal states of both - // ends match again. - reinit(); - }); - - // Test minimum padding length check =================================== - if (testConfig.cipher !== null) { - let payloadLen; - const blockLen = cipherInfo.blockLen; - if (/chacha|gcm/i.test(testConfig.cipher) - || /etm/i.test(testConfig.mac)) { - payloadLen = blockLen - 2; - } else { - payloadLen = blockLen - 6; - } - const minLen = 4 + 1 + payloadLen + (blockLen + 1); - // We don't do strict equality checks here since the length of the - // returned Buffer can vary due to implementation details. - assert(cipher.allocPacket(payloadLen).length >= minLen); - } - - // ===================================================================== - cipher.free(); - decipher.free(); - if (testConfig.cipher === null) - break; - } - }); - } - - // Test createCipher()/createDecipher() exceptions - { - [ - [ - [true, null], - /invalid config/i - ], - [ - [{}], - [/invalid outbound/i, /invalid inbound/i] - ], - [ - [{ outbound: {}, inbound: {} }], - [/invalid outbound\.onWrite/i, /invalid inbound\.onPayload/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: null - }, - }, - ], - [/invalid outbound\.cipherInfo/i, /invalid inbound\.decipherInfo/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: {}, - cipherKey: {}, - }, - inbound: { - onPayload: () => {}, - decipherInfo: {}, - decipherKey: {}, - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 32 }, - cipherKey: Buffer.alloc(8), - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 32 }, - decipherKey: Buffer.alloc(8), - }, - }, - ], - [/invalid outbound\.cipherKey/i, /invalid inbound\.decipherKey/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: null - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: {} - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: {} - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: Buffer.alloc(1) - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: Buffer.alloc(1) - }, - }, - ], - [/invalid outbound\.cipherIV/i, /invalid inbound\.decipherIV/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0 }, - cipherKey: Buffer.alloc(1), - seqno: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0 }, - decipherKey: Buffer.alloc(1), - seqno: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0 }, - cipherKey: Buffer.alloc(1), - seqno: -1 - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0 }, - decipherKey: Buffer.alloc(1), - seqno: -1 - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0 }, - cipherKey: Buffer.alloc(1), - seqno: 2 ** 32 - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0 }, - decipherKey: Buffer.alloc(1), - seqno: 2 ** 32 - }, - }, - ], - [/invalid outbound\.seqno/i, /invalid inbound\.seqno/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0 - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0 - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: null - }, - }, - ], - [/invalid outbound\.macInfo/i, /invalid inbound\.macInfo/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 } - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 } - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: null - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: Buffer.alloc(1) - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: Buffer.alloc(1) - }, - }, - ], - [/invalid outbound\.macKey/i, /invalid inbound\.macKey/i] - ], - ].forEach((testCase) => { - let errorChecks = testCase[1]; - if (!Array.isArray(errorChecks)) - errorChecks = [errorChecks[0], errorChecks[0]]; - for (const input of testCase[0]) { - assert.throws(() => createCipher(input), errorChecks[0]); - assert.throws(() => createDecipher(input), errorChecks[1]); - } - }); - } -})(); diff --git a/reverse_engineering/node_modules/ssh2/test/test-protocol-keyparser.js b/reverse_engineering/node_modules/ssh2/test/test-protocol-keyparser.js deleted file mode 100644 index 850d405..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-protocol-keyparser.js +++ /dev/null @@ -1,145 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { readdirSync, readFileSync } = require('fs'); -const { inspect } = require('util'); - -const { parseKey } = require('../lib/protocol/keyParser.js'); - -const { EDDSA_SUPPORTED } = require('../lib/protocol/constants.js'); - -const BASE_PATH = `${__dirname}/fixtures/keyParser`; - -function failMsg(name, message, exit) { - const msg = `[${name}] ${message}`; - if (!exit) - return msg; - console.error(msg); - process.exit(1); -} - -readdirSync(BASE_PATH).forEach((name) => { - if (/\.result$/i.test(name)) - return; - if (/ed25519/i.test(name) && !EDDSA_SUPPORTED) - return; - - const isPublic = /\.pub$/i.test(name); - const isEncrypted = /_enc/i.test(name); - const isPPK = /^ppk_/i.test(name); - const key = readFileSync(`${BASE_PATH}/${name}`); - let res; - if (isEncrypted) - res = parseKey(key, (isPPK ? 'node.js' : 'password')); - else - res = parseKey(key); - let expected = JSON.parse( - readFileSync(`${BASE_PATH}/${name}.result`, 'utf8') - ); - if (typeof expected === 'string') { - if (!(res instanceof Error)) - failMsg(name, `Expected error: ${expected}`, true); - assert.strictEqual( - expected, - res.message, - failMsg(name, - 'Error message mismatch.\n' - + `Expected: ${inspect(expected)}\n` - + `Received: ${inspect(res.message)}`) - ); - } else if (res instanceof Error) { - failMsg(name, `Unexpected error: ${res.stack}`, true); - } else { - if (Array.isArray(expected) && !Array.isArray(res)) - failMsg(name, 'Expected array but did not receive one', true); - if (!Array.isArray(expected) && Array.isArray(res)) - failMsg(name, 'Received array but did not expect one', true); - - if (!Array.isArray(res)) { - res = [res]; - expected = [expected]; - } else if (res.length !== expected.length) { - failMsg(name, - `Expected ${expected.length} keys, but received ${res.length}`, - true); - } - - res.forEach((curKey, i) => { - const details = { - type: curKey.type, - comment: curKey.comment, - public: curKey.getPublicPEM(), - publicSSH: curKey.getPublicSSH() - && curKey.getPublicSSH().toString('base64'), - private: curKey.getPrivatePEM() - }; - assert.deepStrictEqual( - details, - expected[i], - failMsg(name, - 'Parser output mismatch.\n' - + `Expected: ${inspect(expected[i])}\n\n` - + `Received: ${inspect(details)}`) - ); - }); - } - - if (isEncrypted && !isPublic) { - // Make sure parsing encrypted keys without a passhprase or incorrect - // passphrase results in an appropriate error - const err = parseKey(key); - if (!(err instanceof Error)) - failMsg(name, 'Expected error during parse without passphrase', true); - if (!/no passphrase/i.test(err.message)) { - failMsg(name, - `Error during parse without passphrase: ${err.message}`, - true); - } - } - - if (!isPublic) { - // Try signing and verifying to make sure the private/public key PEMs are - // correct - const data = Buffer.from('hello world'); - res.forEach((curKey) => { - let result = curKey.sign(data); - if (result instanceof Error) { - failMsg(name, - `Error while signing data with key: ${result.message}`, - true); - } - result = curKey.verify(data, result); - if (result instanceof Error) { - failMsg(name, - `Error while verifying signed data with key: ${result.message}`, - true); - } - if (!result) - failMsg(name, 'Failed to verify signed data with key', true); - }); - if (res.length === 1 && !isPPK) { - const pubFile = readFileSync(`${BASE_PATH}/${name}.pub`); - const pubParsed = parseKey(pubFile); - if (!(pubParsed instanceof Error)) { - let result = res[0].sign(data); - if (result instanceof Error) { - failMsg(name, - `Error while signing data with key: ${result.message}`, - true); - } - result = pubParsed.verify(data, result); - if (result instanceof Error) { - failMsg(name, - 'Error while verifying signed data with separate public key: ' - + result.message, - true); - } - if (!result) { - failMsg(name, - 'Failed to verify signed data with separate public key', - true); - } - } - } - } -}); diff --git a/reverse_engineering/node_modules/ssh2/test/test-server-hostkeys.js b/reverse_engineering/node_modules/ssh2/test/test-server-hostkeys.js deleted file mode 100644 index 3093864..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-server-hostkeys.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -const { - fixtureKey, - mustCall, - setup, -} = require('./common.js'); - -const debug = false; - -[ - { desc: 'RSA user key (old OpenSSH)', - hostKey: fixtureKey('id_rsa') }, - { desc: 'RSA user key (new OpenSSH)', - hostKey: fixtureKey('openssh_new_rsa') }, - { desc: 'DSA host key', - hostKey: fixtureKey('ssh_host_dsa_key') }, - { desc: 'ECDSA host key', - hostKey: fixtureKey('ssh_host_ecdsa_key') }, - { desc: 'PPK', - hostKey: fixtureKey('id_rsa.ppk') }, -].forEach((test) => { - const { desc, hostKey } = test; - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - desc, - { - client: { - username, - privateKey: clientKey.raw, - algorithms: { - serverHostKey: [ hostKey.key.type ], - } - }, - server: { hostKeys: [ hostKey.raw ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -}); - - -{ - const RSA_KEY = fixtureKey('ssh_host_rsa_key'); - const ECDSA_KEY = fixtureKey('ssh_host_ecdsa_key'); - [ RSA_KEY, ECDSA_KEY ].forEach((key) => { - const selKeyType = key.key.type; - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { client, server } = setup( - `Multiple host key types (${key.type} selected)`, - { - client: { - username, - privateKey: clientKey.raw, - algorithms: { - serverHostKey: [ selKeyType ], - } - }, - server: { hostKeys: [ RSA_KEY.raw, ECDSA_KEY.raw ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); - client.on('handshake', mustCall((info) => { - assert(info.serverHostKey === selKeyType, 'Wrong host key selected'); - })); - }); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-sftp.js b/reverse_engineering/node_modules/ssh2/test/test-sftp.js deleted file mode 100644 index 50e56f5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-sftp.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { constants } = require('fs'); - -const { - fixture, - mustCall, - mustCallAtLeast, - mustNotCall, - setup: setup_, - setupSimple -} = require('./common.js'); - -const { OPEN_MODE, Stats, STATUS_CODE } = require('../lib/protocol/SFTP.js'); - -const DEBUG = false; - -setup('open', mustCall((client, server) => { - const path_ = '/tmp/foo.txt'; - const handle_ = Buffer.from('node.js'); - const pflags_ = (OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === pflags_, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - server.end(); - })); - client.open(path_, 'w', mustCall((err, handle) => { - assert(!err, `Unexpected open() error: ${err}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - })); -})); - -setup('close', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - server.on('CLOSE', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.close(handle_, mustCall((err) => { - assert(!err, `Unexpected close() error: ${err}`); - })); -})); - -setup('read', mustCall((client, server) => { - const expected = Buffer.from('node.jsnode.jsnode.jsnode.jsnode.jsnode.js'); - const handle_ = Buffer.from('node.js'); - const buf = Buffer.alloc(expected.length); - server.on('READ', mustCall((id, handle, offset, len) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === 5, `Wrong read offset: ${offset}`); - assert(len === buf.length, `Wrong read len: ${len}`); - server.data(id, expected); - server.end(); - })); - client.read(handle_, buf, 0, buf.length, 5, mustCall((err, nb) => { - assert(!err, `Unexpected read() error: ${err}`); - assert.deepStrictEqual(buf, expected, 'read data mismatch'); - })); -})); - -setup('read (overflow)', mustCall((client, server) => { - const maxChunk = client._maxReadLen; - const expected = Buffer.alloc(3 * maxChunk, 'Q'); - const handle_ = Buffer.from('node.js'); - const buf = Buffer.alloc(expected.length, 0); - let reqs = 0; - server.on('READ', mustCall((id, handle, offset, len) => { - ++reqs; - assert.strictEqual(id, reqs - 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.strictEqual(offset, - (reqs - 1) * maxChunk, - `Wrong read offset: ${offset}`); - server.data(id, expected.slice(offset, offset + len)); - if (reqs === 3) - server.end(); - }, 3)); - client.read(handle_, buf, 0, buf.length, 0, mustCall((err, nb) => { - assert(!err, `Unexpected read() error: ${err}`); - assert.deepStrictEqual(buf, expected); - assert.strictEqual(nb, buf.length, 'read nb mismatch'); - })); -})); - -setup('write', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const buf = Buffer.from('node.jsnode.jsnode.jsnode.jsnode.jsnode.js'); - server.on('WRITE', mustCall((id, handle, offset, data) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === 5, `Wrong write offset: ${offset}`); - assert.deepStrictEqual(data, buf, 'write data mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.write(handle_, buf, 0, buf.length, 5, mustCall((err, nb) => { - assert(!err, `Unexpected write() error: ${err}`); - assert.strictEqual(nb, buf.length, 'wrong bytes written'); - })); -})); - -setup('write (overflow)', mustCall((client, server) => { - const maxChunk = client._maxWriteLen; - const handle_ = Buffer.from('node.js'); - const buf = Buffer.allocUnsafe(3 * maxChunk); - let reqs = 0; - server.on('WRITE', mustCall((id, handle, offset, data) => { - ++reqs; - assert.strictEqual(id, reqs - 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.strictEqual(offset, - (reqs - 1) * maxChunk, - `Wrong write offset: ${offset}`); - assert((offset + data.length) <= buf.length, 'bad offset'); - assert.deepStrictEqual(data, - buf.slice(offset, offset + data.length), - 'write data mismatch'); - server.status(id, STATUS_CODE.OK); - if (reqs === 3) - server.end(); - }, 3)); - client.write(handle_, buf, 0, buf.length, 0, mustCall((err, nb) => { - assert(!err, `Unexpected write() error: ${err}`); - assert.strictEqual(nb, buf.length, 'wrote bytes written'); - })); -})); - -setup('lstat', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const attrs_ = new Stats({ - size: 10 * 1024, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('LSTAT', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.attrs(id, attrs_); - server.end(); - })); - client.lstat(path_, mustCall((err, attrs) => { - assert(!err, `Unexpected lstat() error: ${err}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - })); -})); - -setup('fstat', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const attrs_ = new Stats({ - size: 10 * 1024, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('FSTAT', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.attrs(id, attrs_); - server.end(); - })); - client.fstat(handle_, mustCall((err, attrs) => { - assert(!err, `Unexpected fstat() error: ${err}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - })); -})); - -setup('setstat', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const attrs_ = new Stats({ - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('SETSTAT', mustCall((id, path, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.setstat(path_, attrs_, mustCall((err) => { - assert(!err, `Unexpected setstat() error: ${err}`); - })); -})); - -setup('fsetstat', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const attrs_ = new Stats({ - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('FSETSTAT', mustCall((id, handle, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.fsetstat(handle_, attrs_, mustCall((err) => { - assert(!err, `Unexpected fsetstat() error: ${err}`); - })); -})); - -setup('opendir', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const path_ = '/tmp'; - server.on('OPENDIR', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.handle(id, handle_); - server.end(); - })); - client.opendir(path_, mustCall((err, handle) => { - assert(!err, `Unexpected opendir() error: ${err}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - })); -})); - -setup('readdir', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const list_ = [ - { filename: '.', - longname: 'drwxr-xr-x 56 nodejs nodejs 4096 Nov 10 01:05 .', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1415599549, - mtime: 1415599590 - }) - }, - { filename: '..', - longname: 'drwxr-xr-x 4 root root 4096 May 16 2013 ..', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 0, - gid: 0, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'foo', - longname: 'drwxrwxrwx 2 nodejs nodejs 4096 Mar 8 2009 foo', - attrs: new Stats({ - mode: 0o777 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'bar', - longname: '-rw-r--r-- 1 nodejs nodejs 513901992 Dec 4 2009 bar', - attrs: new Stats({ - mode: 0o644 | constants.S_IFREG, - size: 513901992, - uid: 9001, - gid: 8001, - atime: 1259972199, - mtime: 1259972199 - }) - } - ]; - server.on('READDIR', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.name(id, list_); - server.end(); - })); - client.readdir(handle_, mustCall((err, list) => { - assert(!err, `Unexpected readdir() error: ${err}`); - assert.deepStrictEqual(list, - list_.slice(2), - 'dir list mismatch'); - })); -})); - -setup('readdir (full)', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const list_ = [ - { filename: '.', - longname: 'drwxr-xr-x 56 nodejs nodejs 4096 Nov 10 01:05 .', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1415599549, - mtime: 1415599590 - }) - }, - { filename: '..', - longname: 'drwxr-xr-x 4 root root 4096 May 16 2013 ..', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 0, - gid: 0, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'foo', - longname: 'drwxrwxrwx 2 nodejs nodejs 4096 Mar 8 2009 foo', - attrs: new Stats({ - mode: 0o777 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'bar', - longname: '-rw-r--r-- 1 nodejs nodejs 513901992 Dec 4 2009 bar', - attrs: new Stats({ - mode: 0o644 | constants.S_IFREG, - size: 513901992, - uid: 9001, - gid: 8001, - atime: 1259972199, - mtime: 1259972199 - }) - } - ]; - server.on('READDIR', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.name(id, list_); - server.end(); - })); - client.readdir(handle_, { full: true }, mustCall((err, list) => { - assert(!err, `Unexpected readdir() error: ${err}`); - assert.deepStrictEqual(list, list_, 'dir list mismatch'); - })); -})); - -setup('readdir (EOF)', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - server.on('READDIR', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.EOF); - server.end(); - })); - client.readdir(handle_, mustCall((err, list) => { - assert(err && err.code === STATUS_CODE.EOF, - `Expected EOF, got: ${err}`); - })); -})); - -setup('unlink', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('REMOVE', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.unlink(path_, mustCall((err) => { - assert(!err, `Unexpected unlink() error: ${err}`); - })); -})); - -setup('mkdir', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('MKDIR', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.mkdir(path_, mustCall((err) => { - assert(!err, `Unexpected mkdir() error: ${err}`); - })); -})); - -setup('rmdir', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('RMDIR', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.rmdir(path_, mustCall((err) => { - assert(!err, `Unexpected rmdir() error: ${err}`); - })); -})); - -setup('realpath', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const name_ = { filename: '/tmp/foo' }; - server.on('REALPATH', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.name(id, name_); - server.end(); - })); - client.realpath(path_, mustCall((err, name) => { - assert(!err, `Unexpected realpath() error: ${err}`); - assert.deepStrictEqual(name, name_.filename, 'name mismatch'); - })); -})); - -setup('stat', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const attrs_ = new Stats({ - mode: 0o644 | constants.S_IFREG, - size: 10 * 1024, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('STAT', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.attrs(id, attrs_); - server.end(); - })); - client.stat(path_, mustCall((err, attrs) => { - assert(!err, `Unexpected stat() error: ${err}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - const expectedTypes = { - isDirectory: false, - isFile: true, - isBlockDevice: false, - isCharacterDevice: false, - isSymbolicLink: false, - isFIFO: false, - isSocket: false - }; - for (const [fn, expect] of Object.entries(expectedTypes)) - assert(attrs[fn]() === expect, `attrs.${fn}() failed`); - })); -})); - -setup('rename', mustCall((client, server) => { - const oldPath_ = '/foo/bar/baz'; - const newPath_ = '/tmp/foo'; - server.on('RENAME', mustCall((id, oldPath, newPath) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(oldPath === oldPath_, `Wrong old path: ${oldPath}`); - assert(newPath === newPath_, `Wrong new path: ${newPath}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.rename(oldPath_, newPath_, mustCall((err) => { - assert(!err, `Unexpected rename() error: ${err}`); - })); -})); - -setup('readlink', mustCall((client, server) => { - const linkPath_ = '/foo/bar/baz'; - const name = { filename: '/tmp/foo' }; - server.on('READLINK', mustCall((id, linkPath) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(linkPath === linkPath_, `Wrong link path: ${linkPath}`); - server.name(id, name); - server.end(); - })); - client.readlink(linkPath_, mustCall((err, targetPath) => { - assert(!err, `Unexpected readlink() error: ${err}`); - assert(targetPath === name.filename, - `Wrong target path: ${targetPath}`); - })); -})); - -setup('symlink', mustCall((client, server) => { - const linkPath_ = '/foo/bar/baz'; - const targetPath_ = '/tmp/foo'; - server.on('SYMLINK', mustCall((id, linkPath, targetPath) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(linkPath === linkPath_, `Wrong link path: ${linkPath}`); - assert(targetPath === targetPath_, `Wrong target path: ${targetPath}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.symlink(targetPath_, linkPath_, mustCall((err) => { - assert(!err, `Unexpected symlink() error: ${err}`); - })); -})); - -setup('readFile', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('FSTAT', mustCall((id, handle) => { - assert(id === 1, `Wrong request id: ${id}`); - const attrs = new Stats({ - size: data_.length, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.attrs(id, attrs); - })).on('READ', mustCall((id, handle, offset, len) => { - assert(id === 2, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === 0, `Wrong read offset: ${offset}`); - server.data(id, data_); - })).on('CLOSE', mustCall((id, handle) => { - assert(id === 3, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.readFile(path_, mustCall((err, buf) => { - assert(!err, `Unexpected error: ${err}`); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('readFile (no size from fstat)', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - let reads = 0; - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('FSTAT', mustCall((id, handle) => { - assert(id === 1, `Wrong request id: ${id}`); - const attrs = new Stats({ - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.attrs(id, attrs); - })).on('READ', mustCall((id, handle, offset, len) => { - assert(++reads + 1 === id, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - switch (id) { - case 2: - assert(offset === 0, `Wrong read offset for first read: ${offset}`); - server.data(id, data_); - break; - case 3: - assert(offset === data_.length, - `Wrong read offset for second read: ${offset}`); - server.status(id, STATUS_CODE.EOF); - break; - } - }, 2)).on('CLOSE', mustCall((id, handle) => { - assert(id === 4, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.readFile(path_, mustCall((err, buf) => { - assert(!err, `Unexpected error: ${err}`); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('ReadStream', mustCall((client, server) => { - let reads = 0; - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('READ', mustCall((id, handle, offset, len) => { - assert(id === ++reads, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - if (reads === 1) { - assert(offset === 0, `Wrong read offset: ${offset}`); - server.data(id, data_); - } else { - server.status(id, STATUS_CODE.EOF); - } - }, 2)).on('CLOSE', mustCall((id, handle) => { - assert(id === 3, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - let buf = []; - client.createReadStream(path_).on('readable', mustCallAtLeast(function() { - let chunk; - while ((chunk = this.read()) !== null) - buf.push(chunk); - })).on('end', mustCall(() => { - buf = Buffer.concat(buf); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('ReadStream (fewer bytes than requested)', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - server.handle(id, handle_); - })).on('READ', mustCallAtLeast((id, handle, offset, len) => { - if (offset > data_.length) { - server.status(id, STATUS_CODE.EOF); - } else { - // Only read 4 bytes at a time - server.data(id, data_.slice(offset, offset + 4)); - } - })).on('CLOSE', mustCall((id, handle) => { - server.status(id, STATUS_CODE.OK); - server.end(); - })); - let buf = []; - client.createReadStream(path_).on('readable', mustCallAtLeast(function() { - let chunk; - while ((chunk = this.read()) !== null) - buf.push(chunk); - })).on('end', mustCall(() => { - buf = Buffer.concat(buf); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('ReadStream (error)', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.status(id, STATUS_CODE.NO_SUCH_FILE); - server.end(); - })); - client.createReadStream(path_).on('error', mustCall((err) => { - assert(err.code === STATUS_CODE.NO_SUCH_FILE); - })); -})); - -setup('WriteStream', mustCall((client, server) => { - let writes = 0; - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - const pflags_ = OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE; - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === pflags_, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('FSETSTAT', mustCall((id, handle, attrs) => { - assert(id === 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.strictEqual(attrs.mode, 0o666, 'Wrong file mode'); - server.status(id, STATUS_CODE.OK); - })).on('WRITE', mustCall((id, handle, offset, data) => { - assert(id === ++writes + 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === ((writes - 1) * data_.length), - `Wrong write offset: ${offset}`); - assert.deepStrictEqual(data, data_, 'Wrong data'); - server.status(id, STATUS_CODE.OK); - }, 3)).on('CLOSE', mustCall((id, handle) => { - assert(id === 5, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - - const writer = client.createWriteStream(path_); - writer.cork && writer.cork(); - writer.write(data_); - writer.write(data_); - writer.write(data_); - writer.uncork && writer.uncork(); - writer.end(); -})); - -{ - const { client, server } = setup_( - 'SFTP server aborts with exit-status', - { - client: { username: 'foo', password: 'bar' }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('sftp', mustCall((accept, reject) => { - const sftp = accept(); - - // XXX: hack - sftp._protocol.exitStatus(sftp.outgoing.id, 127); - sftp._protocol.channelClose(sftp.outgoing.id); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - const timeout = setTimeout(mustNotCall(), 1000); - client.sftp(mustCall((err, sftp) => { - clearTimeout(timeout); - assert(err, 'Expected error'); - assert(err.code === 127, `Expected exit code 127, saw: ${err.code}`); - client.end(); - })); - })); -} - - -// ============================================================================= -function setup(title, cb) { - const { client, server } = setupSimple(DEBUG, title); - let clientSFTP; - let serverSFTP; - - const onSFTP = mustCall(() => { - if (clientSFTP && serverSFTP) - cb(clientSFTP, serverSFTP); - }, 2); - - client.on('ready', mustCall(() => { - client.sftp(mustCall((err, sftp) => { - assert(!err, `[${title}] Unexpected client sftp start error: ${err}`); - sftp.on('close', mustCall(() => { - client.end(); - })); - clientSFTP = sftp; - onSFTP(); - })); - })); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('sftp', mustCall((accept, reject) => { - const sftp = accept(); - sftp.on('close', mustCall(() => { - conn.end(); - })); - serverSFTP = sftp; - onSFTP(); - })); - })); - })); - })); -} - -function flagsToHuman(flags) { - const ret = []; - - for (const [name, value] of Object.entries(OPEN_MODE)) { - if (flags & value) - ret.push(name); - } - - return ret.join(' | '); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-shell.js b/reverse_engineering/node_modules/ssh2/test/test-shell.js deleted file mode 100644 index debba11..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-shell.js +++ /dev/null @@ -1,109 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - mustCall, - mustCallAtLeast, - setupSimple, -} = require('./common.js'); - -const DEBUG = false; - -const setup = setupSimple.bind(undefined, DEBUG); - -{ - const { client, server } = setup('Simple shell()'); - - const OUTPUT = 'shell output!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('pty', mustCall((accept, reject, info) => { - accept(); - session.on('shell', mustCall((accept, reject) => { - let input = ''; - const stream = accept(); - stream.write(OUTPUT); - stream.on('data', mustCallAtLeast((data) => { - input += data; - if (input === 'exit\n') { - stream.end(); - conn.end(); - } - })); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let output = ''; - client.on('close', mustCall(() => { - assert(output === OUTPUT, `Wrong shell output: ${inspect(output)}`); - })).shell(mustCall((err, stream) => { - assert(!err, `Unexpected shell error: ${err}`); - stream.write('exit\n'); - stream.on('data', mustCallAtLeast((d) => { - output += d; - })).on('close', mustCall(() => {})); - })); - })); -} - -{ - const { client, server } = setup('Shell with environment set'); - - const OUTPUT = 'shell output!\n'; - const clientEnv = { SSH2NODETEST: 'foo' }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let pty = false; - let env = false; - accept().on('pty', mustCall((accept, reject, info) => { - accept(); - pty = true; - })).on('env', mustCall((accept, reject, info) => { - accept && accept(); - env = true; - assert(info.key === Object.keys(clientEnv)[0], - `Wrong env key: ${inspect(info.key)}`); - assert(info.val === Object.values(clientEnv)[0], - `Wrong env value: ${inspect(info.val)}`); - })).on('shell', mustCall((accept, reject) => { - assert(pty, 'Expected pty before shell'); - assert(env, 'Expected env before shell'); - let input = ''; - const stream = accept(); - stream.write(OUTPUT); - stream.on('data', mustCallAtLeast((data) => { - input += data; - if (input === 'exit\n') { - stream.end(); - conn.end(); - } - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let output = ''; - client.on('close', mustCall(() => { - assert(output === OUTPUT, `Wrong shell output: ${inspect(output)}`); - })).shell({ env: clientEnv }, mustCall((err, stream) => { - assert(!err, `Unexpected shell error: ${err}`); - stream.write('exit\n'); - stream.on('data', mustCallAtLeast((d) => { - output += d; - })).on('close', mustCall(() => {})); - })); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent-openssh.js b/reverse_engineering/node_modules/ssh2/test/test-userauth-agent-openssh.js deleted file mode 100644 index 55d1a25..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent-openssh.js +++ /dev/null @@ -1,109 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { spawnSync } = require('child_process'); - -const debug = false; -const SPAWN_OPTS = { windowsHide: true }; - -// TODO: figure out why this test is failing on Windows -if (process.platform === 'win32') { - console.log('Skipping ssh-agent test on Windows'); - process.exit(0); -} - -if (process.argv[2] === 'child') { - const { - fixtureKey, - mustCall, - setup, - } = require('./common.js'); - - const serverCfg = { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }; - - const clientKey = fixtureKey('openssh_new_rsa'); - - // Add key to the agent first - { - const { - error, status - } = spawnSync('ssh-add', [ clientKey.fullPath ], SPAWN_OPTS); - if (error || status !== 0) { - console.error('Failed to add key to agent'); - process.exit(1); - } - } - - const username = 'Agent User'; - const { server } = setup( - 'Agent authentication', - { - client: { username, agent: process.env.SSH_AUTH_SOCK }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} else { - { - const { - error, status - } = spawnSync('which', ['ssh-agent'], SPAWN_OPTS); - - if (error || status !== 0) { - console.log('No ssh-agent available, skipping agent test ...'); - process.exit(0); - } - } - - { - const { - error, status - } = spawnSync('which', ['ssh-add'], SPAWN_OPTS); - - if (error || status !== 0) { - console.log('No ssh-add available, skipping agent test ...'); - process.exit(0); - } - } - - const { - error, status - } = spawnSync('ssh-agent', - [ process.execPath, __filename, 'child' ], - { ...SPAWN_OPTS, stdio: 'inherit' }); - if (error || status !== 0) - throw new Error('Agent test failed'); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent.js b/reverse_engineering/node_modules/ssh2/test/test-userauth-agent.js deleted file mode 100644 index a28ad0b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -const debug = false; - -const { - fixtureKey, - mustCall, - setup, -} = require('./common.js'); -const { - AgentProtocol, - BaseAgent, - utils: { parseKey }, -} = require('../lib/index.js'); - -const serverCfg = { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }; - -const clientKey = fixtureKey('openssh_new_rsa'); - -{ - let getIdentitiesCount = 0; - let signCount = 0; - class MyAgent extends BaseAgent { - getIdentities(cb) { - assert.strictEqual(++getIdentitiesCount, 1); - // Ensure that no private portion of the key is used by re-parsing the - // public version of the key - cb(null, [ parseKey(clientKey.key.getPublicSSH()) ]); - } - sign(pubKey, data, options, cb) { - assert.strictEqual(++signCount, 1); - assert.strictEqual(pubKey.getPublicPEM(), clientKey.key.getPublicPEM()); - const sig = clientKey.key.sign(data, options.hash); - cb(null, sig); - } - } - - const username = 'Agent User'; - const { server } = setup( - 'Custom agent authentication', - { - client: { username, agent: new MyAgent() }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - assert.strictEqual(getIdentitiesCount, 1); - assert.strictEqual(signCount, 1); - conn.end(); - })); - })); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - - server.on('identities', mustCall((req) => { - setImmediate(() => server.failureReply(req)); - })); - client.getIdentities(mustCall((err, keys) => { - assert(err, 'Missing expected error'); - })); - - client.pipe(server).pipe(client); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - - server.on('identities', mustCall((req) => { - const keys = [ clientKey.key ]; - server.getIdentitiesReply(req, keys); - })); - client.getIdentities(mustCall((err, keys) => { - assert(!err, 'Unexpected error'); - assert.strictEqual(keys.length, 1); - assert.strictEqual(keys[0].isPrivateKey(), false); - assert.strictEqual(keys[0].getPublicPEM(), clientKey.key.getPublicPEM()); - })); - - client.pipe(server).pipe(client); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - const buf = Buffer.from('data to sign'); - - server.on('sign', mustCall((req, pubKey, data, options) => { - assert.strictEqual(pubKey.getPublicPEM(), clientKey.key.getPublicPEM()); - assert.deepStrictEqual(data, buf); - assert.strictEqual(options.hash, undefined); - server.failureReply(req); - })); - client.sign(clientKey.key.getPublicSSH(), - buf, - mustCall((err, signature) => { - assert(err, 'Missing expected error'); - })); - - client.pipe(server).pipe(client); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - const buf = Buffer.from('data to sign'); - - server.on('sign', mustCall((req, pubKey, data, options) => { - assert.strictEqual(pubKey.getPublicPEM(), clientKey.key.getPublicPEM()); - assert.deepStrictEqual(data, buf); - assert.strictEqual(options.hash, undefined); - server.signReply(req, clientKey.key.sign(data)); - })); - client.sign(clientKey.key.getPublicSSH(), - buf, - mustCall((err, signature) => { - assert(!err, 'Unexpected error'); - const pubKey = parseKey(clientKey.key.getPublicSSH()); - assert.strictEqual(pubKey.verify(buf, signature), true); - })); - - client.pipe(server).pipe(client); -} -{ - // Test that outstanding requests are handled upon unexpected closure of the - // protocol stream - - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - - server.on('identities', mustCall((req) => { - server.destroy(); - })); - client.getIdentities(mustCall((err) => { - assert(err, 'Missing expected error'); - })); - - client.pipe(server).pipe(client); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-userauth.js b/reverse_engineering/node_modules/ssh2/test/test-userauth.js deleted file mode 100644 index fb2fe9e..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-userauth.js +++ /dev/null @@ -1,608 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - fixtureKey, - mustCall, - mustNotCall, - setup, -} = require('./common.js'); - -const serverCfg = { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }; - -const debug = false; - -// Keys ======================================================================== -[ - { desc: 'RSA (old OpenSSH)', - clientKey: fixtureKey('id_rsa') }, - { desc: 'RSA (new OpenSSH)', - clientKey: fixtureKey('openssh_new_rsa') }, - { desc: 'RSA (encrypted)', - clientKey: fixtureKey('id_rsa_enc', 'foobarbaz'), - passphrase: 'foobarbaz' }, - { desc: 'DSA', - clientKey: fixtureKey('id_dsa') }, - { desc: 'ECDSA', - clientKey: fixtureKey('id_ecdsa') }, - { desc: 'PPK', - clientKey: fixtureKey('id_rsa.ppk') }, -].forEach((test) => { - const { desc, clientKey, passphrase } = test; - const username = 'Key User'; - const { server } = setup( - desc, - { - client: { username, privateKey: clientKey.raw, passphrase }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -}); - - -// Password ==================================================================== -{ - const username = 'Password User'; - const password = 'hi mom'; - const { server } = setup( - 'Password', - { - client: { username, password }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, - `Wrong password: ${ctx.password}`); - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = ''; - const password = 'hi mom'; - const { server } = setup( - 'Password (empty username)', - { - client: { username, password }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, - `Wrong password: ${ctx.password}`); - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const oldPassword = 'bar'; - const newPassword = 'baz'; - const changePrompt = 'Prithee changeth thy password'; - const { client, server } = setup( - 'Password (change requested)', - { - client: { username, password: oldPassword }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === oldPassword, - `Wrong old password: ${ctx.password}`); - ctx.requestChange(changePrompt, mustCall((newPassword_) => { - assert(newPassword_ === newPassword, - `Wrong new password: ${newPassword_}`); - ctx.accept(); - })); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('change password', mustCall((prompt, done) => { - assert(prompt === changePrompt, `Wrong password change prompt: ${prompt}`); - process.nextTick(done, newPassword); - })); -} - - -// Hostbased =================================================================== -{ - const localUsername = 'Local User Foo'; - const localHostname = 'Local Host Bar'; - const username = 'Hostbased User'; - const clientKey = fixtureKey('id_rsa'); - const { server } = setup( - 'Hostbased', - { - client: { - username, - privateKey: clientKey.raw, - localUsername, - localHostname, - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.method === 'hostbased', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - assert(ctx.signature, 'Expected signature'); - assert(ctx.localHostname === localHostname, 'Wrong local hostname'); - assert(ctx.localUsername === localUsername, 'Wrong local username'); - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify hostbased signature'); - - break; - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - - -// keyboard-interactive ======================================================== -{ - const username = 'Keyboard-Interactive User'; - const request = { - name: 'SSH2 Authentication', - instructions: 'These are instructions', - prompts: [ - { prompt: 'Password: ', echo: false }, - { prompt: 'Is the cake a lie? ', echo: true }, - ], - }; - const responses = [ - 'foobarbaz', - 'yes', - ]; - const { client, server } = setup( - 'Password (empty username)', - { - client: { - username, - tryKeyboard: true, - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'keyboard-interactive', - `Wrong auth method: ${ctx.method}`); - ctx.prompt(request.prompts, - request.name, - request.instructions, - mustCall((responses_) => { - assert.deepStrictEqual(responses_, responses); - ctx.accept(); - })); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('keyboard-interactive', - mustCall((name, instructions, lang, prompts, finish) => { - assert(name === request.name, `Wrong prompt name: ${name}`); - assert(instructions === request.instructions, - `Wrong prompt instructions: ${instructions}`); - assert.deepStrictEqual( - prompts, - request.prompts, - `Wrong prompts: ${inspect(prompts)}` - ); - process.nextTick(finish, responses); - })); -} - -// authHandler() tests ========================================================= -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { server } = setup( - 'authHandler() (sync)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return 'none'; - }), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { server } = setup( - 'authHandler() (async)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - process.nextTick(mustCall(cb), 'none'); - }), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { client, server } = setup( - 'authHandler() (no methods left -- sync)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return false; - }), - }, - server: serverCfg, - - debug, - noForceClientReady: true, - noForceServerReady: true, - } - ); - - // Remove default client error handler added by `setup()` since we are - // expecting an error in this case - client.removeAllListeners('error'); - - client.on('error', mustCall((err) => { - assert.strictEqual(err.level, 'client-authentication'); - assert(/configured authentication methods failed/i.test(err.message), - 'Wrong error message'); - })); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { client, server } = setup( - 'authHandler() (no methods left -- async)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - process.nextTick(mustCall(cb), false); - }), - }, - server: serverCfg, - - debug, - noForceClientReady: true, - noForceServerReady: true, - } - ); - - // Remove default client error handler added by `setup()` since we are - // expecting an error in this case - client.removeAllListeners('error'); - - client.on('error', mustCall((err) => { - assert.strictEqual(err.level, 'client-authentication'); - assert(/configured authentication methods failed/i.test(err.message), - 'Wrong error message'); - })); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const events = []; - const expectedEvents = [ - 'client', 'server', 'client', 'server' - ]; - let clientCalls = 0; - const { client, server } = setup( - 'authHandler() (multi-step)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - events.push('client'); - switch (++clientCalls) { - case 1: - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return 'publickey'; - case 2: - assert.deepStrictEqual( - methodsLeft, - ['password'], - `expected 'password' method left, saw: ${methodsLeft}` - ); - assert(partial === true, 'expected partial success'); - return 'password'; - } - }, 2), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let attempts = 0; - conn.on('authentication', mustCall((ctx) => { - assert(++attempts === clientCalls, 'server<->client state mismatch'); - assert(ctx.username === username, - `Unexpected username: ${ctx.username}`); - events.push('server'); - switch (attempts) { - case 1: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Unexpected key algo: ${ctx.key.algo}`); - assert.deepEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - ctx.reject(['password'], true); - break; - case 2: - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, - `Unexpected password: ${ctx.password}`); - ctx.accept(); - break; - } - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('close', mustCall(() => { - assert.deepStrictEqual(events, expectedEvents); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const { server } = setup( - 'authHandler() (custom auth configuration)', - { - client: { - username: 'bar', - password: '5678', - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return { - type: 'password', - username, - password, - }; - }), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'password', `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, `Unexpected password: ${ctx.password}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const { server } = setup( - 'authHandler() (simple construction with custom auth configuration)', - { - client: { - username: 'bar', - password: '5678', - - authHandler: [{ - type: 'password', - username, - password, - }], - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'password', `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, `Unexpected password: ${ctx.password}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test.js b/reverse_engineering/node_modules/ssh2/test/test.js deleted file mode 100644 index d0380f2..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const { spawnSync } = require('child_process'); -const { readdirSync } = require('fs'); -const { join } = require('path'); - -const files = readdirSync(__dirname).sort(); -for (const filename of files) { - if (filename.startsWith('test-')) { - const path = join(__dirname, filename); - console.log(`> Running ${filename} ...`); - const result = spawnSync(`${process.argv0} ${path}`, { - shell: true, - stdio: 'inherit', - windowsHide: true - }); - if (result.status !== 0) - process.exitCode = 1; - } -} diff --git a/reverse_engineering/node_modules/ssh2/util/build_pagent.bat b/reverse_engineering/node_modules/ssh2/util/build_pagent.bat deleted file mode 100644 index 9f5aaf8..0000000 --- a/reverse_engineering/node_modules/ssh2/util/build_pagent.bat +++ /dev/null @@ -1,2 +0,0 @@ -@cl /Ox pagent.c User32.lib -@del /Q *.obj \ No newline at end of file diff --git a/reverse_engineering/node_modules/ssh2/util/pagent.c b/reverse_engineering/node_modules/ssh2/util/pagent.c deleted file mode 100644 index e900491..0000000 --- a/reverse_engineering/node_modules/ssh2/util/pagent.c +++ /dev/null @@ -1,88 +0,0 @@ -#include -#include -#include - -#define AGENT_COPYDATA_ID 0x804e50ba -#define AGENT_MAX_MSGLEN 8192 - -#define GET_32BIT_MSB_FIRST(cp) \ - (((unsigned long)(unsigned char)(cp)[0] << 24) | \ - ((unsigned long)(unsigned char)(cp)[1] << 16) | \ - ((unsigned long)(unsigned char)(cp)[2] << 8) | \ - ((unsigned long)(unsigned char)(cp)[3])) - -#define GET_32BIT(cp) GET_32BIT_MSB_FIRST(cp) - -#define RET_ERR_BADARGS 10 -#define RET_ERR_UNAVAILABLE 11 -#define RET_ERR_NOMAP 12 -#define RET_ERR_BINSTDIN 13 -#define RET_ERR_BINSTDOUT 14 -#define RET_ERR_BADLEN 15 - -#define RET_NORESPONSE 1 -#define RET_RESPONSE 0 - -int main (int argc, const char* argv[]) { - HWND hwnd; - char *mapname; - HANDLE filemap; - unsigned char *p, *ret; - int id, retlen, inlen, n, rmode, r = RET_NORESPONSE; - COPYDATASTRUCT cds; - void *in; - - if (argc < 2) - return RET_ERR_BADARGS; - - hwnd = FindWindow("Pageant", "Pageant"); - if (!hwnd) - return RET_ERR_UNAVAILABLE; - - rmode = _setmode(_fileno(stdin), _O_BINARY); - if (rmode == -1) - return RET_ERR_BINSTDIN; - - rmode = _setmode(_fileno(stdout), _O_BINARY); - if (rmode == -1) - return RET_ERR_BINSTDOUT; - - inlen = atoi(argv[1]); - in = malloc(inlen); - n = fread(in, 1, inlen, stdin); - if (n != inlen) { - free(in); - return RET_ERR_BADLEN; - } - - mapname = malloc(32); - n = sprintf(mapname, "PageantRequest%08x", (unsigned)GetCurrentThreadId()); - - filemap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, - 0, AGENT_MAX_MSGLEN, mapname); - if (filemap == NULL || filemap == INVALID_HANDLE_VALUE) { - free(in); - free(mapname); - return RET_ERR_NOMAP; - } - - p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0); - memcpy(p, in, inlen); - cds.dwData = AGENT_COPYDATA_ID; - cds.cbData = 1 + n; - cds.lpData = mapname; - - id = SendMessage(hwnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) &cds); - if (id > 0) { - r = RET_RESPONSE; - retlen = 4 + GET_32BIT(p); - fwrite(p, 1, retlen, stdout); - } - - free(in); - free(mapname); - UnmapViewOfFile(p); - CloseHandle(filemap); - - return r; -} diff --git a/reverse_engineering/node_modules/ssh2/util/pagent.exe b/reverse_engineering/node_modules/ssh2/util/pagent.exe deleted file mode 100644 index 6e8a71c..0000000 Binary files a/reverse_engineering/node_modules/ssh2/util/pagent.exe and /dev/null differ diff --git a/reverse_engineering/node_modules/stream-combiner/.npmignore b/reverse_engineering/node_modules/stream-combiner/.npmignore deleted file mode 100644 index 13abef4..0000000 --- a/reverse_engineering/node_modules/stream-combiner/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -node_modules/* -npm_debug.log diff --git a/reverse_engineering/node_modules/stream-combiner/.travis.yml b/reverse_engineering/node_modules/stream-combiner/.travis.yml deleted file mode 100644 index 895dbd3..0000000 --- a/reverse_engineering/node_modules/stream-combiner/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/reverse_engineering/node_modules/stream-combiner/LICENSE b/reverse_engineering/node_modules/stream-combiner/LICENSE deleted file mode 100644 index 6d03581..0000000 --- a/reverse_engineering/node_modules/stream-combiner/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012 'Dominic Tarr' - -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom -the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/stream-combiner/README.md b/reverse_engineering/node_modules/stream-combiner/README.md deleted file mode 100644 index 9c1b52e..0000000 --- a/reverse_engineering/node_modules/stream-combiner/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# stream-combiner - -[![npm version](https://img.shields.io/npm/v/stream-combiner.svg)](https://npmjs.org/package/stream-combiner) -[![Travis CI](https://travis-ci.org/dominictarr/stream-combiner.svg)](https://travis-ci.org/dominictarr/stream-combiner) - -## Combine (stream1,...,streamN) - -Turn a pipeline into a single stream. `Combine` returns a stream that writes to the first stream -and reads from the last stream. - -Listening for 'error' will recieve errors from all streams inside the pipe. - -```js -var Combine = require('stream-combiner') -var es = require('event-stream') - -Combine( // connect streams together with `pipe` - process.openStdin(), // open stdin - es.split(), // split stream to break on newlines - es.map(function (data, callback) { // turn this async function into a stream - var repr = util.inspect(JSON.parse(data)) // render it nicely - callback(null, repr) - }), - process.stdout // pipe it to stdout ! -) -``` - -Can also be called with an array: - -```js -var combinedStream = Combine([ - stream1, - stream2, -]); -``` - -Or to combine gulp plugins: - -```js -function coffeePipe() { - return Combine( - coffeescript(), - coffeelint.reporter('fail').on('error', function(){ - gutil.beep() - gulp.run('lint') - }) -} - -//usage: -gulp.src().pipe(coffeePipe()); -``` - -## License - -MIT diff --git a/reverse_engineering/node_modules/stream-combiner/index.js b/reverse_engineering/node_modules/stream-combiner/index.js deleted file mode 100644 index e23374c..0000000 --- a/reverse_engineering/node_modules/stream-combiner/index.js +++ /dev/null @@ -1,45 +0,0 @@ -var duplexer = require('duplexer') -var through = require('through') - -module.exports = function () { - var streams - - if(arguments.length == 1 && Array.isArray(arguments[0])) { - streams = arguments[0] - } else { - streams = [].slice.call(arguments) - } - - if(streams.length == 0) - return through() - else if(streams.length == 1) - return streams[0] - - var first = streams[0] - , last = streams[streams.length - 1] - , thepipe = duplexer(first, last) - - //pipe all the streams together - - function recurse (streams) { - if(streams.length < 2) - return - streams[0].pipe(streams[1]) - recurse(streams.slice(1)) - } - - recurse(streams) - - function onerror () { - var args = [].slice.call(arguments) - args.unshift('error') - thepipe.emit.apply(thepipe, args) - } - - //es.duplex already reemits the error from the first and last stream. - //add a listener for the inner streams in the pipeline. - for(var i = 1; i < streams.length - 1; i ++) - streams[i].on('error', onerror) - - return thepipe -} diff --git a/reverse_engineering/node_modules/stream-combiner/package.json b/reverse_engineering/node_modules/stream-combiner/package.json deleted file mode 100644 index 628c6c4..0000000 --- a/reverse_engineering/node_modules/stream-combiner/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "stream-combiner", - "version": "0.2.2", - "homepage": "https://github.com/dominictarr/stream-combiner", - "repository": { - "type": "git", - "url": "git://github.com/dominictarr/stream-combiner.git" - }, - "dependencies": { - "duplexer": "~0.1.1", - "through": "~2.3.4" - }, - "devDependencies": { - "tape": "~2.3.0", - "event-stream": "~3.0.7" - }, - "scripts": { - "test": "set -e; for t in test/*.js; do node $t; done" - }, - "author": "'Dominic Tarr' (http://dominictarr.com)", - "license": "MIT" -} diff --git a/reverse_engineering/node_modules/stream-combiner/test/index.js b/reverse_engineering/node_modules/stream-combiner/test/index.js deleted file mode 100644 index 97cd73e..0000000 --- a/reverse_engineering/node_modules/stream-combiner/test/index.js +++ /dev/null @@ -1,65 +0,0 @@ -var es = require('event-stream') -var combine = require('..') -var test = require('tape') - -test('do not duplicate errors', function (test) { - - var errors = 0; - var pipe = combine( - es.through(function(data) { - return this.emit('data', data); - }), - es.through(function(data) { - return this.emit('error', new Error(data)); - }) - ) - - pipe.on('error', function(err) { - errors++ - test.ok(errors, 'expected error count') - process.nextTick(function () { - return test.end(); - }) - }) - - return pipe.write('meh'); -}) - -test('3 pipe do not duplicate errors', function (test) { - - var errors = 0; - var pipe = combine( - es.through(function(data) { - return this.emit('data', data); - }), - es.through(function(data) { - return this.emit('error', new Error(data)); - }), - es.through() - ) - - pipe.on('error', function(err) { - errors++ - test.ok(errors, 'expected error count') - process.nextTick(function () { - return test.end(); - }) - }) - - return pipe.write('meh'); - -}) - -test('0 argument through stream', function (test) { - test.plan(3) - var pipe = combine() - , expected = [ 'beep', 'boop', 'robots' ] - - pipe.pipe(es.through(function(data) { - test.equal(data, expected.shift()) - })) - pipe.write('beep') - pipe.write('boop') - pipe.end('robots') -}) - diff --git a/reverse_engineering/node_modules/string-width/index.d.ts b/reverse_engineering/node_modules/string-width/index.d.ts deleted file mode 100644 index 12b5309..0000000 --- a/reverse_engineering/node_modules/string-width/index.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -declare const stringWidth: { - /** - Get the visual width of a string - the number of columns required to display it. - - Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. - - @example - ``` - import stringWidth = require('string-width'); - - stringWidth('a'); - //=> 1 - - stringWidth('古'); - //=> 2 - - stringWidth('\u001B[1m古\u001B[22m'); - //=> 2 - ``` - */ - (string: string): number; - - // TODO: remove this in the next major version, refactor the whole definition to: - // declare function stringWidth(string: string): number; - // export = stringWidth; - default: typeof stringWidth; -} - -export = stringWidth; diff --git a/reverse_engineering/node_modules/string-width/index.js b/reverse_engineering/node_modules/string-width/index.js deleted file mode 100644 index f4d261a..0000000 --- a/reverse_engineering/node_modules/string-width/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; -const stripAnsi = require('strip-ansi'); -const isFullwidthCodePoint = require('is-fullwidth-code-point'); -const emojiRegex = require('emoji-regex'); - -const stringWidth = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; -}; - -module.exports = stringWidth; -// TODO: remove this in the next major version -module.exports.default = stringWidth; diff --git a/reverse_engineering/node_modules/string-width/license b/reverse_engineering/node_modules/string-width/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/string-width/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/string-width/package.json b/reverse_engineering/node_modules/string-width/package.json deleted file mode 100644 index 28ba7b4..0000000 --- a/reverse_engineering/node_modules/string-width/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "string-width", - "version": "4.2.3", - "description": "Get the visual width of a string - the number of columns required to display it", - "license": "MIT", - "repository": "sindresorhus/string-width", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "string", - "character", - "unicode", - "width", - "visual", - "column", - "columns", - "fullwidth", - "full-width", - "full", - "ansi", - "escape", - "codes", - "cli", - "command-line", - "terminal", - "console", - "cjk", - "chinese", - "japanese", - "korean", - "fixed-width" - ], - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.1", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/string-width/readme.md b/reverse_engineering/node_modules/string-width/readme.md deleted file mode 100644 index bdd3141..0000000 --- a/reverse_engineering/node_modules/string-width/readme.md +++ /dev/null @@ -1,50 +0,0 @@ -# string-width - -> Get the visual width of a string - the number of columns required to display it - -Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. - -Useful to be able to measure the actual width of command-line output. - - -## Install - -``` -$ npm install string-width -``` - - -## Usage - -```js -const stringWidth = require('string-width'); - -stringWidth('a'); -//=> 1 - -stringWidth('古'); -//=> 2 - -stringWidth('\u001B[1m古\u001B[22m'); -//=> 2 -``` - - -## Related - -- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module -- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string -- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string - - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/reverse_engineering/node_modules/string_decoder/.travis.yml b/reverse_engineering/node_modules/string_decoder/.travis.yml deleted file mode 100644 index 3347a72..0000000 --- a/reverse_engineering/node_modules/string_decoder/.travis.yml +++ /dev/null @@ -1,50 +0,0 @@ -sudo: false -language: node_js -before_install: - - npm install -g npm@2 - - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g -notifications: - email: false -matrix: - fast_finish: true - include: - - node_js: '0.8' - env: - - TASK=test - - NPM_LEGACY=true - - node_js: '0.10' - env: - - TASK=test - - NPM_LEGACY=true - - node_js: '0.11' - env: - - TASK=test - - NPM_LEGACY=true - - node_js: '0.12' - env: - - TASK=test - - NPM_LEGACY=true - - node_js: 1 - env: - - TASK=test - - NPM_LEGACY=true - - node_js: 2 - env: - - TASK=test - - NPM_LEGACY=true - - node_js: 3 - env: - - TASK=test - - NPM_LEGACY=true - - node_js: 4 - env: TASK=test - - node_js: 5 - env: TASK=test - - node_js: 6 - env: TASK=test - - node_js: 7 - env: TASK=test - - node_js: 8 - env: TASK=test - - node_js: 9 - env: TASK=test diff --git a/reverse_engineering/node_modules/string_decoder/LICENSE b/reverse_engineering/node_modules/string_decoder/LICENSE deleted file mode 100644 index 778edb2..0000000 --- a/reverse_engineering/node_modules/string_decoder/LICENSE +++ /dev/null @@ -1,48 +0,0 @@ -Node.js is licensed for use as follows: - -""" -Copyright Node.js contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" - -This license applies to parts of Node.js originating from the -https://github.com/joyent/node repository: - -""" -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" - diff --git a/reverse_engineering/node_modules/string_decoder/README.md b/reverse_engineering/node_modules/string_decoder/README.md deleted file mode 100644 index 5fd5831..0000000 --- a/reverse_engineering/node_modules/string_decoder/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# string_decoder - -***Node-core v8.9.4 string_decoder for userland*** - - -[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) -[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) - - -```bash -npm install --save string_decoder -``` - -***Node-core string_decoder for userland*** - -This package is a mirror of the string_decoder implementation in Node-core. - -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). - -As of version 1.0.0 **string_decoder** uses semantic versioning. - -## Previous versions - -Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. - -## Update - -The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. - -## Streams Working Group - -`string_decoder` is maintained by the Streams Working Group, which -oversees the development and maintenance of the Streams API within -Node.js. The responsibilities of the Streams Working Group include: - -* Addressing stream issues on the Node.js issue tracker. -* Authoring and editing stream documentation within the Node.js project. -* Reviewing changes to stream subclasses within the Node.js project. -* Redirecting changes to streams from the Node.js project to this - project. -* Assisting in the implementation of stream providers within Node.js. -* Recommending versions of `readable-stream` to be included in Node.js. -* Messaging about the future of streams to give the community advance - notice of changes. - -See [readable-stream](https://github.com/nodejs/readable-stream) for -more details. diff --git a/reverse_engineering/node_modules/string_decoder/lib/string_decoder.js b/reverse_engineering/node_modules/string_decoder/lib/string_decoder.js deleted file mode 100644 index 2e89e63..0000000 --- a/reverse_engineering/node_modules/string_decoder/lib/string_decoder.js +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'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; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -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; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -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 < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -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; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -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); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -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 >= 0xD800 && c <= 0xDBFF) { - 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); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -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; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/LICENSE b/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/README.md b/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg -[travis-url]: https://travis-ci.org/feross/safe-buffer -[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg -[npm-url]: https://npmjs.org/package/safe-buffer -[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg -[downloads-url]: https://npmjs.org/package/safe-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### Safer Node.js Buffer API - -**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, -`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** - -**Uses the built-in implementation when available.** - -## install - -``` -npm install safe-buffer -``` - -## usage - -The goal of this package is to provide a safe replacement for the node.js `Buffer`. - -It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to -the top of your node.js modules: - -```js -var Buffer = require('safe-buffer').Buffer - -// Existing buffer code will continue to work without issues: - -new Buffer('hey', 'utf8') -new Buffer([1, 2, 3], 'utf8') -new Buffer(obj) -new Buffer(16) // create an uninitialized buffer (potentially unsafe) - -// But you can use these new explicit APIs to make clear what you want: - -Buffer.from('hey', 'utf8') // convert from many types to a Buffer -Buffer.alloc(16) // create a zero-filled buffer (safe) -Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) -``` - -## api - -### Class Method: Buffer.from(array) - - -* `array` {Array} - -Allocates a new `Buffer` using an `array` of octets. - -```js -const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); - // creates a new Buffer containing ASCII bytes - // ['b','u','f','f','e','r'] -``` - -A `TypeError` will be thrown if `array` is not an `Array`. - -### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - - -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or - a `new ArrayBuffer()` -* `byteOffset` {Number} Default: `0` -* `length` {Number} Default: `arrayBuffer.length - byteOffset` - -When passed a reference to the `.buffer` property of a `TypedArray` instance, -the newly created `Buffer` will share the same allocated memory as the -TypedArray. - -```js -const arr = new Uint16Array(2); -arr[0] = 5000; -arr[1] = 4000; - -const buf = Buffer.from(arr.buffer); // shares the memory with arr; - -console.log(buf); - // Prints: - -// changing the TypedArray changes the Buffer also -arr[1] = 6000; - -console.log(buf); - // Prints: -``` - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const ab = new ArrayBuffer(10); -const buf = Buffer.from(ab, 0, 2); -console.log(buf.length); - // Prints: 2 -``` - -A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. - -### Class Method: Buffer.from(buffer) - - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = Buffer.from('buffer'); -const buf2 = Buffer.from(buf1); - -buf1[0] = 0x61; -console.log(buf1.toString()); - // 'auffer' -console.log(buf2.toString()); - // 'buffer' (copy is not changed) -``` - -A `TypeError` will be thrown if `buffer` is not a `Buffer`. - -### Class Method: Buffer.from(str[, encoding]) - - -* `str` {String} String to encode. -* `encoding` {String} Encoding to use, Default: `'utf8'` - -Creates a new `Buffer` containing the given JavaScript string `str`. If -provided, the `encoding` parameter identifies the character encoding. -If not provided, `encoding` defaults to `'utf8'`. - -```js -const buf1 = Buffer.from('this is a tést'); -console.log(buf1.toString()); - // prints: this is a tést -console.log(buf1.toString('ascii')); - // prints: this is a tC)st - -const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); -console.log(buf2.toString()); - // prints: this is a tést -``` - -A `TypeError` will be thrown if `str` is not a string. - -### Class Method: Buffer.alloc(size[, fill[, encoding]]) - - -* `size` {Number} -* `fill` {Value} Default: `undefined` -* `encoding` {String} Default: `utf8` - -Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the -`Buffer` will be *zero-filled*. - -```js -const buf = Buffer.alloc(5); -console.log(buf); - // -``` - -The `size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -If `fill` is specified, the allocated `Buffer` will be initialized by calling -`buf.fill(fill)`. See [`buf.fill()`][] for more information. - -```js -const buf = Buffer.alloc(5, 'a'); -console.log(buf); - // -``` - -If both `fill` and `encoding` are specified, the allocated `Buffer` will be -initialized by calling `buf.fill(fill, encoding)`. For example: - -```js -const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -console.log(buf); - // -``` - -Calling `Buffer.alloc(size)` can be significantly slower than the alternative -`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance -contents will *never contain sensitive data*. - -A `TypeError` will be thrown if `size` is not a number. - -### Class Method: Buffer.allocUnsafe(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must -be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit -architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is -thrown. A zero-length Buffer will be created if a `size` less than or equal to -0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -```js -const buf = Buffer.allocUnsafe(5); -console.log(buf); - // - // (octets will be different, every time) -buf.fill(0); -console.log(buf); - // -``` - -A `TypeError` will be thrown if `size` is not a number. - -Note that the `Buffer` module pre-allocates an internal `Buffer` instance of -size `Buffer.poolSize` that is used as a pool for the fast allocation of new -`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated -`new Buffer(size)` constructor) only when `size` is less than or equal to -`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default -value of `Buffer.poolSize` is `8192` but can be modified. - -Use of this pre-allocated internal memory pool is a key difference between -calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. -Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer -pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal -Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The -difference is subtle but can be important when an application requires the -additional performance that `Buffer.allocUnsafe(size)` provides. - -### Class Method: Buffer.allocUnsafeSlow(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The -`size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, -allocations under 4KB are, by default, sliced from a single pre-allocated -`Buffer`. This allows applications to avoid the garbage collection overhead of -creating many individually allocated Buffers. This approach improves both -performance and memory usage by eliminating the need to track and cleanup as -many `Persistent` objects. - -However, in the case where a developer may need to retain a small chunk of -memory from a pool for an indeterminate amount of time, it may be appropriate -to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then -copy out the relevant bits. - -```js -// need to keep around a few small chunks of memory -const store = []; - -socket.on('readable', () => { - const data = socket.read(); - // allocate for retained data - const sb = Buffer.allocUnsafeSlow(10); - // copy the data into the new allocation - data.copy(sb, 0, 0, 10); - store.push(sb); -}); -``` - -Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* -a developer has observed undue memory retention in their applications. - -A `TypeError` will be thrown if `size` is not a number. - -### All the Rest - -The rest of the `Buffer` API is exactly the same as in node.js. -[See the docs](https://nodejs.org/api/buffer.html). - - -## Related links - -- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) -- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) - -## Why is `Buffer` unsafe? - -Today, the node.js `Buffer` constructor is overloaded to handle many different argument -types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), -`ArrayBuffer`, and also `Number`. - -The API is optimized for convenience: you can throw any type at it, and it will try to do -what you want. - -Because the Buffer constructor is so powerful, you often see code like this: - -```js -// Convert UTF-8 strings to hex -function toHex (str) { - return new Buffer(str).toString('hex') -} -``` - -***But what happens if `toHex` is called with a `Number` argument?*** - -### Remote Memory Disclosure - -If an attacker can make your program call the `Buffer` constructor with a `Number` -argument, then they can make it allocate uninitialized memory from the node.js process. -This could potentially disclose TLS private keys, user data, or database passwords. - -When the `Buffer` constructor is passed a `Number` argument, it returns an -**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like -this, you **MUST** overwrite the contents before returning it to the user. - -From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): - -> `new Buffer(size)` -> -> - `size` Number -> -> The underlying memory for `Buffer` instances created in this way is not initialized. -> **The contents of a newly created `Buffer` are unknown and could contain sensitive -> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. - -(Emphasis our own.) - -Whenever the programmer intended to create an uninitialized `Buffer` you often see code -like this: - -```js -var buf = new Buffer(16) - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### Would this ever be a problem in real code? - -Yes. It's surprisingly common to forget to check the type of your variables in a -dynamically-typed language like JavaScript. - -Usually the consequences of assuming the wrong type is that your program crashes with an -uncaught exception. But the failure mode for forgetting to check the type of arguments to -the `Buffer` constructor is more catastrophic. - -Here's an example of a vulnerable service that takes a JSON payload and converts it to -hex: - -```js -// Take a JSON payload {str: "some string"} and convert it to hex -var server = http.createServer(function (req, res) { - var data = '' - req.setEncoding('utf8') - req.on('data', function (chunk) { - data += chunk - }) - req.on('end', function () { - var body = JSON.parse(data) - res.end(new Buffer(body.str).toString('hex')) - }) -}) - -server.listen(8080) -``` - -In this example, an http client just has to send: - -```json -{ - "str": 1000 -} -``` - -and it will get back 1,000 bytes of uninitialized memory from the server. - -This is a very serious bug. It's similar in severity to the -[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process -memory by remote attackers. - - -### Which real-world packages were vulnerable? - -#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) - -[Mathias Buus](https://github.com/mafintosh) and I -([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, -[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow -anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get -them to reveal 20 bytes at a time of uninitialized memory from the node.js process. - -Here's -[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) -that fixed it. We released a new fixed version, created a -[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all -vulnerable versions on npm so users will get a warning to upgrade to a newer version. - -#### [`ws`](https://www.npmjs.com/package/ws) - -That got us wondering if there were other vulnerable packages. Sure enough, within a short -period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the -most popular WebSocket implementation in node.js. - -If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as -expected, then uninitialized server memory would be disclosed to the remote peer. - -These were the vulnerable methods: - -```js -socket.send(number) -socket.ping(number) -socket.pong(number) -``` - -Here's a vulnerable socket server with some echo functionality: - -```js -server.on('connection', function (socket) { - socket.on('message', function (message) { - message = JSON.parse(message) - if (message.type === 'echo') { - socket.send(message.data) // send back the user's message - } - }) -}) -``` - -`socket.send(number)` called on the server, will disclose server memory. - -Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue -was fixed, with a more detailed explanation. Props to -[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the -[Node Security Project disclosure](https://nodesecurity.io/advisories/67). - - -### What's the solution? - -It's important that node.js offers a fast way to get memory otherwise performance-critical -applications would needlessly get a lot slower. - -But we need a better way to *signal our intent* as programmers. **When we want -uninitialized memory, we should request it explicitly.** - -Sensitive functionality should not be packed into a developer-friendly API that loosely -accepts many different types. This type of API encourages the lazy practice of passing -variables in without checking the type very carefully. - -#### A new API: `Buffer.allocUnsafe(number)` - -The functionality of creating buffers with uninitialized memory should be part of another -API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that -frequently gets user input of all sorts of different types passed into it. - -```js -var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### How do we fix node.js core? - -We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as -`semver-major`) which defends against one case: - -```js -var str = 16 -new Buffer(str, 'utf8') -``` - -In this situation, it's implied that the programmer intended the first argument to be a -string, since they passed an encoding as a second argument. Today, node.js will allocate -uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not -what the programmer intended. - -But this is only a partial solution, since if the programmer does `new Buffer(variable)` -(without an `encoding` parameter) there's no way to know what they intended. If `variable` -is sometimes a number, then uninitialized memory will sometimes be returned. - -### What's the real long-term fix? - -We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when -we need uninitialized memory. But that would break 1000s of packages. - -~~We believe the best solution is to:~~ - -~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ - -~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ - -#### Update - -We now support adding three new APIs: - -- `Buffer.from(value)` - convert from any type to a buffer -- `Buffer.alloc(size)` - create a zero-filled buffer -- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size - -This solves the core problem that affected `ws` and `bittorrent-dht` which is -`Buffer(variable)` getting tricked into taking a number argument. - -This way, existing code continues working and the impact on the npm ecosystem will be -minimal. Over time, npm maintainers can migrate performance-critical code to use -`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. - - -### Conclusion - -We think there's a serious design issue with the `Buffer` API as it exists today. It -promotes insecure software by putting high-risk functionality into a convenient API -with friendly "developer ergonomics". - -This wasn't merely a theoretical exercise because we found the issue in some of the -most popular npm packages. - -Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of -`buffer`. - -```js -var Buffer = require('safe-buffer').Buffer -``` - -Eventually, we hope that node.js core can switch to this new, safer behavior. We believe -the impact on the ecosystem would be minimal since it's not a breaking change. -Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while -older, insecure packages would magically become safe from this attack vector. - - -## links - -- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) -- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) -- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) - - -## credit - -The original issues in `bittorrent-dht` -([disclosure](https://nodesecurity.io/advisories/68)) and -`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by -[Mathias Buus](https://github.com/mafintosh) and -[Feross Aboukhadijeh](http://feross.org/). - -Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues -and for his work running the [Node Security Project](https://nodesecurity.io/). - -Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and -auditing the code. - - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts b/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -declare module "safe-buffer" { - export class Buffer { - length: number - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor (str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor (size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor (arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor (buffer: Buffer); - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; - } -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/index.js b/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/index.js deleted file mode 100644 index 22438da..0000000 --- a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -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 { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -// Copy static methods from Buffer -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) -} diff --git a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/package.json b/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/package.json deleted file mode 100644 index 623fbc3..0000000 --- a/reverse_engineering/node_modules/string_decoder/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "safe-buffer", - "description": "Safer Node.js Buffer API", - "version": "5.1.2", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "devDependencies": { - "standard": "*", - "tape": "^4.0.0" - }, - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test/*.js" - } -} diff --git a/reverse_engineering/node_modules/string_decoder/package.json b/reverse_engineering/node_modules/string_decoder/package.json deleted file mode 100644 index 518c3eb..0000000 --- a/reverse_engineering/node_modules/string_decoder/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "string_decoder", - "version": "1.1.1", - "description": "The string_decoder module from Node core", - "main": "lib/string_decoder.js", - "dependencies": { - "safe-buffer": "~5.1.0" - }, - "devDependencies": { - "babel-polyfill": "^6.23.0", - "core-util-is": "^1.0.2", - "inherits": "^2.0.3", - "tap": "~0.4.8" - }, - "scripts": { - "test": "tap test/parallel/*.js && node test/verify-dependencies", - "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/nodejs/string_decoder.git" - }, - "homepage": "https://github.com/nodejs/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT" -} diff --git a/reverse_engineering/node_modules/strip-ansi/index.d.ts b/reverse_engineering/node_modules/strip-ansi/index.d.ts deleted file mode 100644 index 907fccc..0000000 --- a/reverse_engineering/node_modules/strip-ansi/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** -Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. - -@example -``` -import stripAnsi = require('strip-ansi'); - -stripAnsi('\u001B[4mUnicorn\u001B[0m'); -//=> 'Unicorn' - -stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); -//=> 'Click' -``` -*/ -declare function stripAnsi(string: string): string; - -export = stripAnsi; diff --git a/reverse_engineering/node_modules/strip-ansi/index.js b/reverse_engineering/node_modules/strip-ansi/index.js deleted file mode 100644 index 9a593df..0000000 --- a/reverse_engineering/node_modules/strip-ansi/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; -const ansiRegex = require('ansi-regex'); - -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/reverse_engineering/node_modules/strip-ansi/license b/reverse_engineering/node_modules/strip-ansi/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/strip-ansi/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/strip-ansi/package.json b/reverse_engineering/node_modules/strip-ansi/package.json deleted file mode 100644 index 1a41108..0000000 --- a/reverse_engineering/node_modules/strip-ansi/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "strip-ansi", - "version": "6.0.1", - "description": "Strip ANSI escape codes from a string", - "license": "MIT", - "repository": "chalk/strip-ansi", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "strip", - "trim", - "remove", - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "devDependencies": { - "ava": "^2.4.0", - "tsd": "^0.10.0", - "xo": "^0.25.3" - } -} diff --git a/reverse_engineering/node_modules/strip-ansi/readme.md b/reverse_engineering/node_modules/strip-ansi/readme.md deleted file mode 100644 index 7c4b56d..0000000 --- a/reverse_engineering/node_modules/strip-ansi/readme.md +++ /dev/null @@ -1,46 +0,0 @@ -# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) - -> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string - - -## Install - -``` -$ npm install strip-ansi -``` - - -## Usage - -```js -const stripAnsi = require('strip-ansi'); - -stripAnsi('\u001B[4mUnicorn\u001B[0m'); -//=> 'Unicorn' - -stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); -//=> 'Click' -``` - - -## strip-ansi for enterprise - -Available as part of the Tidelift Subscription. - -The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - - -## Related - -- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module -- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module -- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes -- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes -- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right - - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - diff --git a/reverse_engineering/node_modules/through/.travis.yml b/reverse_engineering/node_modules/through/.travis.yml deleted file mode 100644 index c693a93..0000000 --- a/reverse_engineering/node_modules/through/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - "0.10" diff --git a/reverse_engineering/node_modules/through/LICENSE.APACHE2 b/reverse_engineering/node_modules/through/LICENSE.APACHE2 deleted file mode 100644 index 6366c04..0000000 --- a/reverse_engineering/node_modules/through/LICENSE.APACHE2 +++ /dev/null @@ -1,15 +0,0 @@ -Apache License, Version 2.0 - -Copyright (c) 2011 Dominic Tarr - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/reverse_engineering/node_modules/through/LICENSE.MIT b/reverse_engineering/node_modules/through/LICENSE.MIT deleted file mode 100644 index 6eafbd7..0000000 --- a/reverse_engineering/node_modules/through/LICENSE.MIT +++ /dev/null @@ -1,24 +0,0 @@ -The MIT License - -Copyright (c) 2011 Dominic Tarr - -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom -the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/through/index.js b/reverse_engineering/node_modules/through/index.js deleted file mode 100644 index ca5fc59..0000000 --- a/reverse_engineering/node_modules/through/index.js +++ /dev/null @@ -1,108 +0,0 @@ -var Stream = require('stream') - -// through -// -// a stream that does nothing but re-emit the input. -// useful for aggregating a series of changing but not ending streams into one stream) - -exports = module.exports = through -through.through = through - -//create a readable writable stream. - -function through (write, end, opts) { - write = write || function (data) { this.queue(data) } - end = end || function () { this.queue(null) } - - var ended = false, destroyed = false, buffer = [], _ended = false - var stream = new Stream() - stream.readable = stream.writable = true - stream.paused = false - -// stream.autoPause = !(opts && opts.autoPause === false) - stream.autoDestroy = !(opts && opts.autoDestroy === false) - - stream.write = function (data) { - write.call(this, data) - return !stream.paused - } - - function drain() { - while(buffer.length && !stream.paused) { - var data = buffer.shift() - if(null === data) - return stream.emit('end') - else - stream.emit('data', data) - } - } - - stream.queue = stream.push = function (data) { -// console.error(ended) - if(_ended) return stream - if(data === null) _ended = true - buffer.push(data) - drain() - return stream - } - - //this will be registered as the first 'end' listener - //must call destroy next tick, to make sure we're after any - //stream piped from here. - //this is only a problem if end is not emitted synchronously. - //a nicer way to do this is to make sure this is the last listener for 'end' - - stream.on('end', function () { - stream.readable = false - if(!stream.writable && stream.autoDestroy) - process.nextTick(function () { - stream.destroy() - }) - }) - - function _end () { - stream.writable = false - end.call(stream) - if(!stream.readable && stream.autoDestroy) - stream.destroy() - } - - stream.end = function (data) { - if(ended) return - ended = true - if(arguments.length) stream.write(data) - _end() // will emit or queue - return stream - } - - stream.destroy = function () { - if(destroyed) return - destroyed = true - ended = true - buffer.length = 0 - stream.writable = stream.readable = false - stream.emit('close') - return stream - } - - stream.pause = function () { - if(stream.paused) return - stream.paused = true - return stream - } - - stream.resume = function () { - if(stream.paused) { - stream.paused = false - stream.emit('resume') - } - drain() - //may have become paused again, - //as drain emits 'data'. - if(!stream.paused) - stream.emit('drain') - return stream - } - return stream -} - diff --git a/reverse_engineering/node_modules/through/package.json b/reverse_engineering/node_modules/through/package.json deleted file mode 100644 index 9862189..0000000 --- a/reverse_engineering/node_modules/through/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "through", - "version": "2.3.8", - "description": "simplified stream construction", - "main": "index.js", - "scripts": { - "test": "set -e; for t in test/*.js; do node $t; done" - }, - "devDependencies": { - "stream-spec": "~0.3.5", - "tape": "~2.3.2", - "from": "~0.1.3" - }, - "keywords": [ - "stream", - "streams", - "user-streams", - "pipe" - ], - "author": "Dominic Tarr (dominictarr.com)", - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/dominictarr/through.git" - }, - "homepage": "https://github.com/dominictarr/through", - "testling": { - "browsers": [ - "ie/8..latest", - "ff/15..latest", - "chrome/20..latest", - "safari/5.1..latest" - ], - "files": "test/*.js" - } -} diff --git a/reverse_engineering/node_modules/through/readme.markdown b/reverse_engineering/node_modules/through/readme.markdown deleted file mode 100644 index cb34c81..0000000 --- a/reverse_engineering/node_modules/through/readme.markdown +++ /dev/null @@ -1,64 +0,0 @@ -#through - -[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through) -[![testling badge](https://ci.testling.com/dominictarr/through.png)](https://ci.testling.com/dominictarr/through) - -Easy way to create a `Stream` that is both `readable` and `writable`. - -* Pass in optional `write` and `end` methods. -* `through` takes care of pause/resume logic if you use `this.queue(data)` instead of `this.emit('data', data)`. -* Use `this.pause()` and `this.resume()` to manage flow. -* Check `this.paused` to see current flow state. (`write` always returns `!this.paused`). - -This function is the basis for most of the synchronous streams in -[event-stream](http://github.com/dominictarr/event-stream). - -``` js -var through = require('through') - -through(function write(data) { - this.queue(data) //data *must* not be null - }, - function end () { //optional - this.queue(null) - }) -``` - -Or, can also be used _without_ buffering on pause, use `this.emit('data', data)`, -and this.emit('end') - -``` js -var through = require('through') - -through(function write(data) { - this.emit('data', data) - //this.pause() - }, - function end () { //optional - this.emit('end') - }) -``` - -## Extended Options - -You will probably not need these 99% of the time. - -### autoDestroy=false - -By default, `through` emits close when the writable -and readable side of the stream has ended. -If that is not desired, set `autoDestroy=false`. - -``` js -var through = require('through') - -//like this -var ts = through(write, end, {autoDestroy: false}) -//or like this -var ts = through(write, end) -ts.autoDestroy = false -``` - -## License - -MIT / Apache2 diff --git a/reverse_engineering/node_modules/through/test/async.js b/reverse_engineering/node_modules/through/test/async.js deleted file mode 100644 index 46bdbae..0000000 --- a/reverse_engineering/node_modules/through/test/async.js +++ /dev/null @@ -1,28 +0,0 @@ -var from = require('from') -var through = require('../') - -var tape = require('tape') - -tape('simple async example', function (t) { - - var n = 0, expected = [1,2,3,4,5], actual = [] - from(expected) - .pipe(through(function(data) { - this.pause() - n ++ - setTimeout(function(){ - console.log('pushing data', data) - this.push(data) - this.resume() - }.bind(this), 300) - })).pipe(through(function(data) { - console.log('pushing data second time', data); - this.push(data) - })).on('data', function (d) { - actual.push(d) - }).on('end', function() { - t.deepEqual(actual, expected) - t.end() - }) - -}) diff --git a/reverse_engineering/node_modules/through/test/auto-destroy.js b/reverse_engineering/node_modules/through/test/auto-destroy.js deleted file mode 100644 index 9a8fd00..0000000 --- a/reverse_engineering/node_modules/through/test/auto-destroy.js +++ /dev/null @@ -1,30 +0,0 @@ -var test = require('tape') -var through = require('../') - -// must emit end before close. - -test('end before close', function (assert) { - var ts = through() - ts.autoDestroy = false - var ended = false, closed = false - - ts.on('end', function () { - assert.ok(!closed) - ended = true - }) - ts.on('close', function () { - assert.ok(ended) - closed = true - }) - - ts.write(1) - ts.write(2) - ts.write(3) - ts.end() - assert.ok(ended) - assert.notOk(closed) - ts.destroy() - assert.ok(closed) - assert.end() -}) - diff --git a/reverse_engineering/node_modules/through/test/buffering.js b/reverse_engineering/node_modules/through/test/buffering.js deleted file mode 100644 index b0084bf..0000000 --- a/reverse_engineering/node_modules/through/test/buffering.js +++ /dev/null @@ -1,71 +0,0 @@ -var test = require('tape') -var through = require('../') - -// must emit end before close. - -test('buffering', function(assert) { - var ts = through(function (data) { - this.queue(data) - }, function () { - this.queue(null) - }) - - var ended = false, actual = [] - - ts.on('data', actual.push.bind(actual)) - ts.on('end', function () { - ended = true - }) - - ts.write(1) - ts.write(2) - ts.write(3) - assert.deepEqual(actual, [1, 2, 3]) - ts.pause() - ts.write(4) - ts.write(5) - ts.write(6) - assert.deepEqual(actual, [1, 2, 3]) - ts.resume() - assert.deepEqual(actual, [1, 2, 3, 4, 5, 6]) - ts.pause() - ts.end() - assert.ok(!ended) - ts.resume() - assert.ok(ended) - assert.end() -}) - -test('buffering has data in queue, when ends', function (assert) { - - /* - * If stream ends while paused with data in the queue, - * stream should still emit end after all data is written - * on resume. - */ - - var ts = through(function (data) { - this.queue(data) - }, function () { - this.queue(null) - }) - - var ended = false, actual = [] - - ts.on('data', actual.push.bind(actual)) - ts.on('end', function () { - ended = true - }) - - ts.pause() - ts.write(1) - ts.write(2) - ts.write(3) - ts.end() - assert.deepEqual(actual, [], 'no data written yet, still paused') - assert.ok(!ended, 'end not emitted yet, still paused') - ts.resume() - assert.deepEqual(actual, [1, 2, 3], 'resumed, all data should be delivered') - assert.ok(ended, 'end should be emitted once all data was delivered') - assert.end(); -}) diff --git a/reverse_engineering/node_modules/through/test/end.js b/reverse_engineering/node_modules/through/test/end.js deleted file mode 100644 index fa113f5..0000000 --- a/reverse_engineering/node_modules/through/test/end.js +++ /dev/null @@ -1,45 +0,0 @@ -var test = require('tape') -var through = require('../') - -// must emit end before close. - -test('end before close', function (assert) { - var ts = through() - var ended = false, closed = false - - ts.on('end', function () { - assert.ok(!closed) - ended = true - }) - ts.on('close', function () { - assert.ok(ended) - closed = true - }) - - ts.write(1) - ts.write(2) - ts.write(3) - ts.end() - assert.ok(ended) - assert.ok(closed) - assert.end() -}) - -test('end only once', function (t) { - - var ts = through() - var ended = false, closed = false - - ts.on('end', function () { - t.equal(ended, false) - ended = true - }) - - ts.queue(null) - ts.queue(null) - ts.queue(null) - - ts.resume() - - t.end() -}) diff --git a/reverse_engineering/node_modules/through/test/index.js b/reverse_engineering/node_modules/through/test/index.js deleted file mode 100644 index 96da82f..0000000 --- a/reverse_engineering/node_modules/through/test/index.js +++ /dev/null @@ -1,133 +0,0 @@ - -var test = require('tape') -var spec = require('stream-spec') -var through = require('../') - -/* - I'm using these two functions, and not streams and pipe - so there is less to break. if this test fails it must be - the implementation of _through_ -*/ - -function write(array, stream) { - array = array.slice() - function next() { - while(array.length) - if(stream.write(array.shift()) === false) - return stream.once('drain', next) - - stream.end() - } - - next() -} - -function read(stream, callback) { - var actual = [] - stream.on('data', function (data) { - actual.push(data) - }) - stream.once('end', function () { - callback(null, actual) - }) - stream.once('error', function (err) { - callback(err) - }) -} - -test('simple defaults', function(assert) { - - var l = 1000 - , expected = [] - - while(l--) expected.push(l * Math.random()) - - var t = through() - var s = spec(t).through().pausable() - - read(t, function (err, actual) { - assert.ifError(err) - assert.deepEqual(actual, expected) - assert.end() - }) - - t.on('close', s.validate) - - write(expected, t) -}); - -test('simple functions', function(assert) { - - var l = 1000 - , expected = [] - - while(l--) expected.push(l * Math.random()) - - var t = through(function (data) { - this.emit('data', data*2) - }) - var s = spec(t).through().pausable() - - - read(t, function (err, actual) { - assert.ifError(err) - assert.deepEqual(actual, expected.map(function (data) { - return data*2 - })) - assert.end() - }) - - t.on('close', s.validate) - - write(expected, t) -}) - -test('pauses', function(assert) { - - var l = 1000 - , expected = [] - - while(l--) expected.push(l) //Math.random()) - - var t = through() - - var s = spec(t) - .through() - .pausable() - - t.on('data', function () { - if(Math.random() > 0.1) return - t.pause() - process.nextTick(function () { - t.resume() - }) - }) - - read(t, function (err, actual) { - assert.ifError(err) - assert.deepEqual(actual, expected) - }) - - t.on('close', function () { - s.validate() - assert.end() - }) - - write(expected, t) -}) - -test('does not soft-end on `undefined`', function(assert) { - var stream = through() - , count = 0 - - stream.on('data', function (data) { - count++ - }) - - stream.write(undefined) - stream.write(undefined) - - assert.equal(count, 2) - - assert.end() -}) diff --git a/reverse_engineering/node_modules/tunnel-ssh/.eslintignore b/reverse_engineering/node_modules/tunnel-ssh/.eslintignore deleted file mode 100644 index 91064a5..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/.eslintignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules/** -.idea/** -build/** -examples diff --git a/reverse_engineering/node_modules/tunnel-ssh/.travis.yml b/reverse_engineering/node_modules/tunnel-ssh/.travis.yml deleted file mode 100644 index c086098..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js - -node_js: - - node diff --git a/reverse_engineering/node_modules/tunnel-ssh/LICENSE b/reverse_engineering/node_modules/tunnel-ssh/LICENSE deleted file mode 100644 index 6bd4c38..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Christoph Hagenbrock (agebrock.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/tunnel-ssh/README.md b/reverse_engineering/node_modules/tunnel-ssh/README.md deleted file mode 100644 index 60f4548..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/README.md +++ /dev/null @@ -1,139 +0,0 @@ -Tunnel-SSH -========== - -One to connect them all ! - -![Tunnel-SSH Logo](http://i.imgur.com/I5PRnDD.jpg) - -Tunnel-ssh is based on the fantastic [ssh2](https://github.com/mscdex/ssh2) library by Brian White. -Trouble ? Please study the ssh2 configuration. - -### Latest Relese 4.1.3 - -## Release notes -* Closing sshconnections correctly thx @actionshrimp -* Improved readme -* Updated modules - -Special thanks to -@vweevers and @dickeyxxx - - -### Related projects -* [If you don't want to wrap a tunnel around your code: inject-tunnel-ssh](https://github.com/agebrock/inject-tunnel-ssh) -* [If you need it the other way around: reverse-tunnel-ssh](https://github.com/agebrock/reverse-tunnel-ssh) - -### Integration -By default tunnel-ssh will close the tunnel after a client disconnects, so your cli tools should work in the same way, they do if you connect directly. -If you need the tunnel to stay open, use the "keepAlive:true" option within -the configuration. - - -```js - - var config = { - ... - keepAlive:true - }; - - var tnl = tunnel(config, function(error, tnl){ - yourClient.connect(); - yourClient.disconnect(); - setTimeout(function(){ - // you only need to close the tunnel by yourself if you set the - // keepAlive:true option in the configuration ! - tnl.close(); - },2000); - }); - - // you can also close the tunnel from here... - setTimeout(function(){ - tnl.close(); - },2000); - -``` - - -## Understanding the configuration - -1. A local server listening for connections to forward via ssh -Description: This is where you bind your interface. -Properties: -** localHost (default is '127.0.0.1') -** localPort (default is dstPort) - - -2. The ssh configuration -Description: The host you want to use as ssh-tunnel server. -Properties: -** host -** port (22) -** username -** ... - - -3. The destination host configuration (based on the ssh host) -Imagine you just connected to The host you want to connect to. (via host:port) -now that server connects requires a target to tunnel to. -Properties: -** dstHost (localhost) -** dstPort - - -### Config example - -```js - - var config = { - username:'root', - password:'secret', - host:sshServer, - port:22, - dstHost:destinationServer, - dstPort:27017, - localHost:'127.0.0.1', - localPort: 27000 - }; - - var tunnel = require('tunnel-ssh'); - tunnel(config, function (error, server) { - //.... - }); -``` -#### Sugar configuration - -tunnel-ssh assumes that you want to map the same port on a remote machine to your localhost using the ssh-server on the remote machine. - - -```js - - var config = { - username:'root', - dstHost:'remotehost.with.sshserver.com', - dstPort:27017, - privateKey:require(fs).readFileSync('/path/to/key'), - passphrase:'secret' - }; - -``` - -#### More configuration options -tunnel-ssh pipes the configuration direct into the ssh2 library so every config option provided by ssh2 still works. -[ssh2 configuration](https://github.com/mscdex/ssh2#client-methods) - - -#### catching errors: -```js - var tunnel = require('tunnel-ssh'); - //map port from remote 3306 to localhost 3306 - var server = tunnel({host: '172.16.0.8', dstPort: 3306}, function (error, server) { - if(error){ - //catch configuration and startup errors here. - } - }); - - // Use a listener to handle errors outside the callback - server.on('error', function(err){ - console.error('Something bad happened:', err); - }); -``` diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/default.js b/reverse_engineering/node_modules/tunnel-ssh/examples/default.js deleted file mode 100644 index d050211..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/default.js +++ /dev/null @@ -1,26 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); - - -/** -make sure you can connect to your own machine with the current user without password. -Example: ssh $USER@127.0.0.1 - -Remember to add your privateKey to your ssh-agent (ssh-add) -**/ - -var config = { - host: '127.0.0.1', username: process.env.USER, dstPort: 8000, localPort: 7000 -}; - -var fakeServer = helper.createServer(config.dstPort, '127.0.0.1', function () { - tunnel(config, function () { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log); - }).on('error', function (e) { - console.log('error', e); - }); -}); - -fakeServer.unref(); diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive.js b/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive.js deleted file mode 100644 index 33af4b9..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive.js +++ /dev/null @@ -1,35 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); - -// Keep alive example -// this example demonstrates the keepAlive option. -// keepAlive will reuse the connections -// note the "tunnelKeepAlive.close();" at the end. -// this step is required to finish execution nicely - -var configA = { - host: '127.0.0.1', username: process.env.USER, dstPort: 8000, localPort: 7000, // Use keepAlive:true to keep the tunnel open. - keepAlive: true -}; - -var fakeServer = helper.createServer(configA.dstPort, '127.0.0.1', function () { - var tunnelKeepAlive = tunnel(configA, function () { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - setTimeout(function () { - // Call tunnel.close() to shutdown the server. - console.log('TRYING TO CLOSE'); - tunnelKeepAlive.close(); - }, 2000); - }); - }); - }); - }).on('error', function (e) { - console.log('error', e); - }); -}); -fakeServer.unref(); diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive_error.js b/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive_error.js deleted file mode 100644 index 97998c1..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive_error.js +++ /dev/null @@ -1,35 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); - -// Keep alive example -// this example demonstrates the keepAlive option. -// keepAlive will reuse the connections -// note the "tunnelKeepAlive.close();" at the end. -// this step is required to finish execution nicely - -var configA = { - host: '127.0.0.1', - username: process.env.USER, - dstPort: 8000, - localPort: 7000, // Use keepAlive:true to keep the tunnel open. - keepAlive: true -}; -var tunnelKeepAlive = tunnel(configA, function () { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - setTimeout(function () { - // Call tunnel.close() to shutdown the server. - console.log('TRYING TO CLOSE'); - tunnelKeepAlive.close(); - }, 2000); - }); - }); - }); -}).on('error', function (e) { - console.log('error', e); -}); - diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/server/index.js b/reverse_engineering/node_modules/tunnel-ssh/examples/server/index.js deleted file mode 100644 index c3132bd..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/server/index.js +++ /dev/null @@ -1,36 +0,0 @@ -var net = require('net'); -var debug = require('debug')('tunnel-ssh:test-server-client'); - -function createServer(port, addr, callback) { - var handleConnection = function (socket) { - socket.on('data', function (data) { - debug('server::data', data); - }); - debug('server::write'); - socket.write('Echo server\r\n'); - }; - - return net.createServer(handleConnection).listen(port, addr, callback); -} - -function createClient(port, addr, callback) { - var client = new net.Socket(); - - client.on('error', function (e) { - console.log('errortest', e); - }); - - client.connect(port, addr, function () { - debug('client::write'); - client.write('alive !'); - setTimeout(function () { - client.end(); - debug('client::end'); - callback(null, true); - }, 300); - }); - return client; -} - -exports.createServer = createServer; -exports.createClient = createClient; diff --git a/reverse_engineering/node_modules/tunnel-ssh/index.js b/reverse_engineering/node_modules/tunnel-ssh/index.js deleted file mode 100644 index 68f3401..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/index.js +++ /dev/null @@ -1,112 +0,0 @@ -var net = require('net'); -var debug = require('debug')('tunnel-ssh'); -var Connection = require('ssh2').Client; -var createConfig = require('./lib/config'); -var events = require('events'); -var noop = function () { -}; - -function bindSSHConnection(config, netConnection) { - var sshConnection = new Connection(); - netConnection.on('close', sshConnection.end.bind(sshConnection)); - - sshConnection.on('ready', function () { - debug('sshConnection:ready'); - netConnection.emit('sshConnection', sshConnection, netConnection); - sshConnection.forwardOut(config.srcHost, config.srcPort, config.dstHost, config.dstPort, function (err, sshStream) { - if (err) { - // Bubble up the error => netConnection => server - netConnection.emit('error', err); - debug('Destination port:', err); - return; - } - - debug('sshStream:create'); - netConnection.emit('sshStream', sshStream); - netConnection.pipe(sshStream).pipe(netConnection); - }); - }); - return sshConnection; -} - -function omit(obj, keys) { - return keys.reduce(function (copyObj, key) { - delete copyObj[key]; - return copyObj; - }, Object.assign({}, obj)); -} - -function createServer(config) { - var server; - var connections = []; - var connectionCount = 0; - - server = net.createServer(function (netConnection) { - var sshConnection; - connectionCount++; - netConnection.on('error', server.emit.bind(server, 'error')); - netConnection.on('close', function () { - connectionCount--; - if (connectionCount === 0) { - if (!config.keepAlive) { - setTimeout(function () { - if (connectionCount === 0) { - server.close(); - } - }, 2); - } - } - }); - - server.emit('netConnection', netConnection, server); - sshConnection = bindSSHConnection(config, netConnection); - sshConnection.on('error', server.emit.bind(server, 'error')); - - netConnection.on('sshStream', function (sshStream) { - sshStream.on('error', function () { - server.close(); - }); - }); - - connections.push(sshConnection, netConnection); - try { - sshConnection.connect(omit(config, ['localPort', 'localHost'])); - } catch (error) { - server.emit('error', error); - } - }); - - server.on('close', function () { - connections.forEach(function (connection) { - connection.end(); - }); - }); - - return server; -} - -function tunnel(configArgs, callback) { - var server; - var config; - - if (!callback) { - callback = noop; - } - try { - config = createConfig(configArgs); - server = createServer(config); - - server.listen(config.localPort, config.localHost, function (error) { - callback(error, server); - }); - } catch (e) { - server = new events.EventEmitter(); - setImmediate(function () { - callback(e); - server.emit('error', e); - }); - } - return server; -} - -module.exports = tunnel; diff --git a/reverse_engineering/node_modules/tunnel-ssh/lib/config.js b/reverse_engineering/node_modules/tunnel-ssh/lib/config.js deleted file mode 100644 index 49f7327..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/lib/config.js +++ /dev/null @@ -1,53 +0,0 @@ -var util = require('util'); -var defaults = require('lodash.defaults'); -var debug = require('debug')('tunnel-ssh-config'); - -var ConfigError = function (message, extra) { - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.message = message; - this.extra = extra; -}; - -util.inherits(ConfigError, Error); - -function createConfig(config) { - var env = process.env; - - defaults(config || {}, { - username: env.TUNNELSSH_USER || env.USER || env.USERNAME || 'root', - port: 22, - host: null, - srcPort: 0, - srcHost: '127.0.0.1', - dstPort: null, - dstHost: '127.0.0.1', - localHost: '127.0.0.1', - localPort: config.dstPort, - agent: process.env.SSH_AUTH_SOCK - }); - - if (!config.host) { - throw new ConfigError('host not set'); - } - - if (!config.dstPort) { - throw new ConfigError('dstPort not set'); - } - debug('ssh-config', (function () { - var hiddenValues = ['password', 'privateKey']; - - return Object.keys(config).reduce(function (obj, key) { - if (hiddenValues.indexOf(key) === -1) { - obj[key] = config[key]; - } else { - obj[key] = '***HIDDEN***'; - } - return obj; - }, {}); - })()); - - return config; -} - -module.exports = createConfig; diff --git a/reverse_engineering/node_modules/tunnel-ssh/package.json b/reverse_engineering/node_modules/tunnel-ssh/package.json deleted file mode 100644 index d9ca69a..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "tunnel-ssh", - "version": "4.1.6", - "description": "Easy extendable SSH tunnel", - "main": "index.js", - "scripts": { - "test": "mocha && eslint ." - }, - "repository": { - "type": "git", - "url": "https://github.com/agebrock/tunnel-ssh" - }, - "keywords": [ - "tunnel", - "ssh", - "mysql", - "develop", - "net" - ], - "author": { - "name": "Christoph Hagenbrock", - "email": "christoph.hagenbrock@googlemail.com" - }, - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "lodash.defaults": "^4.1.0", - "ssh2": "1.4.0" - }, - "devDependencies": { - "chai": "3.5.0", - "eslint": "^3.2.2", - "eslint-config-xo": "^0.17.0", - "mocha": "^3.5.3" - }, - "eslintConfig": { - "extends": "xo", - "env": { - "mocha": true - }, - "rules": { - "indent": [ - "error", - 4 - ] - } - } -} diff --git a/reverse_engineering/node_modules/tunnel-ssh/test/config-spec.js b/reverse_engineering/node_modules/tunnel-ssh/test/config-spec.js deleted file mode 100644 index 7ad297b..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/test/config-spec.js +++ /dev/null @@ -1,56 +0,0 @@ -var chai = require('chai'); -var expect = chai.expect; -var createConfig = require('../lib/config'); - -describe('config', function () { - it('use dstPort as localPort', function () { - var config = { - host: 'test.host', dstPort: 8000 - }; - expect(createConfig(config).localPort).to.be.equal(8000); - }); - - it('should emit an error', function () { - var config = { - host: 'remoteHost' - }; - expect(createConfig.bind(null, config)).to.throw('dstPort not set'); - }); - - it('throws an error if host is missing', function () { - var config = { - dstPort: 8000 - }; - expect(createConfig.bind(null, config)).to.throw('host not set'); - }); -}); - -/* - // Keep alive - var configA = { - host: '127.0.0.1', - username: process.env.USER, - dstPort: 8000, - localPort: 7000, - // Use keepAlive:true to keep the tunnel open. - keepAlive: true - }; - var tunnelKeepAlive = tunnel(configA, function() { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log).on('close', function() { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function() { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function() { - setTimeout(function() { - // Call tunnel.close() to shutdown the server. - console.log('TRYING TO CLOSE'); - tunnelKeepAlive.close(); - }, 2000); - }); - }); - }); - }).on('error', function(e) { - console.log('error', e); - }); - }); - - */ diff --git a/reverse_engineering/node_modules/tunnel-ssh/test/main-spec.js b/reverse_engineering/node_modules/tunnel-ssh/test/main-spec.js deleted file mode 100644 index 4849387..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/test/main-spec.js +++ /dev/null @@ -1,37 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); -var chai = require('chai'); -var expect = chai.expect; - -describe('tunnel-ssh', function () { - it('should emit an error', function (done) { - var config = { - host: '127.0.0.1', username: process.env.USER, dstPort: 8000, localPort: 7000 - }; - - tunnel(config, function () { - helper.createClient(7000, '127.0.0.1', done); - }).on('error', function (e) { - expect(e).to.be.instanceOf(Error); - done(null); - }); - }); - - it('brokenConfig, should callback an error', function (done) { - var brokenConfig = {}; - - tunnel(brokenConfig, function (e) { - expect(e).to.be.instanceOf(Error); - done(); - }); - }); - - it('brokenConfig, should emit an error', function (done) { - var brokenConfig = {}; - - tunnel(brokenConfig).on('error', function (e) { - expect(e).to.be.instanceOf(Error); - done(null); - }); - }); -}); diff --git a/reverse_engineering/node_modules/tunnel-ssh/test/server/index.js b/reverse_engineering/node_modules/tunnel-ssh/test/server/index.js deleted file mode 100644 index 5a7e232..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/test/server/index.js +++ /dev/null @@ -1,36 +0,0 @@ -var net = require('net'); -var debug = require('debug')('tunnel-ssh:test-server-client'); - -function createServer(port, addr, callback) { - var handleConnection = function (socket) { - socket.on('data', function (data) { - debug('server::data', data); - }); - debug('server::write'); - socket.write('Echo server\r\n'); - }; - - return net.createServer(handleConnection).listen(port, addr, callback); -} - -function createClient(port, addr, callback) { - var client = new net.Socket(); - - client.on('error', function (e) { - debug('clientError', e); - }); - - client.connect(port, addr, function () { - debug('client::write'); - client.write('alive !'); - setTimeout(function () { - client.end(); - debug('client::end'); - callback(null, true); - }, 300); - }); - return client; -} - -exports.createServer = createServer; -exports.createClient = createClient; diff --git a/reverse_engineering/node_modules/tweetnacl/.npmignore b/reverse_engineering/node_modules/tweetnacl/.npmignore deleted file mode 100644 index 7d98dcb..0000000 --- a/reverse_engineering/node_modules/tweetnacl/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -.eslintrc -.travis.yml -bower.json -test diff --git a/reverse_engineering/node_modules/tweetnacl/AUTHORS.md b/reverse_engineering/node_modules/tweetnacl/AUTHORS.md deleted file mode 100644 index 6d74d40..0000000 --- a/reverse_engineering/node_modules/tweetnacl/AUTHORS.md +++ /dev/null @@ -1,28 +0,0 @@ -List of TweetNaCl.js authors -============================ - - Alphabetical order by first name. - Format: Name (GitHub username or URL) - -* AndSDev (@AndSDev) -* Devi Mandiri (@devi) -* Dmitry Chestnykh (@dchest) - -List of authors of third-party public domain code from which TweetNaCl.js code was derived -========================================================================================== - -[TweetNaCl](http://tweetnacl.cr.yp.to/) --------------------------------------- - -* Bernard van Gastel -* Daniel J. Bernstein -* Peter Schwabe -* Sjaak Smetsers -* Tanja Lange -* Wesley Janssen - - -[Poly1305-donna](https://github.com/floodyberry/poly1305-donna) --------------------------------------------------------------- - -* Andrew Moon (@floodyberry) diff --git a/reverse_engineering/node_modules/tweetnacl/CHANGELOG.md b/reverse_engineering/node_modules/tweetnacl/CHANGELOG.md deleted file mode 100644 index 92a4fdc..0000000 --- a/reverse_engineering/node_modules/tweetnacl/CHANGELOG.md +++ /dev/null @@ -1,221 +0,0 @@ -TweetNaCl.js Changelog -====================== - - -v0.14.5 -------- - -* Fixed incomplete return types in TypeScript typings. -* Replaced COPYING.txt with LICENSE file, which now has public domain dedication - text from The Unlicense. License fields in package.json and bower.json have - been set to "Unlicense". The project was and will be in the public domain -- - this change just makes it easier for automated tools to know about this fact by - using the widely recognized and SPDX-compatible template for public domain - dedication. - - -v0.14.4 -------- - -* Added TypeScript type definitions (contributed by @AndSDev). -* Improved benchmarking code. - - -v0.14.3 -------- - -Fixed a bug in the fast version of Poly1305 and brought it back. - -Thanks to @floodyberry for promptly responding and fixing the original C code: - -> "The issue was not properly detecting if st->h was >= 2^130 - 5, coupled with -> [testing mistake] not catching the failure. The chance of the bug affecting -> anything in the real world is essentially zero luckily, but it's good to have -> it fixed." - -https://github.com/floodyberry/poly1305-donna/issues/2#issuecomment-202698577 - - -v0.14.2 -------- - -Switched Poly1305 fast version back to original (slow) version due to a bug. - - -v0.14.1 -------- - -No code changes, just tweaked packaging and added COPYING.txt. - - -v0.14.0 -------- - -* **Breaking change!** All functions from `nacl.util` have been removed. These - functions are no longer available: - - nacl.util.decodeUTF8 - nacl.util.encodeUTF8 - nacl.util.decodeBase64 - nacl.util.encodeBase64 - - If want to continue using them, you can include - package: - - - - - or - - var nacl = require('tweetnacl'); - nacl.util = require('tweetnacl-util'); - - However it is recommended to use better packages that have wider - compatibility and better performance. Functions from `nacl.util` were never - intended to be robust solution for string conversion and were included for - convenience: cryptography library is not the right place for them. - - Currently calling these functions will throw error pointing to - `tweetnacl-util-js` (in the next version this error message will be removed). - -* Improved detection of available random number generators, making it possible - to use `nacl.randomBytes` and related functions in Web Workers without - changes. - -* Changes to testing (see README). - - -v0.13.3 -------- - -No code changes. - -* Reverted license field in package.json to "Public domain". - -* Fixed typo in README. - - -v0.13.2 -------- - -* Fixed undefined variable bug in fast version of Poly1305. No worries, this - bug was *never* triggered. - -* Specified CC0 public domain dedication. - -* Updated development dependencies. - - -v0.13.1 -------- - -* Exclude `crypto` and `buffer` modules from browserify builds. - - -v0.13.0 -------- - -* Made `nacl-fast` the default version in NPM package. Now - `require("tweetnacl")` will use fast version; to get the original version, - use `require("tweetnacl/nacl.js")`. - -* Cleanup temporary array after generating random bytes. - - -v0.12.2 -------- - -* Improved performance of curve operations, making `nacl.scalarMult`, `nacl.box`, - `nacl.sign` and related functions up to 3x faster in `nacl-fast` version. - - -v0.12.1 -------- - -* Significantly improved performance of Salsa20 (~1.5x faster) and - Poly1305 (~3.5x faster) in `nacl-fast` version. - - -v0.12.0 -------- - -* Instead of using the given secret key directly, TweetNaCl.js now copies it to - a new array in `nacl.box.keyPair.fromSecretKey` and - `nacl.sign.keyPair.fromSecretKey`. - - -v0.11.2 -------- - -* Added new constant: `nacl.sign.seedLength`. - - -v0.11.1 -------- - -* Even faster hash for both short and long inputs (in `nacl-fast`). - - -v0.11.0 -------- - -* Implement `nacl.sign.keyPair.fromSeed` to enable creation of sign key pairs - deterministically from a 32-byte seed. (It behaves like - [libsodium's](http://doc.libsodium.org/public-key_cryptography/public-key_signatures.html) - `crypto_sign_seed_keypair`: the seed becomes a secret part of the secret key.) - -* Fast version now has an improved hash implementation that is 2x-5x faster. - -* Fixed benchmarks, which may have produced incorrect measurements. - - -v0.10.1 -------- - -* Exported undocumented `nacl.lowlevel.crypto_core_hsalsa20`. - - -v0.10.0 -------- - -* **Signature API breaking change!** `nacl.sign` and `nacl.sign.open` now deal - with signed messages, and new `nacl.sign.detached` and - `nacl.sign.detached.verify` are available. - - Previously, `nacl.sign` returned a signature, and `nacl.sign.open` accepted a - message and "detached" signature. This was unlike NaCl's API, which dealt with - signed messages (concatenation of signature and message). - - The new API is: - - nacl.sign(message, secretKey) -> signedMessage - nacl.sign.open(signedMessage, publicKey) -> message | null - - Since detached signatures are common, two new API functions were introduced: - - nacl.sign.detached(message, secretKey) -> signature - nacl.sign.detached.verify(message, signature, publicKey) -> true | false - - (Note that it's `verify`, not `open`, and it returns a boolean value, unlike - `open`, which returns an "unsigned" message.) - -* NPM package now comes without `test` directory to keep it small. - - -v0.9.2 ------- - -* Improved documentation. -* Fast version: increased theoretical message size limit from 2^32-1 to 2^52 - bytes in Poly1305 (and thus, secretbox and box). However this has no impact - in practice since JavaScript arrays or ArrayBuffers are limited to 32-bit - indexes, and most implementations won't allocate more than a gigabyte or so. - (Obviously, there are no tests for the correctness of implementation.) Also, - it's not recommended to use messages that large without splitting them into - smaller packets anyway. - - -v0.9.1 ------- - -* Initial release diff --git a/reverse_engineering/node_modules/tweetnacl/LICENSE b/reverse_engineering/node_modules/tweetnacl/LICENSE deleted file mode 100644 index cf1ab25..0000000 --- a/reverse_engineering/node_modules/tweetnacl/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to diff --git a/reverse_engineering/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md b/reverse_engineering/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index a8eb4a9..0000000 --- a/reverse_engineering/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,20 +0,0 @@ -# Important! - -If your contribution is not trivial (not a typo fix, etc.), we can only accept -it if you dedicate your copyright for the contribution to the public domain. -Make sure you understand what it means (see http://unlicense.org/)! If you -agree, please add yourself to AUTHORS.md file, and include the following text -to your pull request description or a comment in it: - ------------------------------------------------------------------------------- - - I dedicate any and all copyright interest in this software to the - public domain. I make this dedication for the benefit of the public at - large and to the detriment of my heirs and successors. I intend this - dedication to be an overt act of relinquishment in perpetuity of all - present and future rights to this software under copyright law. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. diff --git a/reverse_engineering/node_modules/tweetnacl/README.md b/reverse_engineering/node_modules/tweetnacl/README.md deleted file mode 100644 index ffb6871..0000000 --- a/reverse_engineering/node_modules/tweetnacl/README.md +++ /dev/null @@ -1,459 +0,0 @@ -TweetNaCl.js -============ - -Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) -to JavaScript for modern browsers and Node.js. Public domain. - -[![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) -](https://travis-ci.org/dchest/tweetnacl-js) - -Demo: - -**:warning: The library is stable and API is frozen, however it has not been -independently reviewed. If you can help reviewing it, please [contact -me](mailto:dmitry@codingrobots.com).** - -Documentation -============= - -* [Overview](#overview) -* [Installation](#installation) -* [Usage](#usage) - * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) - * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) - * [Scalar multiplication](#scalar-multiplication) - * [Signatures](#signatures) - * [Hashing](#hashing) - * [Random bytes generation](#random-bytes-generation) - * [Constant-time comparison](#constant-time-comparison) -* [System requirements](#system-requirements) -* [Development and testing](#development-and-testing) -* [Benchmarks](#benchmarks) -* [Contributors](#contributors) -* [Who uses it](#who-uses-it) - - -Overview --------- - -The primary goal of this project is to produce a translation of TweetNaCl to -JavaScript which is as close as possible to the original C implementation, plus -a thin layer of idiomatic high-level API on top of it. - -There are two versions, you can use either of them: - -* `nacl.js` is the port of TweetNaCl with minimum differences from the - original + high-level API. - -* `nacl-fast.js` is like `nacl.js`, but with some functions replaced with - faster versions. - - -Installation ------------- - -You can install TweetNaCl.js via a package manager: - -[Bower](http://bower.io): - - $ bower install tweetnacl - -[NPM](https://www.npmjs.org/): - - $ npm install tweetnacl - -or [download source code](https://github.com/dchest/tweetnacl-js/releases). - - -Usage ------ - -All API functions accept and return bytes as `Uint8Array`s. If you need to -encode or decode strings, use functions from - or one of the more robust codec -packages. - -In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you -can freely pass them to TweetNaCl.js functions as arguments. The returned -objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to -convert them manually; make sure to convert using copying: `new Buffer(array)`, -instead of sharing: `new Buffer(array.buffer)`, because some functions return -subarrays of their buffers. - - -### Public-key authenticated encryption (box) - -Implements *curve25519-xsalsa20-poly1305*. - -#### nacl.box.keyPair() - -Generates a new random key pair for box and returns it as an object with -`publicKey` and `secretKey` members: - - { - publicKey: ..., // Uint8Array with 32-byte public key - secretKey: ... // Uint8Array with 32-byte secret key - } - - -#### nacl.box.keyPair.fromSecretKey(secretKey) - -Returns a key pair for box with public key corresponding to the given secret -key. - -#### nacl.box(message, nonce, theirPublicKey, mySecretKey) - -Encrypt and authenticates message using peer's public key, our secret key, and -the given nonce, which must be unique for each distinct message for a key pair. - -Returns an encrypted and authenticated message, which is -`nacl.box.overheadLength` longer than the original message. - -#### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) - -Authenticates and decrypts the given box with peer's public key, our secret -key, and the given nonce. - -Returns the original message, or `false` if authentication fails. - -#### nacl.box.before(theirPublicKey, mySecretKey) - -Returns a precomputed shared key which can be used in `nacl.box.after` and -`nacl.box.open.after`. - -#### nacl.box.after(message, nonce, sharedKey) - -Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. - -#### nacl.box.open.after(box, nonce, sharedKey) - -Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. - -#### nacl.box.publicKeyLength = 32 - -Length of public key in bytes. - -#### nacl.box.secretKeyLength = 32 - -Length of secret key in bytes. - -#### nacl.box.sharedKeyLength = 32 - -Length of precomputed shared key in bytes. - -#### nacl.box.nonceLength = 24 - -Length of nonce in bytes. - -#### nacl.box.overheadLength = 16 - -Length of overhead added to box compared to original message. - - -### Secret-key authenticated encryption (secretbox) - -Implements *xsalsa20-poly1305*. - -#### nacl.secretbox(message, nonce, key) - -Encrypt and authenticates message using the key and the nonce. The nonce must -be unique for each distinct message for this key. - -Returns an encrypted and authenticated message, which is -`nacl.secretbox.overheadLength` longer than the original message. - -#### nacl.secretbox.open(box, nonce, key) - -Authenticates and decrypts the given secret box using the key and the nonce. - -Returns the original message, or `false` if authentication fails. - -#### nacl.secretbox.keyLength = 32 - -Length of key in bytes. - -#### nacl.secretbox.nonceLength = 24 - -Length of nonce in bytes. - -#### nacl.secretbox.overheadLength = 16 - -Length of overhead added to secret box compared to original message. - - -### Scalar multiplication - -Implements *curve25519*. - -#### nacl.scalarMult(n, p) - -Multiplies an integer `n` by a group element `p` and returns the resulting -group element. - -#### nacl.scalarMult.base(n) - -Multiplies an integer `n` by a standard group element and returns the resulting -group element. - -#### nacl.scalarMult.scalarLength = 32 - -Length of scalar in bytes. - -#### nacl.scalarMult.groupElementLength = 32 - -Length of group element in bytes. - - -### Signatures - -Implements [ed25519](http://ed25519.cr.yp.to). - -#### nacl.sign.keyPair() - -Generates new random key pair for signing and returns it as an object with -`publicKey` and `secretKey` members: - - { - publicKey: ..., // Uint8Array with 32-byte public key - secretKey: ... // Uint8Array with 64-byte secret key - } - -#### nacl.sign.keyPair.fromSecretKey(secretKey) - -Returns a signing key pair with public key corresponding to the given -64-byte secret key. The secret key must have been generated by -`nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. - -#### nacl.sign.keyPair.fromSeed(seed) - -Returns a new signing key pair generated deterministically from a 32-byte seed. -The seed must contain enough entropy to be secure. This method is not -recommended for general use: instead, use `nacl.sign.keyPair` to generate a new -key pair from a random seed. - -#### nacl.sign(message, secretKey) - -Signs the message using the secret key and returns a signed message. - -#### nacl.sign.open(signedMessage, publicKey) - -Verifies the signed message and returns the message without signature. - -Returns `null` if verification failed. - -#### nacl.sign.detached(message, secretKey) - -Signs the message using the secret key and returns a signature. - -#### nacl.sign.detached.verify(message, signature, publicKey) - -Verifies the signature for the message and returns `true` if verification -succeeded or `false` if it failed. - -#### nacl.sign.publicKeyLength = 32 - -Length of signing public key in bytes. - -#### nacl.sign.secretKeyLength = 64 - -Length of signing secret key in bytes. - -#### nacl.sign.seedLength = 32 - -Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. - -#### nacl.sign.signatureLength = 64 - -Length of signature in bytes. - - -### Hashing - -Implements *SHA-512*. - -#### nacl.hash(message) - -Returns SHA-512 hash of the message. - -#### nacl.hash.hashLength = 64 - -Length of hash in bytes. - - -### Random bytes generation - -#### nacl.randomBytes(length) - -Returns a `Uint8Array` of the given length containing random bytes of -cryptographic quality. - -**Implementation note** - -TweetNaCl.js uses the following methods to generate random bytes, -depending on the platform it runs on: - -* `window.crypto.getRandomValues` (WebCrypto standard) -* `window.msCrypto.getRandomValues` (Internet Explorer 11) -* `crypto.randomBytes` (Node.js) - -If the platform doesn't provide a suitable PRNG, the following functions, -which require random numbers, will throw exception: - -* `nacl.randomBytes` -* `nacl.box.keyPair` -* `nacl.sign.keyPair` - -Other functions are deterministic and will continue working. - -If a platform you are targeting doesn't implement secure random number -generator, but you somehow have a cryptographically-strong source of entropy -(not `Math.random`!), and you know what you are doing, you can plug it into -TweetNaCl.js like this: - - nacl.setPRNG(function(x, n) { - // ... copy n random bytes into x ... - }); - -Note that `nacl.setPRNG` *completely replaces* internal random byte generator -with the one provided. - - -### Constant-time comparison - -#### nacl.verify(x, y) - -Compares `x` and `y` in constant time and returns `true` if their lengths are -non-zero and equal, and their contents are equal. - -Returns `false` if either of the arguments has zero length, or arguments have -different lengths, or their contents differ. - - -System requirements -------------------- - -TweetNaCl.js supports modern browsers that have a cryptographically secure -pseudorandom number generator and typed arrays, including the latest versions -of: - -* Chrome -* Firefox -* Safari (Mac, iOS) -* Internet Explorer 11 - -Other systems: - -* Node.js - - -Development and testing ------------------------- - -Install NPM modules needed for development: - - $ npm install - -To build minified versions: - - $ npm run build - -Tests use minified version, so make sure to rebuild it every time you change -`nacl.js` or `nacl-fast.js`. - -### Testing - -To run tests in Node.js: - - $ npm run test-node - -By default all tests described here work on `nacl.min.js`. To test other -versions, set environment variable `NACL_SRC` to the file name you want to test. -For example, the following command will test fast minified version: - - $ NACL_SRC=nacl-fast.min.js npm run test-node - -To run full suite of tests in Node.js, including comparing outputs of -JavaScript port to outputs of the original C version: - - $ npm run test-node-all - -To prepare tests for browsers: - - $ npm run build-test-browser - -and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to -run them. - -To run headless browser tests with `tape-run` (powered by Electron): - - $ npm run test-browser - -(If you get `Error: spawn ENOENT`, install *xvfb*: `sudo apt-get install xvfb`.) - -To run tests in both Node and Electron: - - $ npm test - -### Benchmarking - -To run benchmarks in Node.js: - - $ npm run bench - $ NACL_SRC=nacl-fast.min.js npm run bench - -To run benchmarks in a browser, open `test/benchmark/bench.html` (or -`test/benchmark/bench-fast.html`). - - -Benchmarks ----------- - -For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) -laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi -Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in -Chrome 52/Android: - -| | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | -| ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| -| salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | -| poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | -| hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | -| secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | -| box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | -| scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | -| sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | -| sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | - -(You can run benchmarks on your devices by clicking on the links at the bottom -of the [home page](https://tweetnacl.js.org)). - -In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and -authenticate more than 57000 messages per second on a typical laptop or more than -14000 messages per second on a $170 smartphone, sign about 200 and verify 100 -messages per second on a laptop or 60 and 30 messages per second on a smartphone, -per CPU core (with Web Workers you can do these operations in parallel), -which is good enough for most applications. - - -Contributors ------------- - -See AUTHORS.md file. - - -Third-party libraries based on TweetNaCl.js -------------------------------------------- - -* [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation -* [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption -* [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) -* [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules - - -Who uses it ------------ - -Some notable users of TweetNaCl.js: - -* [miniLock](http://minilock.io/) -* [Stellar](https://www.stellar.org/) diff --git a/reverse_engineering/node_modules/tweetnacl/nacl-fast.js b/reverse_engineering/node_modules/tweetnacl/nacl-fast.js deleted file mode 100644 index 5e4562f..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl-fast.js +++ /dev/null @@ -1,2388 +0,0 @@ -(function(nacl) { -'use strict'; - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _0 = new Uint8Array(16); -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function ts64(x, i, h, l) { - x[i] = (h >> 24) & 0xff; - x[i+1] = (h >> 16) & 0xff; - x[i+2] = (h >> 8) & 0xff; - x[i+3] = h & 0xff; - x[i+4] = (l >> 24) & 0xff; - x[i+5] = (l >> 16) & 0xff; - x[i+6] = (l >> 8) & 0xff; - x[i+7] = l & 0xff; -} - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function core_salsa20(o, p, k, c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; - - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; - - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); - - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; - - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; - - o[ 4] = x1 >>> 0 & 0xff; - o[ 5] = x1 >>> 8 & 0xff; - o[ 6] = x1 >>> 16 & 0xff; - o[ 7] = x1 >>> 24 & 0xff; - - o[ 8] = x2 >>> 0 & 0xff; - o[ 9] = x2 >>> 8 & 0xff; - o[10] = x2 >>> 16 & 0xff; - o[11] = x2 >>> 24 & 0xff; - - o[12] = x3 >>> 0 & 0xff; - o[13] = x3 >>> 8 & 0xff; - o[14] = x3 >>> 16 & 0xff; - o[15] = x3 >>> 24 & 0xff; - - o[16] = x4 >>> 0 & 0xff; - o[17] = x4 >>> 8 & 0xff; - o[18] = x4 >>> 16 & 0xff; - o[19] = x4 >>> 24 & 0xff; - - o[20] = x5 >>> 0 & 0xff; - o[21] = x5 >>> 8 & 0xff; - o[22] = x5 >>> 16 & 0xff; - o[23] = x5 >>> 24 & 0xff; - - o[24] = x6 >>> 0 & 0xff; - o[25] = x6 >>> 8 & 0xff; - o[26] = x6 >>> 16 & 0xff; - o[27] = x6 >>> 24 & 0xff; - - o[28] = x7 >>> 0 & 0xff; - o[29] = x7 >>> 8 & 0xff; - o[30] = x7 >>> 16 & 0xff; - o[31] = x7 >>> 24 & 0xff; - - o[32] = x8 >>> 0 & 0xff; - o[33] = x8 >>> 8 & 0xff; - o[34] = x8 >>> 16 & 0xff; - o[35] = x8 >>> 24 & 0xff; - - o[36] = x9 >>> 0 & 0xff; - o[37] = x9 >>> 8 & 0xff; - o[38] = x9 >>> 16 & 0xff; - o[39] = x9 >>> 24 & 0xff; - - o[40] = x10 >>> 0 & 0xff; - o[41] = x10 >>> 8 & 0xff; - o[42] = x10 >>> 16 & 0xff; - o[43] = x10 >>> 24 & 0xff; - - o[44] = x11 >>> 0 & 0xff; - o[45] = x11 >>> 8 & 0xff; - o[46] = x11 >>> 16 & 0xff; - o[47] = x11 >>> 24 & 0xff; - - o[48] = x12 >>> 0 & 0xff; - o[49] = x12 >>> 8 & 0xff; - o[50] = x12 >>> 16 & 0xff; - o[51] = x12 >>> 24 & 0xff; - - o[52] = x13 >>> 0 & 0xff; - o[53] = x13 >>> 8 & 0xff; - o[54] = x13 >>> 16 & 0xff; - o[55] = x13 >>> 24 & 0xff; - - o[56] = x14 >>> 0 & 0xff; - o[57] = x14 >>> 8 & 0xff; - o[58] = x14 >>> 16 & 0xff; - o[59] = x14 >>> 24 & 0xff; - - o[60] = x15 >>> 0 & 0xff; - o[61] = x15 >>> 8 & 0xff; - o[62] = x15 >>> 16 & 0xff; - o[63] = x15 >>> 24 & 0xff; -} - -function core_hsalsa20(o,p,k,c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; - - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; - - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); - - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } - - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; - - o[ 4] = x5 >>> 0 & 0xff; - o[ 5] = x5 >>> 8 & 0xff; - o[ 6] = x5 >>> 16 & 0xff; - o[ 7] = x5 >>> 24 & 0xff; - - o[ 8] = x10 >>> 0 & 0xff; - o[ 9] = x10 >>> 8 & 0xff; - o[10] = x10 >>> 16 & 0xff; - o[11] = x10 >>> 24 & 0xff; - - o[12] = x15 >>> 0 & 0xff; - o[13] = x15 >>> 8 & 0xff; - o[14] = x15 >>> 16 & 0xff; - o[15] = x15 >>> 24 & 0xff; - - o[16] = x6 >>> 0 & 0xff; - o[17] = x6 >>> 8 & 0xff; - o[18] = x6 >>> 16 & 0xff; - o[19] = x6 >>> 24 & 0xff; - - o[20] = x7 >>> 0 & 0xff; - o[21] = x7 >>> 8 & 0xff; - o[22] = x7 >>> 16 & 0xff; - o[23] = x7 >>> 24 & 0xff; - - o[24] = x8 >>> 0 & 0xff; - o[25] = x8 >>> 8 & 0xff; - o[26] = x8 >>> 16 & 0xff; - o[27] = x8 >>> 24 & 0xff; - - o[28] = x9 >>> 0 & 0xff; - o[29] = x9 >>> 8 & 0xff; - o[30] = x9 >>> 16 & 0xff; - o[31] = x9 >>> 24 & 0xff; -} - -function crypto_core_salsa20(out,inp,k,c) { - core_salsa20(out,inp,k,c); -} - -function crypto_core_hsalsa20(out,inp,k,c) { - core_hsalsa20(out,inp,k,c); -} - -var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" - -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - } - return 0; -} - -function crypto_stream_salsa20(c,cpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = x[i]; - } - return 0; -} - -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20(c,cpos,d,sn,s); -} - -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); -} - -/* -* Port of Andrew Moon's Poly1305-donna-16. Public domain. -* https://github.com/floodyberry/poly1305-donna -*/ - -var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; - - var t0, t1, t2, t3, t4, t5, t6, t7; - - t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; - t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; - t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; - this.r[5] = ((t4 >>> 1)) & 0x1ffe; - t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; - t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - this.r[9] = ((t7 >>> 5)) & 0x007f; - - this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; - this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; - this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; - this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; - this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; - this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; - this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; - this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; -}; - -poly1305.prototype.blocks = function(m, mpos, bytes) { - var hibit = this.fin ? 0 : (1 << 11); - var t0, t1, t2, t3, t4, t5, t6, t7, c; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - - var h0 = this.h[0], - h1 = this.h[1], - h2 = this.h[2], - h3 = this.h[3], - h4 = this.h[4], - h5 = this.h[5], - h6 = this.h[6], - h7 = this.h[7], - h8 = this.h[8], - h9 = this.h[9]; - - var r0 = this.r[0], - r1 = this.r[1], - r2 = this.r[2], - r3 = this.r[3], - r4 = this.r[4], - r5 = this.r[5], - r6 = this.r[6], - r7 = this.r[7], - r8 = this.r[8], - r9 = this.r[9]; - - while (bytes >= 16) { - t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; - t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; - t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; - h5 += ((t4 >>> 1)) & 0x1fff; - t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; - t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - h9 += ((t7 >>> 5)) | hibit; - - c = 0; - - d0 = c; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h2 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c = (d0 >>> 13); d0 &= 0x1fff; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c += (d0 >>> 13); d0 &= 0x1fff; - - d1 = c; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h2 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c = (d1 >>> 13); d1 &= 0x1fff; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c += (d1 >>> 13); d1 &= 0x1fff; - - d2 = c; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h2 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c = (d2 >>> 13); d2 &= 0x1fff; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c += (d2 >>> 13); d2 &= 0x1fff; - - d3 = c; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h2 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c = (d3 >>> 13); d3 &= 0x1fff; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c += (d3 >>> 13); d3 &= 0x1fff; - - d4 = c; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h2 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c = (d4 >>> 13); d4 &= 0x1fff; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c += (d4 >>> 13); d4 &= 0x1fff; - - d5 = c; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h2 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c = (d5 >>> 13); d5 &= 0x1fff; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c += (d5 >>> 13); d5 &= 0x1fff; - - d6 = c; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h2 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c = (d6 >>> 13); d6 &= 0x1fff; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c += (d6 >>> 13); d6 &= 0x1fff; - - d7 = c; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h2 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c = (d7 >>> 13); d7 &= 0x1fff; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c += (d7 >>> 13); d7 &= 0x1fff; - - d8 = c; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h2 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c = (d8 >>> 13); d8 &= 0x1fff; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c += (d8 >>> 13); d8 &= 0x1fff; - - d9 = c; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h2 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c = (d9 >>> 13); d9 &= 0x1fff; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c += (d9 >>> 13); d9 &= 0x1fff; - - c = (((c << 2) + c)) | 0; - c = (c + d0) | 0; - d0 = c & 0x1fff; - c = (c >>> 13); - d1 += c; - - h0 = d0; - h1 = d1; - h2 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; - - mpos += 16; - bytes -= 16; - } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h2; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; -}; - -poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; - - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); - } - - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 0x1fff; - } - this.h[0] += (c * 5); - c = this.h[0] >>> 13; - this.h[0] &= 0x1fff; - this.h[1] += c; - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - this.h[2] += c; - - g[0] = this.h[0] + 5; - c = g[0] >>> 13; - g[0] &= 0x1fff; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 0x1fff; - } - g[9] -= (1 << 13); - - mask = (c ^ 1) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; - - this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; - this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; - this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; - this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; - this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; - this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; - this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; - this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; - - f = this.h[0] + this.pad[0]; - this.h[0] = f & 0xffff; - for (i = 1; i < 8; i++) { - f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; - this.h[i] = f & 0xffff; - } - - mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; - mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; - mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; - mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; - mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; - mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; - mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; - mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; - mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; - mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; - mac[macpos+10] = (this.h[5] >>> 0) & 0xff; - mac[macpos+11] = (this.h[5] >>> 8) & 0xff; - mac[macpos+12] = (this.h[6] >>> 0) & 0xff; - mac[macpos+13] = (this.h[6] >>> 8) & 0xff; - mac[macpos+14] = (this.h[7] >>> 0) & 0xff; - mac[macpos+15] = (this.h[7] >>> 8) & 0xff; -}; - -poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; - - if (this.leftover) { - want = (16 - this.leftover); - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; - } - - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; - } - - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; - } -}; - -function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s = new poly1305(k); - s.update(m, mpos, n); - s.finish(out, outpos); - return 0; -} - -function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); -} - -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; -} - -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; -} - -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; -} - -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); -} - -var crypto_box_afternm = crypto_secretbox; -var crypto_box_open_afternm = crypto_secretbox_open; - -function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); -} - -function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); -} - -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function crypto_hashblocks_hl(hh, hl, m, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), - bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, - bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, - th, tl, i, j, h, l, a, b, c, d; - - var ah0 = hh[0], - ah1 = hh[1], - ah2 = hh[2], - ah3 = hh[3], - ah4 = hh[4], - ah5 = hh[5], - ah6 = hh[6], - ah7 = hh[7], - - al0 = hl[0], - al1 = hl[1], - al2 = hl[2], - al3 = hl[3], - al4 = hl[4], - al5 = hl[5], - al6 = hl[6], - al7 = hl[7]; - - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; - wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; - } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; - - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; - - // add - h = ah7; - l = al7; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - // Sigma1 - h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); - l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // Ch - h = (ah4 & ah5) ^ (~ah4 & ah6); - l = (al4 & al5) ^ (~al4 & al6); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // K - h = K[i*2]; - l = K[i*2+1]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // w - h = wh[i%16]; - l = wl[i%16]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - th = c & 0xffff | d << 16; - tl = a & 0xffff | b << 16; - - // add - h = th; - l = tl; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - // Sigma0 - h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); - l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // Maj - h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); - l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - bh7 = (c & 0xffff) | (d << 16); - bl7 = (a & 0xffff) | (b << 16); - - // add - h = bh3; - l = bl3; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = th; - l = tl; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - bh3 = (c & 0xffff) | (d << 16); - bl3 = (a & 0xffff) | (b << 16); - - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; - - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; - - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - // add - h = wh[j]; - l = wl[j]; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = wh[(j+9)%16]; - l = wl[(j+9)%16]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // sigma0 - th = wh[(j+1)%16]; - tl = wl[(j+1)%16]; - h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); - l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // sigma1 - th = wh[(j+14)%16]; - tl = wl[(j+14)%16]; - h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); - l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - wh[j] = (c & 0xffff) | (d << 16); - wl[j] = (a & 0xffff) | (b << 16); - } - } - } - - // add - h = ah0; - l = al0; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[0]; - l = hl[0]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[0] = ah0 = (c & 0xffff) | (d << 16); - hl[0] = al0 = (a & 0xffff) | (b << 16); - - h = ah1; - l = al1; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[1]; - l = hl[1]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[1] = ah1 = (c & 0xffff) | (d << 16); - hl[1] = al1 = (a & 0xffff) | (b << 16); - - h = ah2; - l = al2; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[2]; - l = hl[2]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[2] = ah2 = (c & 0xffff) | (d << 16); - hl[2] = al2 = (a & 0xffff) | (b << 16); - - h = ah3; - l = al3; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[3]; - l = hl[3]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[3] = ah3 = (c & 0xffff) | (d << 16); - hl[3] = al3 = (a & 0xffff) | (b << 16); - - h = ah4; - l = al4; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[4]; - l = hl[4]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[4] = ah4 = (c & 0xffff) | (d << 16); - hl[4] = al4 = (a & 0xffff) | (b << 16); - - h = ah5; - l = al5; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[5]; - l = hl[5]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[5] = ah5 = (c & 0xffff) | (d << 16); - hl[5] = al5 = (a & 0xffff) | (b << 16); - - h = ah6; - l = al6; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[6]; - l = hl[6]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[6] = ah6 = (c & 0xffff) | (d << 16); - hl[6] = al6 = (a & 0xffff) | (b << 16); - - h = ah7; - l = al7; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[7]; - l = hl[7]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[7] = ah7 = (c & 0xffff) | (d << 16); - hl[7] = al7 = (a & 0xffff) | (b << 16); - - pos += 128; - n -= 128; - } - - return n; -} - -function crypto_hash(out, m, n) { - var hh = new Int32Array(8), - hl = new Int32Array(8), - x = new Uint8Array(256), - i, b = n; - - hh[0] = 0x6a09e667; - hh[1] = 0xbb67ae85; - hh[2] = 0x3c6ef372; - hh[3] = 0xa54ff53a; - hh[4] = 0x510e527f; - hh[5] = 0x9b05688c; - hh[6] = 0x1f83d9ab; - hh[7] = 0x5be0cd19; - - hl[0] = 0xf3bcc908; - hl[1] = 0x84caa73b; - hl[2] = 0xfe94f82b; - hl[3] = 0x5f1d36f1; - hl[4] = 0xade682d1; - hl[5] = 0x2b3e6c1f; - hl[6] = 0xfb41bd6b; - hl[7] = 0x137e2179; - - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; - - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; - - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, (b / 0x20000000) | 0, b << 3); - crypto_hashblocks_hl(hh, hl, x, n); - - for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); - - return 0; -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - mlen = -1; - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; -} - -var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; - -nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, - - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES -}; - -/* High-level API */ - -function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); -} - -function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); -} - -function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -// TODO: Completely remove this in v0.15. -if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); - }; -} - -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; -}; - -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; - -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); -}; - -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; -}; - -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); -}; - -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; -}; - -nacl.box.after = nacl.secretbox; - -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; - -nacl.box.open.after = nacl.secretbox.open; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; -nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; -nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; -nacl.box.nonceLength = crypto_box_NONCEBYTES; -nacl.box.overheadLength = nacl.secretbox.overheadLength; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; - -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; - -nacl.hash.hashLength = crypto_hash_BYTES; - -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0) ? true : false; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof require !== 'undefined') { - // Node.js. - crypto = require('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); diff --git a/reverse_engineering/node_modules/tweetnacl/nacl-fast.min.js b/reverse_engineering/node_modules/tweetnacl/nacl-fast.min.js deleted file mode 100644 index 8bc47da..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl-fast.min.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(r){"use strict";function t(r,t,n,e){r[t]=n>>24&255,r[t+1]=n>>16&255,r[t+2]=n>>8&255,r[t+3]=255&n,r[t+4]=e>>24&255,r[t+5]=e>>16&255,r[t+6]=e>>8&255,r[t+7]=255&e}function n(r,t,n,e,o){var i,h=0;for(i=0;i>>8)-1}function e(r,t,e,o){return n(r,t,e,o,16)}function o(r,t,e,o){return n(r,t,e,o,32)}function i(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,c=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,p=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,_=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,A=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,d=i,U=h,E=a,x=f,M=s,m=c,B=u,S=y,K=l,T=w,Y=p,k=v,L=b,z=g,R=_,P=A,O=0;O<20;O+=2)o=d+L|0,M^=o<<7|o>>>25,o=M+d|0,K^=o<<9|o>>>23,o=K+M|0,L^=o<<13|o>>>19,o=L+K|0,d^=o<<18|o>>>14,o=m+U|0,T^=o<<7|o>>>25,o=T+m|0,z^=o<<9|o>>>23,o=z+T|0,U^=o<<13|o>>>19,o=U+z|0,m^=o<<18|o>>>14,o=Y+B|0,R^=o<<7|o>>>25,o=R+Y|0,E^=o<<9|o>>>23,o=E+R|0,B^=o<<13|o>>>19,o=B+E|0,Y^=o<<18|o>>>14,o=P+k|0,x^=o<<7|o>>>25,o=x+P|0,S^=o<<9|o>>>23,o=S+x|0,k^=o<<13|o>>>19,o=k+S|0,P^=o<<18|o>>>14,o=d+x|0,U^=o<<7|o>>>25,o=U+d|0,E^=o<<9|o>>>23,o=E+U|0,x^=o<<13|o>>>19,o=x+E|0,d^=o<<18|o>>>14,o=m+M|0,B^=o<<7|o>>>25,o=B+m|0,S^=o<<9|o>>>23,o=S+B|0,M^=o<<13|o>>>19,o=M+S|0,m^=o<<18|o>>>14,o=Y+T|0,k^=o<<7|o>>>25,o=k+Y|0,K^=o<<9|o>>>23,o=K+k|0,T^=o<<13|o>>>19,o=T+K|0,Y^=o<<18|o>>>14,o=P+R|0,L^=o<<7|o>>>25,o=L+P|0,z^=o<<9|o>>>23,o=z+L|0,R^=o<<13|o>>>19,o=R+z|0,P^=o<<18|o>>>14;d=d+i|0,U=U+h|0,E=E+a|0,x=x+f|0,M=M+s|0,m=m+c|0,B=B+u|0,S=S+y|0,K=K+l|0,T=T+w|0,Y=Y+p|0,k=k+v|0,L=L+b|0,z=z+g|0,R=R+_|0,P=P+A|0,r[0]=d>>>0&255,r[1]=d>>>8&255,r[2]=d>>>16&255,r[3]=d>>>24&255,r[4]=U>>>0&255,r[5]=U>>>8&255,r[6]=U>>>16&255,r[7]=U>>>24&255,r[8]=E>>>0&255,r[9]=E>>>8&255,r[10]=E>>>16&255,r[11]=E>>>24&255,r[12]=x>>>0&255,r[13]=x>>>8&255,r[14]=x>>>16&255,r[15]=x>>>24&255,r[16]=M>>>0&255,r[17]=M>>>8&255,r[18]=M>>>16&255,r[19]=M>>>24&255,r[20]=m>>>0&255,r[21]=m>>>8&255,r[22]=m>>>16&255,r[23]=m>>>24&255,r[24]=B>>>0&255,r[25]=B>>>8&255,r[26]=B>>>16&255,r[27]=B>>>24&255,r[28]=S>>>0&255,r[29]=S>>>8&255,r[30]=S>>>16&255,r[31]=S>>>24&255,r[32]=K>>>0&255,r[33]=K>>>8&255,r[34]=K>>>16&255,r[35]=K>>>24&255,r[36]=T>>>0&255,r[37]=T>>>8&255,r[38]=T>>>16&255,r[39]=T>>>24&255,r[40]=Y>>>0&255,r[41]=Y>>>8&255,r[42]=Y>>>16&255,r[43]=Y>>>24&255,r[44]=k>>>0&255,r[45]=k>>>8&255,r[46]=k>>>16&255,r[47]=k>>>24&255,r[48]=L>>>0&255,r[49]=L>>>8&255,r[50]=L>>>16&255,r[51]=L>>>24&255,r[52]=z>>>0&255,r[53]=z>>>8&255,r[54]=z>>>16&255,r[55]=z>>>24&255,r[56]=R>>>0&255,r[57]=R>>>8&255,r[58]=R>>>16&255,r[59]=R>>>24&255,r[60]=P>>>0&255,r[61]=P>>>8&255,r[62]=P>>>16&255,r[63]=P>>>24&255}function h(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,c=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,p=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,_=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,A=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,d=i,U=h,E=a,x=f,M=s,m=c,B=u,S=y,K=l,T=w,Y=p,k=v,L=b,z=g,R=_,P=A,O=0;O<20;O+=2)o=d+L|0,M^=o<<7|o>>>25,o=M+d|0,K^=o<<9|o>>>23,o=K+M|0,L^=o<<13|o>>>19,o=L+K|0,d^=o<<18|o>>>14,o=m+U|0,T^=o<<7|o>>>25,o=T+m|0,z^=o<<9|o>>>23,o=z+T|0,U^=o<<13|o>>>19,o=U+z|0,m^=o<<18|o>>>14,o=Y+B|0,R^=o<<7|o>>>25,o=R+Y|0,E^=o<<9|o>>>23,o=E+R|0,B^=o<<13|o>>>19,o=B+E|0,Y^=o<<18|o>>>14,o=P+k|0,x^=o<<7|o>>>25,o=x+P|0,S^=o<<9|o>>>23,o=S+x|0,k^=o<<13|o>>>19,o=k+S|0,P^=o<<18|o>>>14,o=d+x|0,U^=o<<7|o>>>25,o=U+d|0,E^=o<<9|o>>>23,o=E+U|0,x^=o<<13|o>>>19,o=x+E|0,d^=o<<18|o>>>14,o=m+M|0,B^=o<<7|o>>>25,o=B+m|0,S^=o<<9|o>>>23,o=S+B|0,M^=o<<13|o>>>19,o=M+S|0,m^=o<<18|o>>>14,o=Y+T|0,k^=o<<7|o>>>25,o=k+Y|0,K^=o<<9|o>>>23,o=K+k|0,T^=o<<13|o>>>19,o=T+K|0,Y^=o<<18|o>>>14,o=P+R|0,L^=o<<7|o>>>25,o=L+P|0,z^=o<<9|o>>>23,o=z+L|0,R^=o<<13|o>>>19,o=R+z|0,P^=o<<18|o>>>14;r[0]=d>>>0&255,r[1]=d>>>8&255,r[2]=d>>>16&255,r[3]=d>>>24&255,r[4]=m>>>0&255,r[5]=m>>>8&255,r[6]=m>>>16&255,r[7]=m>>>24&255,r[8]=Y>>>0&255,r[9]=Y>>>8&255,r[10]=Y>>>16&255,r[11]=Y>>>24&255,r[12]=P>>>0&255,r[13]=P>>>8&255,r[14]=P>>>16&255,r[15]=P>>>24&255,r[16]=B>>>0&255,r[17]=B>>>8&255,r[18]=B>>>16&255,r[19]=B>>>24&255,r[20]=S>>>0&255,r[21]=S>>>8&255,r[22]=S>>>16&255,r[23]=S>>>24&255,r[24]=K>>>0&255,r[25]=K>>>8&255,r[26]=K>>>16&255,r[27]=K>>>24&255,r[28]=T>>>0&255,r[29]=T>>>8&255,r[30]=T>>>16&255,r[31]=T>>>24&255}function a(r,t,n,e){i(r,t,n,e)}function f(r,t,n,e){h(r,t,n,e)}function s(r,t,n,e,o,i,h){var f,s,c=new Uint8Array(16),u=new Uint8Array(64);for(s=0;s<16;s++)c[s]=0;for(s=0;s<8;s++)c[s]=i[s];for(;o>=64;){for(a(u,c,h,ur),s=0;s<64;s++)r[t+s]=n[e+s]^u[s];for(f=1,s=8;s<16;s++)f=f+(255&c[s])|0,c[s]=255&f,f>>>=8;o-=64,t+=64,e+=64}if(o>0)for(a(u,c,h,ur),s=0;s=64;){for(a(s,f,o,ur),h=0;h<64;h++)r[t+h]=s[h];for(i=1,h=8;h<16;h++)i=i+(255&f[h])|0,f[h]=255&i,i>>>=8;n-=64,t+=64}if(n>0)for(a(s,f,o,ur),h=0;h>16&1),i[n-1]&=65535;i[15]=h[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,_(h,i,1-o)}for(n=0;n<16;n++)r[2*n]=255&h[n],r[2*n+1]=h[n]>>8}function d(r,t){var n=new Uint8Array(32),e=new Uint8Array(32);return A(n,r),A(e,t),o(n,0,e,0)}function U(r){var t=new Uint8Array(32);return A(t,r),1&t[0]}function E(r,t){var n;for(n=0;n<16;n++)r[n]=t[2*n]+(t[2*n+1]<<8);r[15]&=32767}function x(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]+n[e]}function M(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]-n[e]}function m(r,t,n){var e,o,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+=e*N,E+=e*C,x+=e*F,M+=e*I,m+=e*G,B+=e*Z,S+=e*j,K+=e*q,T+=e*V,Y+=e*X,k+=e*D,L+=e*H,z+=e*J,R+=e*Q,i+=38*d,h+=38*U,a+=38*E,f+=38*x,s+=38*M,c+=38*m,u+=38*B,y+=38*S,l+=38*K,w+=38*T,p+=38*Y,v+=38*k,b+=38*L,g+=38*z,_+=38*R,o=1,e=i+o+65535,o=Math.floor(e/65536),i=e-65536*o,e=h+o+65535,o=Math.floor(e/65536),h=e-65536*o,e=a+o+65535,o=Math.floor(e/65536),a=e-65536*o,e=f+o+65535,o=Math.floor(e/65536),f=e-65536*o,e=s+o+65535,o=Math.floor(e/65536),s=e-65536*o,e=c+o+65535,o=Math.floor(e/65536),c=e-65536*o,e=u+o+65535,o=Math.floor(e/65536),u=e-65536*o,e=y+o+65535,o=Math.floor(e/65536),y=e-65536*o,e=l+o+65535,o=Math.floor(e/65536),l=e-65536*o,e=w+o+65535,o=Math.floor(e/65536),w=e-65536*o,e=p+o+65535,o=Math.floor(e/65536),p=e-65536*o,e=v+o+65535,o=Math.floor(e/65536),v=e-65536*o,e=b+o+65535,o=Math.floor(e/65536),b=e-65536*o,e=g+o+65535,o=Math.floor(e/65536),g=e-65536*o,e=_+o+65535,o=Math.floor(e/65536),_=e-65536*o,e=A+o+65535,o=Math.floor(e/65536),A=e-65536*o,i+=o-1+37*(o-1),o=1,e=i+o+65535,o=Math.floor(e/65536),i=e-65536*o,e=h+o+65535,o=Math.floor(e/65536),h=e-65536*o,e=a+o+65535,o=Math.floor(e/65536),a=e-65536*o,e=f+o+65535,o=Math.floor(e/65536),f=e-65536*o,e=s+o+65535,o=Math.floor(e/65536),s=e-65536*o,e=c+o+65535,o=Math.floor(e/65536),c=e-65536*o,e=u+o+65535,o=Math.floor(e/65536),u=e-65536*o,e=y+o+65535,o=Math.floor(e/65536),y=e-65536*o,e=l+o+65535,o=Math.floor(e/65536),l=e-65536*o,e=w+o+65535,o=Math.floor(e/65536),w=e-65536*o,e=p+o+65535,o=Math.floor(e/65536),p=e-65536*o,e=v+o+65535,o=Math.floor(e/65536),v=e-65536*o,e=b+o+65535,o=Math.floor(e/65536),b=e-65536*o,e=g+o+65535,o=Math.floor(e/65536),g=e-65536*o,e=_+o+65535,o=Math.floor(e/65536),_=e-65536*o,e=A+o+65535,o=Math.floor(e/65536),A=e-65536*o,i+=o-1+37*(o-1),r[0]=i,r[1]=h,r[2]=a,r[3]=f,r[4]=s,r[5]=c,r[6]=u,r[7]=y,r[8]=l,r[9]=w,r[10]=p,r[11]=v,r[12]=b,r[13]=g;r[14]=_;r[15]=A}function B(r,t){m(r,t,t)}function S(r,t){var n,e=$();for(n=0;n<16;n++)e[n]=t[n];for(n=253;n>=0;n--)B(e,e),2!==n&&4!==n&&m(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function K(r,t){var n,e=$();for(n=0;n<16;n++)e[n]=t[n];for(n=250;n>=0;n--)B(e,e),1!==n&&m(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function T(r,t,n){var e,o,i=new Uint8Array(32),h=new Float64Array(80),a=$(),f=$(),s=$(),c=$(),u=$(),y=$();for(o=0;o<31;o++)i[o]=t[o];for(i[31]=127&t[31]|64,i[0]&=248,E(h,n),o=0;o<16;o++)f[o]=h[o],c[o]=a[o]=s[o]=0;for(a[0]=c[0]=1,o=254;o>=0;--o)e=i[o>>>3]>>>(7&o)&1,_(a,f,e),_(s,c,e),x(u,a,s),M(a,a,s),x(s,f,c),M(f,f,c),B(c,u),B(y,a),m(a,s,a),m(s,f,u),x(u,a,s),M(a,a,s),B(f,a),M(s,c,y),m(a,s,ir),x(a,a,c),m(s,s,a),m(a,c,y),m(c,f,h),B(f,u),_(a,f,e),_(s,c,e);for(o=0;o<16;o++)h[o+16]=a[o],h[o+32]=s[o],h[o+48]=f[o],h[o+64]=c[o];var l=h.subarray(32),w=h.subarray(16);return S(l,l),m(w,w,l),A(r,w),0}function Y(r,t){return T(r,t,nr)}function k(r,t){return rr(t,32),Y(r,t)}function L(r,t,n){var e=new Uint8Array(32);return T(e,n,t),f(r,tr,e,ur)}function z(r,t,n,e,o,i){var h=new Uint8Array(32);return L(h,o,i),lr(r,t,n,e,h)}function R(r,t,n,e,o,i){var h=new Uint8Array(32);return L(h,o,i),wr(r,t,n,e,h)}function P(r,t,n,e){for(var o,i,h,a,f,s,c,u,y,l,w,p,v,b,g,_,A,d,U,E,x,M,m,B,S,K,T=new Int32Array(16),Y=new Int32Array(16),k=r[0],L=r[1],z=r[2],R=r[3],P=r[4],O=r[5],N=r[6],C=r[7],F=t[0],I=t[1],G=t[2],Z=t[3],j=t[4],q=t[5],V=t[6],X=t[7],D=0;e>=128;){for(U=0;U<16;U++)E=8*U+D,T[U]=n[E+0]<<24|n[E+1]<<16|n[E+2]<<8|n[E+3],Y[U]=n[E+4]<<24|n[E+5]<<16|n[E+6]<<8|n[E+7];for(U=0;U<80;U++)if(o=k,i=L,h=z,a=R,f=P,s=O,c=N,u=C,y=F,l=I,w=G,p=Z,v=j,b=q,g=V,_=X,x=C,M=X,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=(P>>>14|j<<18)^(P>>>18|j<<14)^(j>>>9|P<<23),M=(j>>>14|P<<18)^(j>>>18|P<<14)^(P>>>9|j<<23),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=P&O^~P&N,M=j&q^~j&V,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=pr[2*U],M=pr[2*U+1],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=T[U%16],M=Y[U%16],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,A=65535&S|K<<16,d=65535&m|B<<16,x=A,M=d,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=(k>>>28|F<<4)^(F>>>2|k<<30)^(F>>>7|k<<25),M=(F>>>28|k<<4)^(k>>>2|F<<30)^(k>>>7|F<<25),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=k&L^k&z^L&z,M=F&I^F&G^I&G,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,u=65535&S|K<<16,_=65535&m|B<<16,x=a,M=p,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=A,M=d,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,a=65535&S|K<<16,p=65535&m|B<<16,L=o,z=i,R=h,P=a,O=f,N=s,C=c,k=u,I=y,G=l,Z=w,j=p,q=v,V=b,X=g,F=_,U%16===15)for(E=0;E<16;E++)x=T[E],M=Y[E],m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=T[(E+9)%16],M=Y[(E+9)%16],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,A=T[(E+1)%16],d=Y[(E+1)%16],x=(A>>>1|d<<31)^(A>>>8|d<<24)^A>>>7,M=(d>>>1|A<<31)^(d>>>8|A<<24)^(d>>>7|A<<25),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,A=T[(E+14)%16],d=Y[(E+14)%16],x=(A>>>19|d<<13)^(d>>>29|A<<3)^A>>>6,M=(d>>>19|A<<13)^(A>>>29|d<<3)^(d>>>6|A<<26),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,T[E]=65535&S|K<<16,Y[E]=65535&m|B<<16;x=k,M=F,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[0],M=t[0],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[0]=k=65535&S|K<<16,t[0]=F=65535&m|B<<16,x=L,M=I,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[1],M=t[1],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[1]=L=65535&S|K<<16,t[1]=I=65535&m|B<<16,x=z,M=G,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[2],M=t[2],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[2]=z=65535&S|K<<16,t[2]=G=65535&m|B<<16,x=R,M=Z,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[3],M=t[3],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[3]=R=65535&S|K<<16,t[3]=Z=65535&m|B<<16,x=P,M=j,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[4],M=t[4],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[4]=P=65535&S|K<<16,t[4]=j=65535&m|B<<16,x=O,M=q,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[5],M=t[5],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[5]=O=65535&S|K<<16,t[5]=q=65535&m|B<<16,x=N,M=V,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[6],M=t[6],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[6]=N=65535&S|K<<16,t[6]=V=65535&m|B<<16,x=C,M=X,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[7],M=t[7],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[7]=C=65535&S|K<<16,t[7]=X=65535&m|B<<16,D+=128,e-=128}return e}function O(r,n,e){var o,i=new Int32Array(8),h=new Int32Array(8),a=new Uint8Array(256),f=e;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,h[0]=4089235720,h[1]=2227873595,h[2]=4271175723,h[3]=1595750129,h[4]=2917565137,h[5]=725511199,h[6]=4215389547,h[7]=327033209,P(i,h,n,e),e%=128,o=0;o=0;--o)e=n[o/8|0]>>(7&o)&1,C(r,t,e),N(t,r),N(r,r),C(r,t,e)}function G(r,t){var n=[$(),$(),$(),$()];b(n[0],fr),b(n[1],sr),b(n[2],or),m(n[3],fr,sr),I(r,n,t)}function Z(r,t,n){var e,o=new Uint8Array(64),i=[$(),$(),$(),$()];for(n||rr(t,32),O(o,t,32),o[0]&=248,o[31]&=127,o[31]|=64,G(i,o),F(r,i),e=0;e<32;e++)t[e+32]=r[e];return 0}function j(r,t){var n,e,o,i;for(e=63;e>=32;--e){for(n=0,o=e-32,i=e-12;o>8,t[o]-=256*n;t[o]+=n,t[e]=0}for(n=0,o=0;o<32;o++)t[o]+=n-(t[31]>>4)*vr[o],n=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=n*vr[o];for(e=0;e<32;e++)t[e+1]+=t[e]>>8,r[e]=255&t[e]}function q(r){var t,n=new Float64Array(64);for(t=0;t<64;t++)n[t]=r[t];for(t=0;t<64;t++)r[t]=0;j(r,n)}function V(r,t,n,e){var o,i,h=new Uint8Array(64),a=new Uint8Array(64),f=new Uint8Array(64),s=new Float64Array(64),c=[$(),$(),$(),$()];O(h,e,32),h[0]&=248,h[31]&=127,h[31]|=64;var u=n+64;for(o=0;o>7&&M(r[0],er,r[0]),m(r[3],r[0],r[1]),0)}function D(r,t,n,e){var i,h,a=new Uint8Array(32),f=new Uint8Array(64),s=[$(),$(),$(),$()],c=[$(),$(),$(),$()];if(h=-1,n<64)return-1;if(X(c,e))return-1;for(i=0;i>>13|n<<3),e=255&r[4]|(255&r[5])<<8,this.r[2]=7939&(n>>>10|e<<6),o=255&r[6]|(255&r[7])<<8,this.r[3]=8191&(e>>>7|o<<9),i=255&r[8]|(255&r[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,h=255&r[10]|(255&r[11])<<8,this.r[6]=8191&(i>>>14|h<<2),a=255&r[12]|(255&r[13])<<8,this.r[7]=8065&(h>>>11|a<<5),f=255&r[14]|(255&r[15])<<8,this.r[8]=8191&(a>>>8|f<<8),this.r[9]=f>>>5&127,this.pad[0]=255&r[16]|(255&r[17])<<8,this.pad[1]=255&r[18]|(255&r[19])<<8,this.pad[2]=255&r[20]|(255&r[21])<<8,this.pad[3]=255&r[22]|(255&r[23])<<8,this.pad[4]=255&r[24]|(255&r[25])<<8,this.pad[5]=255&r[26]|(255&r[27])<<8,this.pad[6]=255&r[28]|(255&r[29])<<8,this.pad[7]=255&r[30]|(255&r[31])<<8};yr.prototype.blocks=function(r,t,n){for(var e,o,i,h,a,f,s,c,u,y,l,w,p,v,b,g,_,A,d,U=this.fin?0:2048,E=this.h[0],x=this.h[1],M=this.h[2],m=this.h[3],B=this.h[4],S=this.h[5],K=this.h[6],T=this.h[7],Y=this.h[8],k=this.h[9],L=this.r[0],z=this.r[1],R=this.r[2],P=this.r[3],O=this.r[4],N=this.r[5],C=this.r[6],F=this.r[7],I=this.r[8],G=this.r[9];n>=16;)e=255&r[t+0]|(255&r[t+1])<<8,E+=8191&e,o=255&r[t+2]|(255&r[t+3])<<8,x+=8191&(e>>>13|o<<3),i=255&r[t+4]|(255&r[t+5])<<8,M+=8191&(o>>>10|i<<6),h=255&r[t+6]|(255&r[t+7])<<8,m+=8191&(i>>>7|h<<9),a=255&r[t+8]|(255&r[t+9])<<8,B+=8191&(h>>>4|a<<12),S+=a>>>1&8191,f=255&r[t+10]|(255&r[t+11])<<8,K+=8191&(a>>>14|f<<2),s=255&r[t+12]|(255&r[t+13])<<8,T+=8191&(f>>>11|s<<5),c=255&r[t+14]|(255&r[t+15])<<8,Y+=8191&(s>>>8|c<<8),k+=c>>>5|U,u=0,y=u,y+=E*L,y+=x*(5*G),y+=M*(5*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*G),u+=A>>>13,A&=8191,d=u,d+=E*G,d+=x*I,d+=M*F,d+=m*C,d+=B*N,u=d>>>13,d&=8191,d+=S*O,d+=K*P,d+=T*R,d+=Y*z,d+=k*L,u+=d>>>13,d&=8191,u=(u<<2)+u|0,u=u+y|0,y=8191&u,u>>>=13,l+=u,E=y,x=l,M=w,m=p,B=v,S=b,K=g,T=_,Y=A,k=d,t+=16,n-=16;this.h[0]=E,this.h[1]=x,this.h[2]=M,this.h[3]=m,this.h[4]=B,this.h[5]=S,this.h[6]=K,this.h[7]=T,this.h[8]=Y,this.h[9]=k},yr.prototype.finish=function(r,t){var n,e,o,i,h=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(n=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=n,n=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*n,n=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=n,n=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=n,h[0]=this.h[0]+5,n=h[0]>>>13,h[0]&=8191,i=1;i<10;i++)h[i]=this.h[i]+n,n=h[i]>>>13,h[i]&=8191;for(h[9]-=8192,e=(1^n)-1,i=0;i<10;i++)h[i]&=e;for(e=~e,i=0;i<10;i++)this.h[i]=this.h[i]&e|h[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;r[t+0]=this.h[0]>>>0&255,r[t+1]=this.h[0]>>>8&255,r[t+2]=this.h[1]>>>0&255,r[t+3]=this.h[1]>>>8&255,r[t+4]=this.h[2]>>>0&255,r[t+5]=this.h[2]>>>8&255,r[t+6]=this.h[3]>>>0&255,r[t+7]=this.h[3]>>>8&255,r[t+8]=this.h[4]>>>0&255,r[t+9]=this.h[4]>>>8&255,r[t+10]=this.h[5]>>>0&255,r[t+11]=this.h[5]>>>8&255,r[t+12]=this.h[6]>>>0&255,r[t+13]=this.h[6]>>>8&255,r[t+14]=this.h[7]>>>0&255,r[t+15]=this.h[7]>>>8&255},yr.prototype.update=function(r,t,n){var e,o;if(this.leftover){for(o=16-this.leftover,o>n&&(o=n),e=0;e=16&&(o=n-n%16,this.blocks(r,t,o),t+=o,n-=o),n){for(e=0;e=0},r.sign.keyPair=function(){var r=new Uint8Array(Tr),t=new Uint8Array(Yr);return Z(r,t),{publicKey:r,secretKey:t}},r.sign.keyPair.fromSecretKey=function(r){if(Q(r),r.length!==Yr)throw new Error("bad secret key size");for(var t=new Uint8Array(Tr),n=0;n void): void; -} diff --git a/reverse_engineering/node_modules/tweetnacl/nacl.js b/reverse_engineering/node_modules/tweetnacl/nacl.js deleted file mode 100644 index f72dd78..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl.js +++ /dev/null @@ -1,1175 +0,0 @@ -(function(nacl) { -'use strict'; - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var u64 = function(h, l) { this.hi = h|0 >>> 0; this.lo = l|0 >>> 0; }; -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _0 = new Uint8Array(16); -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function L32(x, c) { return (x << c) | (x >>> (32 - c)); } - -function ld32(x, i) { - var u = x[i+3] & 0xff; - u = (u<<8)|(x[i+2] & 0xff); - u = (u<<8)|(x[i+1] & 0xff); - return (u<<8)|(x[i+0] & 0xff); -} - -function dl64(x, i) { - var h = (x[i] << 24) | (x[i+1] << 16) | (x[i+2] << 8) | x[i+3]; - var l = (x[i+4] << 24) | (x[i+5] << 16) | (x[i+6] << 8) | x[i+7]; - return new u64(h, l); -} - -function st32(x, j, u) { - var i; - for (i = 0; i < 4; i++) { x[j+i] = u & 255; u >>>= 8; } -} - -function ts64(x, i, u) { - x[i] = (u.hi >> 24) & 0xff; - x[i+1] = (u.hi >> 16) & 0xff; - x[i+2] = (u.hi >> 8) & 0xff; - x[i+3] = u.hi & 0xff; - x[i+4] = (u.lo >> 24) & 0xff; - x[i+5] = (u.lo >> 16) & 0xff; - x[i+6] = (u.lo >> 8) & 0xff; - x[i+7] = u.lo & 0xff; -} - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function core(out,inp,k,c,h) { - var w = new Uint32Array(16), x = new Uint32Array(16), - y = new Uint32Array(16), t = new Uint32Array(4); - var i, j, m; - - for (i = 0; i < 4; i++) { - x[5*i] = ld32(c, 4*i); - x[1+i] = ld32(k, 4*i); - x[6+i] = ld32(inp, 4*i); - x[11+i] = ld32(k, 16+4*i); - } - - for (i = 0; i < 16; i++) y[i] = x[i]; - - for (i = 0; i < 20; i++) { - for (j = 0; j < 4; j++) { - for (m = 0; m < 4; m++) t[m] = x[(5*j+4*m)%16]; - t[1] ^= L32((t[0]+t[3])|0, 7); - t[2] ^= L32((t[1]+t[0])|0, 9); - t[3] ^= L32((t[2]+t[1])|0,13); - t[0] ^= L32((t[3]+t[2])|0,18); - for (m = 0; m < 4; m++) w[4*j+(j+m)%4] = t[m]; - } - for (m = 0; m < 16; m++) x[m] = w[m]; - } - - if (h) { - for (i = 0; i < 16; i++) x[i] = (x[i] + y[i]) | 0; - for (i = 0; i < 4; i++) { - x[5*i] = (x[5*i] - ld32(c, 4*i)) | 0; - x[6+i] = (x[6+i] - ld32(inp, 4*i)) | 0; - } - for (i = 0; i < 4; i++) { - st32(out,4*i,x[5*i]); - st32(out,16+4*i,x[6+i]); - } - } else { - for (i = 0; i < 16; i++) st32(out, 4 * i, (x[i] + y[i]) | 0); - } -} - -function crypto_core_salsa20(out,inp,k,c) { - core(out,inp,k,c,false); - return 0; -} - -function crypto_core_hsalsa20(out,inp,k,c) { - core(out,inp,k,c,true); - return 0; -} - -var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" - -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - if (!b) return 0; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - if (m) mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; - } - return 0; -} - -function crypto_stream_salsa20(c,cpos,d,n,k) { - return crypto_stream_salsa20_xor(c,cpos,null,0,d,n,k); -} - -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - return crypto_stream_salsa20(c,cpos,d,n.subarray(16),s); -} - -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,n.subarray(16),s); -} - -function add1305(h, c) { - var j, u = 0; - for (j = 0; j < 17; j++) { - u = (u + ((h[j] + c[j]) | 0)) | 0; - h[j] = u & 255; - u >>>= 8; - } -} - -var minusp = new Uint32Array([ - 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252 -]); - -function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s, i, j, u; - var x = new Uint32Array(17), r = new Uint32Array(17), - h = new Uint32Array(17), c = new Uint32Array(17), - g = new Uint32Array(17); - for (j = 0; j < 17; j++) r[j]=h[j]=0; - for (j = 0; j < 16; j++) r[j]=k[j]; - r[3]&=15; - r[4]&=252; - r[7]&=15; - r[8]&=252; - r[11]&=15; - r[12]&=252; - r[15]&=15; - - while (n > 0) { - for (j = 0; j < 17; j++) c[j] = 0; - for (j = 0; (j < 16) && (j < n); ++j) c[j] = m[mpos+j]; - c[j] = 1; - mpos += j; n -= j; - add1305(h,c); - for (i = 0; i < 17; i++) { - x[i] = 0; - for (j = 0; j < 17; j++) x[i] = (x[i] + (h[j] * ((j <= i) ? r[i - j] : ((320 * r[i + 17 - j])|0))) | 0) | 0; - } - for (i = 0; i < 17; i++) h[i] = x[i]; - u = 0; - for (j = 0; j < 16; j++) { - u = (u + h[j]) | 0; - h[j] = u & 255; - u >>>= 8; - } - u = (u + h[16]) | 0; h[16] = u & 3; - u = (5 * (u >>> 2)) | 0; - for (j = 0; j < 16; j++) { - u = (u + h[j]) | 0; - h[j] = u & 255; - u >>>= 8; - } - u = (u + h[16]) | 0; h[16] = u; - } - - for (j = 0; j < 17; j++) g[j] = h[j]; - add1305(h,minusp); - s = (-(h[16] >>> 7) | 0); - for (j = 0; j < 17; j++) h[j] ^= s & (g[j] ^ h[j]); - - for (j = 0; j < 16; j++) c[j] = k[j + 16]; - c[16] = 0; - add1305(h,c); - for (j = 0; j < 16; j++) out[outpos+j] = h[j]; - return 0; -} - -function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); -} - -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; -} - -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var c; - var i; - for (i = 0; i < 16; i++) { - o[i] += 65536; - c = Math.floor(o[i] / 65536); - o[(i+1)*(i<15?1:0)] += c - 1 + 37 * (c-1) * (i===15?1:0); - o[i] -= (c * 65536); - } -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - var i; - for (i = 0; i < 16; i++) o[i] = (a[i] + b[i])|0; -} - -function Z(o, a, b) { - var i; - for (i = 0; i < 16; i++) o[i] = (a[i] - b[i])|0; -} - -function M(o, a, b) { - var i, j, t = new Float64Array(31); - for (i = 0; i < 31; i++) t[i] = 0; - for (i = 0; i < 16; i++) { - for (j = 0; j < 16; j++) { - t[i+j] += a[i] * b[j]; - } - } - for (i = 0; i < 15; i++) { - t[i] += 38 * t[i+16]; - } - for (i = 0; i < 16; i++) o[i] = t[i]; - car25519(o); - car25519(o); -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); -} - -var crypto_box_afternm = crypto_secretbox; -var crypto_box_open_afternm = crypto_secretbox_open; - -function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); -} - -function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); -} - -function add64() { - var a = 0, b = 0, c = 0, d = 0, m16 = 65535, l, h, i; - for (i = 0; i < arguments.length; i++) { - l = arguments[i].lo; - h = arguments[i].hi; - a += (l & m16); b += (l >>> 16); - c += (h & m16); d += (h >>> 16); - } - - b += (a >>> 16); - c += (b >>> 16); - d += (c >>> 16); - - return new u64((c & m16) | (d << 16), (a & m16) | (b << 16)); -} - -function shr64(x, c) { - return new u64((x.hi >>> c), (x.lo >>> c) | (x.hi << (32 - c))); -} - -function xor64() { - var l = 0, h = 0, i; - for (i = 0; i < arguments.length; i++) { - l ^= arguments[i].lo; - h ^= arguments[i].hi; - } - return new u64(h, l); -} - -function R(x, c) { - var h, l, c1 = 32 - c; - if (c < 32) { - h = (x.hi >>> c) | (x.lo << c1); - l = (x.lo >>> c) | (x.hi << c1); - } else if (c < 64) { - h = (x.lo >>> c) | (x.hi << c1); - l = (x.hi >>> c) | (x.lo << c1); - } - return new u64(h, l); -} - -function Ch(x, y, z) { - var h = (x.hi & y.hi) ^ (~x.hi & z.hi), - l = (x.lo & y.lo) ^ (~x.lo & z.lo); - return new u64(h, l); -} - -function Maj(x, y, z) { - var h = (x.hi & y.hi) ^ (x.hi & z.hi) ^ (y.hi & z.hi), - l = (x.lo & y.lo) ^ (x.lo & z.lo) ^ (y.lo & z.lo); - return new u64(h, l); -} - -function Sigma0(x) { return xor64(R(x,28), R(x,34), R(x,39)); } -function Sigma1(x) { return xor64(R(x,14), R(x,18), R(x,41)); } -function sigma0(x) { return xor64(R(x, 1), R(x, 8), shr64(x,7)); } -function sigma1(x) { return xor64(R(x,19), R(x,61), shr64(x,6)); } - -var K = [ - new u64(0x428a2f98, 0xd728ae22), new u64(0x71374491, 0x23ef65cd), - new u64(0xb5c0fbcf, 0xec4d3b2f), new u64(0xe9b5dba5, 0x8189dbbc), - new u64(0x3956c25b, 0xf348b538), new u64(0x59f111f1, 0xb605d019), - new u64(0x923f82a4, 0xaf194f9b), new u64(0xab1c5ed5, 0xda6d8118), - new u64(0xd807aa98, 0xa3030242), new u64(0x12835b01, 0x45706fbe), - new u64(0x243185be, 0x4ee4b28c), new u64(0x550c7dc3, 0xd5ffb4e2), - new u64(0x72be5d74, 0xf27b896f), new u64(0x80deb1fe, 0x3b1696b1), - new u64(0x9bdc06a7, 0x25c71235), new u64(0xc19bf174, 0xcf692694), - new u64(0xe49b69c1, 0x9ef14ad2), new u64(0xefbe4786, 0x384f25e3), - new u64(0x0fc19dc6, 0x8b8cd5b5), new u64(0x240ca1cc, 0x77ac9c65), - new u64(0x2de92c6f, 0x592b0275), new u64(0x4a7484aa, 0x6ea6e483), - new u64(0x5cb0a9dc, 0xbd41fbd4), new u64(0x76f988da, 0x831153b5), - new u64(0x983e5152, 0xee66dfab), new u64(0xa831c66d, 0x2db43210), - new u64(0xb00327c8, 0x98fb213f), new u64(0xbf597fc7, 0xbeef0ee4), - new u64(0xc6e00bf3, 0x3da88fc2), new u64(0xd5a79147, 0x930aa725), - new u64(0x06ca6351, 0xe003826f), new u64(0x14292967, 0x0a0e6e70), - new u64(0x27b70a85, 0x46d22ffc), new u64(0x2e1b2138, 0x5c26c926), - new u64(0x4d2c6dfc, 0x5ac42aed), new u64(0x53380d13, 0x9d95b3df), - new u64(0x650a7354, 0x8baf63de), new u64(0x766a0abb, 0x3c77b2a8), - new u64(0x81c2c92e, 0x47edaee6), new u64(0x92722c85, 0x1482353b), - new u64(0xa2bfe8a1, 0x4cf10364), new u64(0xa81a664b, 0xbc423001), - new u64(0xc24b8b70, 0xd0f89791), new u64(0xc76c51a3, 0x0654be30), - new u64(0xd192e819, 0xd6ef5218), new u64(0xd6990624, 0x5565a910), - new u64(0xf40e3585, 0x5771202a), new u64(0x106aa070, 0x32bbd1b8), - new u64(0x19a4c116, 0xb8d2d0c8), new u64(0x1e376c08, 0x5141ab53), - new u64(0x2748774c, 0xdf8eeb99), new u64(0x34b0bcb5, 0xe19b48a8), - new u64(0x391c0cb3, 0xc5c95a63), new u64(0x4ed8aa4a, 0xe3418acb), - new u64(0x5b9cca4f, 0x7763e373), new u64(0x682e6ff3, 0xd6b2b8a3), - new u64(0x748f82ee, 0x5defb2fc), new u64(0x78a5636f, 0x43172f60), - new u64(0x84c87814, 0xa1f0ab72), new u64(0x8cc70208, 0x1a6439ec), - new u64(0x90befffa, 0x23631e28), new u64(0xa4506ceb, 0xde82bde9), - new u64(0xbef9a3f7, 0xb2c67915), new u64(0xc67178f2, 0xe372532b), - new u64(0xca273ece, 0xea26619c), new u64(0xd186b8c7, 0x21c0c207), - new u64(0xeada7dd6, 0xcde0eb1e), new u64(0xf57d4f7f, 0xee6ed178), - new u64(0x06f067aa, 0x72176fba), new u64(0x0a637dc5, 0xa2c898a6), - new u64(0x113f9804, 0xbef90dae), new u64(0x1b710b35, 0x131c471b), - new u64(0x28db77f5, 0x23047d84), new u64(0x32caab7b, 0x40c72493), - new u64(0x3c9ebe0a, 0x15c9bebc), new u64(0x431d67c4, 0x9c100d4c), - new u64(0x4cc5d4be, 0xcb3e42b6), new u64(0x597f299c, 0xfc657e2a), - new u64(0x5fcb6fab, 0x3ad6faec), new u64(0x6c44198c, 0x4a475817) -]; - -function crypto_hashblocks(x, m, n) { - var z = [], b = [], a = [], w = [], t, i, j; - - for (i = 0; i < 8; i++) z[i] = a[i] = dl64(x, 8*i); - - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) w[i] = dl64(m, 8*i+pos); - for (i = 0; i < 80; i++) { - for (j = 0; j < 8; j++) b[j] = a[j]; - t = add64(a[7], Sigma1(a[4]), Ch(a[4], a[5], a[6]), K[i], w[i%16]); - b[7] = add64(t, Sigma0(a[0]), Maj(a[0], a[1], a[2])); - b[3] = add64(b[3], t); - for (j = 0; j < 8; j++) a[(j+1)%8] = b[j]; - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - w[j] = add64(w[j], w[(j+9)%16], sigma0(w[(j+1)%16]), sigma1(w[(j+14)%16])); - } - } - } - - for (i = 0; i < 8; i++) { - a[i] = add64(a[i], z[i]); - z[i] = a[i]; - } - - pos += 128; - n -= 128; - } - - for (i = 0; i < 8; i++) ts64(x, 8*i, z[i]); - return n; -} - -var iv = new Uint8Array([ - 0x6a,0x09,0xe6,0x67,0xf3,0xbc,0xc9,0x08, - 0xbb,0x67,0xae,0x85,0x84,0xca,0xa7,0x3b, - 0x3c,0x6e,0xf3,0x72,0xfe,0x94,0xf8,0x2b, - 0xa5,0x4f,0xf5,0x3a,0x5f,0x1d,0x36,0xf1, - 0x51,0x0e,0x52,0x7f,0xad,0xe6,0x82,0xd1, - 0x9b,0x05,0x68,0x8c,0x2b,0x3e,0x6c,0x1f, - 0x1f,0x83,0xd9,0xab,0xfb,0x41,0xbd,0x6b, - 0x5b,0xe0,0xcd,0x19,0x13,0x7e,0x21,0x79 -]); - -function crypto_hash(out, m, n) { - var h = new Uint8Array(64), x = new Uint8Array(256); - var i, b = n; - - for (i = 0; i < 64; i++) h[i] = iv[i]; - - crypto_hashblocks(h, m, n); - n %= 128; - - for (i = 0; i < 256; i++) x[i] = 0; - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; - - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, new u64((b / 0x20000000) | 0, b << 3)); - crypto_hashblocks(h, x, n); - - for (i = 0; i < 64; i++) out[i] = h[i]; - - return 0; -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - mlen = -1; - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; -} - -var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; - -nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, - - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES -}; - -/* High-level API */ - -function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); -} - -function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); -} - -function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -// TODO: Completely remove this in v0.15. -if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); - }; -} - -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; -}; - -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; - -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); -}; - -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; -}; - -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); -}; - -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; -}; - -nacl.box.after = nacl.secretbox; - -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; - -nacl.box.open.after = nacl.secretbox.open; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; -nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; -nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; -nacl.box.nonceLength = crypto_box_NONCEBYTES; -nacl.box.overheadLength = nacl.secretbox.overheadLength; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; - -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; - -nacl.hash.hashLength = crypto_hash_BYTES; - -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0) ? true : false; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof require !== 'undefined') { - // Node.js. - crypto = require('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); diff --git a/reverse_engineering/node_modules/tweetnacl/nacl.min.js b/reverse_engineering/node_modules/tweetnacl/nacl.min.js deleted file mode 100644 index 4484974..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(r){"use strict";function n(r,n){return r<>>32-n}function e(r,n){var e=255&r[n+3];return e=e<<8|255&r[n+2],e=e<<8|255&r[n+1],e<<8|255&r[n+0]}function t(r,n){var e=r[n]<<24|r[n+1]<<16|r[n+2]<<8|r[n+3],t=r[n+4]<<24|r[n+5]<<16|r[n+6]<<8|r[n+7];return new sr(e,t)}function o(r,n,e){var t;for(t=0;t<4;t++)r[n+t]=255&e,e>>>=8}function i(r,n,e){r[n]=e.hi>>24&255,r[n+1]=e.hi>>16&255,r[n+2]=e.hi>>8&255,r[n+3]=255&e.hi,r[n+4]=e.lo>>24&255,r[n+5]=e.lo>>16&255,r[n+6]=e.lo>>8&255,r[n+7]=255&e.lo}function a(r,n,e,t,o){var i,a=0;for(i=0;i>>8)-1}function f(r,n,e,t){return a(r,n,e,t,16)}function u(r,n,e,t){return a(r,n,e,t,32)}function c(r,t,i,a,f){var u,c,w,y=new Uint32Array(16),l=new Uint32Array(16),s=new Uint32Array(16),h=new Uint32Array(4);for(u=0;u<4;u++)l[5*u]=e(a,4*u),l[1+u]=e(i,4*u),l[6+u]=e(t,4*u),l[11+u]=e(i,16+4*u);for(u=0;u<16;u++)s[u]=l[u];for(u=0;u<20;u++){for(c=0;c<4;c++){for(w=0;w<4;w++)h[w]=l[(5*c+4*w)%16];for(h[1]^=n(h[0]+h[3]|0,7),h[2]^=n(h[1]+h[0]|0,9),h[3]^=n(h[2]+h[1]|0,13),h[0]^=n(h[3]+h[2]|0,18),w=0;w<4;w++)y[4*c+(c+w)%4]=h[w]}for(w=0;w<16;w++)l[w]=y[w]}if(f){for(u=0;u<16;u++)l[u]=l[u]+s[u]|0;for(u=0;u<4;u++)l[5*u]=l[5*u]-e(a,4*u)|0,l[6+u]=l[6+u]-e(t,4*u)|0;for(u=0;u<4;u++)o(r,4*u,l[5*u]),o(r,16+4*u,l[6+u])}else for(u=0;u<16;u++)o(r,4*u,l[u]+s[u]|0)}function w(r,n,e,t){return c(r,n,e,t,!1),0}function y(r,n,e,t){return c(r,n,e,t,!0),0}function l(r,n,e,t,o,i,a){var f,u,c=new Uint8Array(16),y=new Uint8Array(64);if(!o)return 0;for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;o>=64;){for(w(y,c,a,Br),u=0;u<64;u++)r[n+u]=(e?e[t+u]:0)^y[u];for(f=1,u=8;u<16;u++)f=f+(255&c[u])|0,c[u]=255&f,f>>>=8;o-=64,n+=64,e&&(t+=64)}if(o>0)for(w(y,c,a,Br),u=0;u>>=8}function b(r,n,e,t,o,i){var a,f,u,c,w=new Uint32Array(17),y=new Uint32Array(17),l=new Uint32Array(17),s=new Uint32Array(17),h=new Uint32Array(17);for(u=0;u<17;u++)y[u]=l[u]=0;for(u=0;u<16;u++)y[u]=i[u];for(y[3]&=15,y[4]&=252,y[7]&=15,y[8]&=252,y[11]&=15,y[12]&=252,y[15]&=15;o>0;){for(u=0;u<17;u++)s[u]=0;for(u=0;u<16&&u>>=8;for(c=c+l[16]|0,l[16]=3&c,c=5*(c>>>2)|0,u=0;u<16;u++)c=c+l[u]|0,l[u]=255&c,c>>>=8;c=c+l[16]|0,l[16]=c}for(u=0;u<17;u++)h[u]=l[u];for(v(l,Sr),a=0|-(l[16]>>>7),u=0;u<17;u++)l[u]^=a&(h[u]^l[u]);for(u=0;u<16;u++)s[u]=i[u+16];for(s[16]=0,v(l,s),u=0;u<16;u++)r[n+u]=l[u];return 0}function p(r,n,e,t,o,i){var a=new Uint8Array(16);return b(a,0,e,t,o,i),f(r,n,a,0)}function _(r,n,e,t,o){var i;if(e<32)return-1;for(g(r,0,n,0,e,t,o),b(r,16,r,32,e-32,r),i=0;i<16;i++)r[i]=0;return 0}function A(r,n,e,t,o){var i,a=new Uint8Array(32);if(e<32)return-1;if(h(a,0,32,t,o),0!==p(n,16,n,32,e-32,a))return-1;for(g(r,0,n,0,e,t,o),i=0;i<32;i++)r[i]=0;return 0}function U(r,n){var e;for(e=0;e<16;e++)r[e]=0|n[e]}function E(r){var n,e;for(e=0;e<16;e++)r[e]+=65536,n=Math.floor(r[e]/65536),r[(e+1)*(e<15?1:0)]+=n-1+37*(n-1)*(15===e?1:0),r[e]-=65536*n}function d(r,n,e){for(var t,o=~(e-1),i=0;i<16;i++)t=o&(r[i]^n[i]),r[i]^=t,n[i]^=t}function x(r,n){var e,t,o,i=hr(),a=hr();for(e=0;e<16;e++)a[e]=n[e];for(E(a),E(a),E(a),t=0;t<2;t++){for(i[0]=a[0]-65517,e=1;e<15;e++)i[e]=a[e]-65535-(i[e-1]>>16&1),i[e-1]&=65535;i[15]=a[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,d(a,i,1-o)}for(e=0;e<16;e++)r[2*e]=255&a[e],r[2*e+1]=a[e]>>8}function m(r,n){var e=new Uint8Array(32),t=new Uint8Array(32);return x(e,r),x(t,n),u(e,0,t,0)}function B(r){var n=new Uint8Array(32);return x(n,r),1&n[0]}function S(r,n){var e;for(e=0;e<16;e++)r[e]=n[2*e]+(n[2*e+1]<<8);r[15]&=32767}function K(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]+e[t]|0}function T(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]-e[t]|0}function Y(r,n,e){var t,o,i=new Float64Array(31);for(t=0;t<31;t++)i[t]=0;for(t=0;t<16;t++)for(o=0;o<16;o++)i[t+o]+=n[t]*e[o];for(t=0;t<15;t++)i[t]+=38*i[t+16];for(t=0;t<16;t++)r[t]=i[t];E(r),E(r)}function L(r,n){Y(r,n,n)}function k(r,n){var e,t=hr();for(e=0;e<16;e++)t[e]=n[e];for(e=253;e>=0;e--)L(t,t),2!==e&&4!==e&&Y(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function z(r,n){var e,t=hr();for(e=0;e<16;e++)t[e]=n[e];for(e=250;e>=0;e--)L(t,t),1!==e&&Y(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function R(r,n,e){var t,o,i=new Uint8Array(32),a=new Float64Array(80),f=hr(),u=hr(),c=hr(),w=hr(),y=hr(),l=hr();for(o=0;o<31;o++)i[o]=n[o];for(i[31]=127&n[31]|64,i[0]&=248,S(a,e),o=0;o<16;o++)u[o]=a[o],w[o]=f[o]=c[o]=0;for(f[0]=w[0]=1,o=254;o>=0;--o)t=i[o>>>3]>>>(7&o)&1,d(f,u,t),d(c,w,t),K(y,f,c),T(f,f,c),K(c,u,w),T(u,u,w),L(w,y),L(l,f),Y(f,c,f),Y(c,u,y),K(y,f,c),T(f,f,c),L(u,f),T(c,w,l),Y(f,c,Ar),K(f,f,w),Y(c,c,f),Y(f,w,l),Y(w,u,a),L(u,y),d(f,u,t),d(c,w,t);for(o=0;o<16;o++)a[o+16]=f[o],a[o+32]=c[o],a[o+48]=u[o],a[o+64]=w[o];var s=a.subarray(32),h=a.subarray(16);return k(s,s),Y(h,h,s),x(r,h),0}function P(r,n){return R(r,n,br)}function O(r,n){return gr(n,32),P(r,n)}function F(r,n,e){var t=new Uint8Array(32);return R(t,e,n),y(r,vr,t,Br)}function N(r,n,e,t,o,i){var a=new Uint8Array(32);return F(a,o,i),Kr(r,n,e,t,a)}function C(r,n,e,t,o,i){var a=new Uint8Array(32);return F(a,o,i),Tr(r,n,e,t,a)}function M(){var r,n,e,t=0,o=0,i=0,a=0,f=65535;for(e=0;e>>16,i+=n&f,a+=n>>>16;return o+=t>>>16,i+=o>>>16,a+=i>>>16,new sr(i&f|a<<16,t&f|o<<16)}function G(r,n){return new sr(r.hi>>>n,r.lo>>>n|r.hi<<32-n)}function Z(){var r,n=0,e=0;for(r=0;r>>n|r.lo<>>n|r.hi<>>n|r.hi<>>n|r.lo<=128;){for(a=0;a<16;a++)y[a]=t(n,8*a+l);for(a=0;a<80;a++){for(f=0;f<8;f++)c[f]=w[f];for(o=M(w[7],X(w[4]),q(w[4],w[5],w[6]),Yr[a],y[a%16]),c[7]=M(o,V(w[0]),I(w[0],w[1],w[2])),c[3]=M(c[3],o),f=0;f<8;f++)w[(f+1)%8]=c[f];if(a%16===15)for(f=0;f<16;f++)y[f]=M(y[f],y[(f+9)%16],D(y[(f+1)%16]),H(y[(f+14)%16]))}for(a=0;a<8;a++)w[a]=M(w[a],u[a]),u[a]=w[a];l+=128,e-=128}for(a=0;a<8;a++)i(r,8*a,u[a]);return e}function Q(r,n,e){var t,o=new Uint8Array(64),a=new Uint8Array(256),f=e;for(t=0;t<64;t++)o[t]=Lr[t];for(J(o,n,e),e%=128,t=0;t<256;t++)a[t]=0;for(t=0;t=0;--o)t=e[o/8|0]>>(7&o)&1,$(r,n,t),W(n,r),W(r,r),$(r,n,t)}function er(r,n){var e=[hr(),hr(),hr(),hr()];U(e[0],dr),U(e[1],xr),U(e[2],_r),Y(e[3],dr,xr),nr(r,e,n)}function tr(r,n,e){var t,o=new Uint8Array(64),i=[hr(),hr(),hr(),hr()];for(e||gr(n,32),Q(o,n,32),o[0]&=248,o[31]&=127,o[31]|=64,er(i,o),rr(r,i),t=0;t<32;t++)n[t+32]=r[t];return 0}function or(r,n){var e,t,o,i;for(t=63;t>=32;--t){for(e=0,o=t-32,i=t-12;o>8,n[o]-=256*e;n[o]+=e,n[t]=0}for(e=0,o=0;o<32;o++)n[o]+=e-(n[31]>>4)*kr[o],e=n[o]>>8,n[o]&=255;for(o=0;o<32;o++)n[o]-=e*kr[o];for(t=0;t<32;t++)n[t+1]+=n[t]>>8,r[t]=255&n[t]}function ir(r){var n,e=new Float64Array(64);for(n=0;n<64;n++)e[n]=r[n];for(n=0;n<64;n++)r[n]=0;or(r,e)}function ar(r,n,e,t){var o,i,a=new Uint8Array(64),f=new Uint8Array(64),u=new Uint8Array(64),c=new Float64Array(64),w=[hr(),hr(),hr(),hr()];Q(a,t,32),a[0]&=248,a[31]&=127,a[31]|=64;var y=e+64;for(o=0;o>7&&T(r[0],pr,r[0]),Y(r[3],r[0],r[1]),0)}function ur(r,n,e,t){var o,i,a=new Uint8Array(32),f=new Uint8Array(64),c=[hr(),hr(),hr(),hr()],w=[hr(),hr(),hr(),hr()];if(i=-1,e<64)return-1;if(fr(w,t))return-1;for(o=0;o=0},r.sign.keyPair=function(){var r=new Uint8Array(Vr),n=new Uint8Array(Xr);return tr(r,n),{publicKey:r,secretKey:n}},r.sign.keyPair.fromSecretKey=function(r){if(yr(r),r.length!==Xr)throw new Error("bad secret key size");for(var n=new Uint8Array(Vr),e=0;e/dev/null && browserify test/browser/init.js test/*.quick.js | uglifyjs -c -m -o test/browser/_bundle-quick.js 2>/dev/null", - "test": "npm run test-node-all && npm run test-browser", - "bench": "node test/benchmark/bench.js", - "lint": "eslint nacl.js nacl-fast.js test/*.js test/benchmark/*.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/dchest/tweetnacl-js.git" - }, - "keywords": [ - "crypto", - "cryptography", - "curve25519", - "ed25519", - "encrypt", - "hash", - "key", - "nacl", - "poly1305", - "public", - "salsa20", - "signatures" - ], - "author": "TweetNaCl-js contributors", - "license": "Unlicense", - "bugs": { - "url": "https://github.com/dchest/tweetnacl-js/issues" - }, - "homepage": "https://tweetnacl.js.org", - "devDependencies": { - "browserify": "^13.0.0", - "eslint": "^2.2.0", - "faucet": "^0.0.1", - "tap-browser-color": "^0.1.2", - "tape": "^4.4.0", - "tape-run": "^2.1.3", - "tweetnacl-util": "^0.13.3", - "uglify-js": "^2.6.1" - }, - "browser": { - "buffer": false, - "crypto": false - } -} diff --git a/reverse_engineering/node_modules/util-deprecate/History.md b/reverse_engineering/node_modules/util-deprecate/History.md deleted file mode 100644 index acc8675..0000000 --- a/reverse_engineering/node_modules/util-deprecate/History.md +++ /dev/null @@ -1,16 +0,0 @@ - -1.0.2 / 2015-10-07 -================== - - * use try/catch when checking `localStorage` (#3, @kumavis) - -1.0.1 / 2014-11-25 -================== - - * browser: use `console.warn()` for deprecation calls - * browser: more jsdocs - -1.0.0 / 2014-04-30 -================== - - * initial commit diff --git a/reverse_engineering/node_modules/util-deprecate/LICENSE b/reverse_engineering/node_modules/util-deprecate/LICENSE deleted file mode 100644 index 6a60e8c..0000000 --- a/reverse_engineering/node_modules/util-deprecate/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Nathan Rajlich - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/util-deprecate/README.md b/reverse_engineering/node_modules/util-deprecate/README.md deleted file mode 100644 index 75622fa..0000000 --- a/reverse_engineering/node_modules/util-deprecate/README.md +++ /dev/null @@ -1,53 +0,0 @@ -util-deprecate -============== -### The Node.js `util.deprecate()` function with browser support - -In Node.js, this module simply re-exports the `util.deprecate()` function. - -In the web browser (i.e. via browserify), a browser-specific implementation -of the `util.deprecate()` function is used. - - -## API - -A `deprecate()` function is the only thing exposed by this module. - -``` javascript -// setup: -exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); - - -// users see: -foo(); -// foo() is deprecated, use bar() instead -foo(); -foo(); -``` - - -## License - -(The MIT License) - -Copyright (c) 2014 Nathan Rajlich - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/util-deprecate/browser.js b/reverse_engineering/node_modules/util-deprecate/browser.js deleted file mode 100644 index 549ae2f..0000000 --- a/reverse_engineering/node_modules/util-deprecate/browser.js +++ /dev/null @@ -1,67 +0,0 @@ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} diff --git a/reverse_engineering/node_modules/util-deprecate/node.js b/reverse_engineering/node_modules/util-deprecate/node.js deleted file mode 100644 index 5e6fcff..0000000 --- a/reverse_engineering/node_modules/util-deprecate/node.js +++ /dev/null @@ -1,6 +0,0 @@ - -/** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - -module.exports = require('util').deprecate; diff --git a/reverse_engineering/node_modules/util-deprecate/package.json b/reverse_engineering/node_modules/util-deprecate/package.json deleted file mode 100644 index 2e79f89..0000000 --- a/reverse_engineering/node_modules/util-deprecate/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "util-deprecate", - "version": "1.0.2", - "description": "The Node.js `util.deprecate()` function with browser support", - "main": "node.js", - "browser": "browser.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "git://github.com/TooTallNate/util-deprecate.git" - }, - "keywords": [ - "util", - "deprecate", - "browserify", - "browser", - "node" - ], - "author": "Nathan Rajlich (http://n8.io/)", - "license": "MIT", - "bugs": { - "url": "https://github.com/TooTallNate/util-deprecate/issues" - }, - "homepage": "https://github.com/TooTallNate/util-deprecate" -} diff --git a/reverse_engineering/node_modules/which-module/CHANGELOG.md b/reverse_engineering/node_modules/which-module/CHANGELOG.md deleted file mode 100644 index 863d469..0000000 --- a/reverse_engineering/node_modules/which-module/CHANGELOG.md +++ /dev/null @@ -1,26 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -# [2.0.0](https://github.com/nexdrew/which-module/compare/v1.0.0...v2.0.0) (2017-05-01) - - -### Features - -* remove Node < 4 from official testing/support ([#22](https://github.com/nexdrew/which-module/issues/22)) ([ee7aff4](https://github.com/nexdrew/which-module/commit/ee7aff4)) - - -### BREAKING CHANGES - -* Node 0.10 or 0.12 no longer supported, please update to Node 4+ or use which-module@1.0.0 - - - - -# 1.0.0 (2016-06-06) - - -### Features - -* initial code ([08074cd](https://github.com/nexdrew/which-module/commit/08074cd)) diff --git a/reverse_engineering/node_modules/which-module/LICENSE b/reverse_engineering/node_modules/which-module/LICENSE deleted file mode 100644 index ab601b6..0000000 --- a/reverse_engineering/node_modules/which-module/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2016, Contributors - -Permission to use, copy, modify, and/or distribute this software for any purpose -with or without fee is hereby granted, provided that the above copyright notice -and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/which-module/README.md b/reverse_engineering/node_modules/which-module/README.md deleted file mode 100644 index a8c4bf8..0000000 --- a/reverse_engineering/node_modules/which-module/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# which-module - -> Find the module object for something that was require()d - -[![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) -[![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) -[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) - -Find the `module` object in `require.cache` for something that was `require()`d -or `import`ed - essentially a reverse `require()` lookup. - -Useful for libs that want to e.g. lookup a filename for a module or submodule -that it did not `require()` itself. - -## Install and Usage - -``` -npm install --save which-module -``` - -```js -const whichModule = require('which-module') - -console.log(whichModule(require('something'))) -// Module { -// id: '/path/to/project/node_modules/something/index.js', -// exports: [Function], -// parent: ..., -// filename: '/path/to/project/node_modules/something/index.js', -// loaded: true, -// children: [], -// paths: [ '/path/to/project/node_modules/something/node_modules', -// '/path/to/project/node_modules', -// '/path/to/node_modules', -// '/path/node_modules', -// '/node_modules' ] } -``` - -## API - -### `whichModule(exported)` - -Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), -if any, that represents the given argument in the `require.cache`. - -`exported` can be anything that was previously `require()`d or `import`ed as a -module, submodule, or dependency - which means `exported` is identical to the -`module.exports` returned by this method. - -If `exported` did not come from the `exports` of a `module` in `require.cache`, -then this method returns `null`. - -## License - -ISC © Contributors diff --git a/reverse_engineering/node_modules/which-module/index.js b/reverse_engineering/node_modules/which-module/index.js deleted file mode 100644 index 45559b7..0000000 --- a/reverse_engineering/node_modules/which-module/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict' - -module.exports = function whichModule (exported) { - for (var i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { - mod = require.cache[files[i]] - if (mod.exports === exported) return mod - } - return null -} diff --git a/reverse_engineering/node_modules/which-module/package.json b/reverse_engineering/node_modules/which-module/package.json deleted file mode 100644 index 3566aff..0000000 --- a/reverse_engineering/node_modules/which-module/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "which-module", - "version": "2.0.0", - "description": "Find the module object for something that was require()d", - "main": "index.js", - "scripts": { - "pretest": "standard", - "test": "nyc ava", - "coverage": "nyc report --reporter=text-lcov | coveralls", - "release": "standard-version" - }, - "files": [ - "index.js" - ], - "repository": { - "type": "git", - "url": "git+https://github.com/nexdrew/which-module.git" - }, - "keywords": [ - "which", - "module", - "exports", - "filename", - "require", - "reverse", - "lookup" - ], - "author": "nexdrew", - "license": "ISC", - "bugs": { - "url": "https://github.com/nexdrew/which-module/issues" - }, - "homepage": "https://github.com/nexdrew/which-module#readme", - "devDependencies": { - "ava": "^0.19.1", - "coveralls": "^2.13.1", - "nyc": "^10.3.0", - "standard": "^10.0.2", - "standard-version": "^4.0.0" - } -} diff --git a/reverse_engineering/node_modules/wrap-ansi/index.js b/reverse_engineering/node_modules/wrap-ansi/index.js deleted file mode 100755 index a6e5443..0000000 --- a/reverse_engineering/node_modules/wrap-ansi/index.js +++ /dev/null @@ -1,186 +0,0 @@ -'use strict'; -const stringWidth = require('string-width'); -const stripAnsi = require('strip-ansi'); -const ansiStyles = require('ansi-styles'); - -const ESCAPES = new Set([ - '\u001B', - '\u009B' -]); - -const END_CODE = 39; - -const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; - -// Calculate the length of words split on ' ', ignoring -// the extra characters added by ansi escape codes -const wordLengths = string => string.split(' ').map(character => stringWidth(character)); - -// Wrap a long word across multiple rows -// Ansi escape codes do not count towards length -const wrapWord = (rows, word, columns) => { - const characters = [...word]; - - let isInsideEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); - - for (const [index, character] of characters.entries()) { - const characterLength = stringWidth(character); - - if (visible + characterLength <= columns) { - rows[rows.length - 1] += character; - } else { - rows.push(character); - visible = 0; - } - - if (ESCAPES.has(character)) { - isInsideEscape = true; - } else if (isInsideEscape && character === 'm') { - isInsideEscape = false; - continue; - } - - if (isInsideEscape) { - continue; - } - - visible += characterLength; - - if (visible === columns && index < characters.length - 1) { - rows.push(''); - visible = 0; - } - } - - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } -}; - -// Trims spaces from a string ignoring invisible sequences -const stringVisibleTrimSpacesRight = str => { - const words = str.split(' '); - let last = words.length; - - while (last > 0) { - if (stringWidth(words[last - 1]) > 0) { - break; - } - - last--; - } - - if (last === words.length) { - return str; - } - - return words.slice(0, last).join(' ') + words.slice(last).join(''); -}; - -// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode -// -// 'hard' will never allow a string to take up more than columns characters -// -// 'soft' allows long words to expand past the column length -const exec = (string, columns, options = {}) => { - if (options.trim !== false && string.trim() === '') { - return ''; - } - - let pre = ''; - let ret = ''; - let escapeCode; - - const lengths = wordLengths(string); - let rows = ['']; - - for (const [index, word] of string.split(' ').entries()) { - if (options.trim !== false) { - rows[rows.length - 1] = rows[rows.length - 1].trimLeft(); - } - - let rowLength = stringWidth(rows[rows.length - 1]); - - if (index !== 0) { - if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } - - if (rowLength > 0 || options.trim === false) { - rows[rows.length - 1] += ' '; - rowLength++; - } - } - - // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' - if (options.hard && lengths[index] > columns) { - const remainingColumns = (columns - rowLength); - const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); - const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); - if (breaksStartingNextLine < breaksStartingThisLine) { - rows.push(''); - } - - wrapWord(rows, word, columns); - continue; - } - - if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { - if (options.wordWrap === false && rowLength < columns) { - wrapWord(rows, word, columns); - continue; - } - - rows.push(''); - } - - if (rowLength + lengths[index] > columns && options.wordWrap === false) { - wrapWord(rows, word, columns); - continue; - } - - rows[rows.length - 1] += word; - } - - if (options.trim !== false) { - rows = rows.map(stringVisibleTrimSpacesRight); - } - - pre = rows.join('\n'); - - for (const [index, character] of [...pre].entries()) { - ret += character; - - if (ESCAPES.has(character)) { - const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4))); - escapeCode = code === END_CODE ? null : code; - } - - const code = ansiStyles.codes.get(Number(escapeCode)); - - if (escapeCode && code) { - if (pre[index + 1] === '\n') { - ret += wrapAnsi(code); - } else if (character === '\n') { - ret += wrapAnsi(escapeCode); - } - } - } - - return ret; -}; - -// For each newline, invoke the method separately -module.exports = (string, columns, options) => { - return String(string) - .normalize() - .replace(/\r\n/g, '\n') - .split('\n') - .map(line => exec(line, columns, options)) - .join('\n'); -}; diff --git a/reverse_engineering/node_modules/wrap-ansi/license b/reverse_engineering/node_modules/wrap-ansi/license deleted file mode 100644 index e7af2f7..0000000 --- a/reverse_engineering/node_modules/wrap-ansi/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/wrap-ansi/package.json b/reverse_engineering/node_modules/wrap-ansi/package.json deleted file mode 100644 index 1d57c9f..0000000 --- a/reverse_engineering/node_modules/wrap-ansi/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "wrap-ansi", - "version": "6.2.0", - "description": "Wordwrap a string with ANSI escape codes", - "license": "MIT", - "repository": "chalk/wrap-ansi", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && nyc ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "wrap", - "break", - "wordwrap", - "wordbreak", - "linewrap", - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "devDependencies": { - "ava": "^2.1.0", - "chalk": "^2.4.2", - "coveralls": "^3.0.3", - "has-ansi": "^3.0.0", - "nyc": "^14.1.1", - "xo": "^0.24.0" - } -} diff --git a/reverse_engineering/node_modules/wrap-ansi/readme.md b/reverse_engineering/node_modules/wrap-ansi/readme.md deleted file mode 100644 index d81a4d5..0000000 --- a/reverse_engineering/node_modules/wrap-ansi/readme.md +++ /dev/null @@ -1,97 +0,0 @@ -# wrap-ansi [![Build Status](https://travis-ci.org/chalk/wrap-ansi.svg?branch=master)](https://travis-ci.org/chalk/wrap-ansi) [![Coverage Status](https://coveralls.io/repos/github/chalk/wrap-ansi/badge.svg?branch=master)](https://coveralls.io/github/chalk/wrap-ansi?branch=master) - -> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) - - -## Install - -``` -$ npm install wrap-ansi -``` - - -## Usage - -```js -const chalk = require('chalk'); -const wrapAnsi = require('wrap-ansi'); - -const input = 'The quick brown ' + chalk.red('fox jumped over ') + - 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); - -console.log(wrapAnsi(input, 20)); -``` - - - - -## API - -### wrapAnsi(string, columns, options?) - -Wrap words to the specified column width. - -#### string - -Type: `string` - -String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. - -#### columns - -Type: `number` - -Number of columns to wrap the text to. - -#### options - -Type: `object` - -##### hard - -Type: `boolean`
-Default: `false` - -By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. - -##### wordWrap - -Type: `boolean`
-Default: `true` - -By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. - -##### trim - -Type: `boolean`
-Default: `true` - -Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. - - -## Related - -- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes -- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal -- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right -- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. - - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) -- [Benjamin Coe](https://github.com/bcoe) - - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/reverse_engineering/node_modules/y18n/CHANGELOG.md b/reverse_engineering/node_modules/y18n/CHANGELOG.md deleted file mode 100644 index b7e86e9..0000000 --- a/reverse_engineering/node_modules/y18n/CHANGELOG.md +++ /dev/null @@ -1,35 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -### [4.0.3](https://www.github.com/yargs/y18n/compare/y18n-v4.0.2...y18n-v4.0.3) (2021-04-07) - - -### Bug Fixes - -* **release:** 4.x.x should not enforce Node 10 ([#126](https://www.github.com/yargs/y18n/issues/126)) ([1e21a53](https://www.github.com/yargs/y18n/commit/1e21a536e9135d8403a47be88922157a706b7cde)) - -### 4.0.1 (2020-11-30) - -### Bug Fixes - -* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/a9ac604abf756dec9687be3843e2c93bfe581f25)) - - -# [4.0.0](https://github.com/yargs/y18n/compare/v3.2.1...v4.0.0) (2017-10-10) - - -### Bug Fixes - -* allow support for falsy values like 0 in tagged literal ([#45](https://github.com/yargs/y18n/issues/45)) ([c926123](https://github.com/yargs/y18n/commit/c926123)) - - -### Features - -* **__:** added tagged template literal support ([#44](https://github.com/yargs/y18n/issues/44)) ([0598daf](https://github.com/yargs/y18n/commit/0598daf)) - - -### BREAKING CHANGES - -* **__:** dropping Node 0.10/Node 0.12 support diff --git a/reverse_engineering/node_modules/y18n/LICENSE b/reverse_engineering/node_modules/y18n/LICENSE deleted file mode 100644 index 3c157f0..0000000 --- a/reverse_engineering/node_modules/y18n/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2015, Contributors - -Permission to use, copy, modify, and/or distribute this software for any purpose -with or without fee is hereby granted, provided that the above copyright notice -and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/y18n/README.md b/reverse_engineering/node_modules/y18n/README.md deleted file mode 100644 index 826474f..0000000 --- a/reverse_engineering/node_modules/y18n/README.md +++ /dev/null @@ -1,109 +0,0 @@ -# y18n - -[![Build Status][travis-image]][travis-url] -[![Coverage Status][coveralls-image]][coveralls-url] -[![NPM version][npm-image]][npm-url] -[![js-standard-style][standard-image]][standard-url] -[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) - -The bare-bones internationalization library used by yargs. - -Inspired by [i18n](https://www.npmjs.com/package/i18n). - -## Examples - -_simple string translation:_ - -```js -var __ = require('y18n').__ - -console.log(__('my awesome string %s', 'foo')) -``` - -output: - -`my awesome string foo` - -_using tagged template literals_ - -```js -var __ = require('y18n').__ -var str = 'foo' - -console.log(__`my awesome string ${str}`) -``` - -output: - -`my awesome string foo` - -_pluralization support:_ - -```js -var __n = require('y18n').__n - -console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) -``` - -output: - -`2 fishes foo` - -## JSON Language Files - -The JSON language files should be stored in a `./locales` folder. -File names correspond to locales, e.g., `en.json`, `pirate.json`. - -When strings are observed for the first time they will be -added to the JSON file corresponding to the current locale. - -## Methods - -### require('y18n')(config) - -Create an instance of y18n with the config provided, options include: - -* `directory`: the locale directory, default `./locales`. -* `updateFiles`: should newly observed strings be updated in file, default `true`. -* `locale`: what locale should be used. -* `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) - be allowed if a file matching the locale does not exist (e.g. `en_US.json`), - default `true`. - -### y18n.\_\_(str, arg, arg, arg) - -Print a localized string, `%s` will be replaced with `arg`s. - -This function can also be used as a tag for a template literal. You can use it -like this: __`hello ${'world'}`. This will be equivalent to -`__('hello %s', 'world')`. - -### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) - -Print a localized string with appropriate pluralization. If `%d` is provided -in the string, the `count` will replace this placeholder. - -### y18n.setLocale(str) - -Set the current locale being used. - -### y18n.getLocale() - -What locale is currently being used? - -### y18n.updateLocale(obj) - -Update the current locale with the key value pairs in `obj`. - -## License - -ISC - -[travis-url]: https://travis-ci.org/yargs/y18n -[travis-image]: https://img.shields.io/travis/yargs/y18n.svg -[coveralls-url]: https://coveralls.io/github/yargs/y18n -[coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg -[npm-url]: https://npmjs.org/package/y18n -[npm-image]: https://img.shields.io/npm/v/y18n.svg -[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg -[standard-url]: https://github.com/feross/standard diff --git a/reverse_engineering/node_modules/y18n/index.js b/reverse_engineering/node_modules/y18n/index.js deleted file mode 100644 index 727362a..0000000 --- a/reverse_engineering/node_modules/y18n/index.js +++ /dev/null @@ -1,188 +0,0 @@ -var fs = require('fs') -var path = require('path') -var util = require('util') - -function Y18N (opts) { - // configurable options. - opts = opts || {} - this.directory = opts.directory || './locales' - this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true - this.locale = opts.locale || 'en' - this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true - - // internal stuff. - this.cache = Object.create(null) - this.writeQueue = [] -} - -Y18N.prototype.__ = function () { - if (typeof arguments[0] !== 'string') { - return this._taggedLiteral.apply(this, arguments) - } - var args = Array.prototype.slice.call(arguments) - var str = args.shift() - var cb = function () {} // start with noop. - - if (typeof args[args.length - 1] === 'function') cb = args.pop() - cb = cb || function () {} // noop. - - if (!this.cache[this.locale]) this._readLocaleFile() - - // we've observed a new string, update the language file. - if (!this.cache[this.locale][str] && this.updateFiles) { - this.cache[this.locale][str] = str - - // include the current directory and locale, - // since these values could change before the - // write is performed. - this._enqueueWrite([this.directory, this.locale, cb]) - } else { - cb() - } - - return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args)) -} - -Y18N.prototype._taggedLiteral = function (parts) { - var args = arguments - var str = '' - parts.forEach(function (part, i) { - var arg = args[i + 1] - str += part - if (typeof arg !== 'undefined') { - str += '%s' - } - }) - return this.__.apply(null, [str].concat([].slice.call(arguments, 1))) -} - -Y18N.prototype._enqueueWrite = function (work) { - this.writeQueue.push(work) - if (this.writeQueue.length === 1) this._processWriteQueue() -} - -Y18N.prototype._processWriteQueue = function () { - var _this = this - var work = this.writeQueue[0] - - // destructure the enqueued work. - var directory = work[0] - var locale = work[1] - var cb = work[2] - - var languageFile = this._resolveLocaleFile(directory, locale) - var serializedLocale = JSON.stringify(this.cache[locale], null, 2) - - fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { - _this.writeQueue.shift() - if (_this.writeQueue.length > 0) _this._processWriteQueue() - cb(err) - }) -} - -Y18N.prototype._readLocaleFile = function () { - var localeLookup = {} - var languageFile = this._resolveLocaleFile(this.directory, this.locale) - - try { - localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8')) - } catch (err) { - if (err instanceof SyntaxError) { - err.message = 'syntax error in ' + languageFile - } - - if (err.code === 'ENOENT') localeLookup = {} - else throw err - } - - this.cache[this.locale] = localeLookup -} - -Y18N.prototype._resolveLocaleFile = function (directory, locale) { - var file = path.resolve(directory, './', locale + '.json') - if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { - // attempt fallback to language only - var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json') - if (this._fileExistsSync(languageFile)) file = languageFile - } - return file -} - -// this only exists because fs.existsSync() "will be deprecated" -// see https://nodejs.org/api/fs.html#fs_fs_existssync_path -Y18N.prototype._fileExistsSync = function (file) { - try { - return fs.statSync(file).isFile() - } catch (err) { - return false - } -} - -Y18N.prototype.__n = function () { - var args = Array.prototype.slice.call(arguments) - var singular = args.shift() - var plural = args.shift() - var quantity = args.shift() - - var cb = function () {} // start with noop. - if (typeof args[args.length - 1] === 'function') cb = args.pop() - - if (!this.cache[this.locale]) this._readLocaleFile() - - var str = quantity === 1 ? singular : plural - if (this.cache[this.locale][singular]) { - str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other'] - } - - // we've observed a new string, update the language file. - if (!this.cache[this.locale][singular] && this.updateFiles) { - this.cache[this.locale][singular] = { - one: singular, - other: plural - } - - // include the current directory and locale, - // since these values could change before the - // write is performed. - this._enqueueWrite([this.directory, this.locale, cb]) - } else { - cb() - } - - // if a %d placeholder is provided, add quantity - // to the arguments expanded by util.format. - var values = [str] - if (~str.indexOf('%d')) values.push(quantity) - - return util.format.apply(util, values.concat(args)) -} - -Y18N.prototype.setLocale = function (locale) { - this.locale = locale -} - -Y18N.prototype.getLocale = function () { - return this.locale -} - -Y18N.prototype.updateLocale = function (obj) { - if (!this.cache[this.locale]) this._readLocaleFile() - - for (var key in obj) { - this.cache[this.locale][key] = obj[key] - } -} - -module.exports = function (opts) { - var y18n = new Y18N(opts) - - // bind all functions to y18n, so that - // they can be used in isolation. - for (var key in y18n) { - if (typeof y18n[key] === 'function') { - y18n[key] = y18n[key].bind(y18n) - } - } - - return y18n -} diff --git a/reverse_engineering/node_modules/y18n/package.json b/reverse_engineering/node_modules/y18n/package.json deleted file mode 100644 index 6f08863..0000000 --- a/reverse_engineering/node_modules/y18n/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "y18n", - "version": "4.0.3", - "description": "the bare-bones internationalization library used by yargs", - "main": "index.js", - "scripts": { - "pretest": "standard", - "test": "nyc mocha", - "coverage": "nyc report --reporter=text-lcov | coveralls", - "release": "standard-version" - }, - "repository": { - "type": "git", - "url": "git@github.com:yargs/y18n.git" - }, - "files": [ - "index.js" - ], - "keywords": [ - "i18n", - "internationalization", - "yargs" - ], - "author": "Ben Coe ", - "license": "ISC", - "bugs": { - "url": "https://github.com/yargs/y18n/issues" - }, - "homepage": "https://github.com/yargs/y18n", - "devDependencies": { - "chai": "^4.0.1", - "coveralls": "^3.0.0", - "mocha": "^4.0.1", - "nyc": "^11.0.1", - "rimraf": "^2.5.0", - "standard": "^10.0.0-beta.0", - "standard-version": "^4.2.0" - } -} diff --git a/reverse_engineering/node_modules/yargs-parser/CHANGELOG.md b/reverse_engineering/node_modules/yargs-parser/CHANGELOG.md deleted file mode 100644 index d91dc51..0000000 --- a/reverse_engineering/node_modules/yargs-parser/CHANGELOG.md +++ /dev/null @@ -1,601 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -### [18.1.3](https://www.github.com/yargs/yargs-parser/compare/v18.1.2...v18.1.3) (2020-04-16) - - -### Bug Fixes - -* **setArg:** options using camel-case and dot-notation populated twice ([#268](https://www.github.com/yargs/yargs-parser/issues/268)) ([f7e15b9](https://www.github.com/yargs/yargs-parser/commit/f7e15b9800900b9856acac1a830a5f35847be73e)) - -### [18.1.2](https://www.github.com/yargs/yargs-parser/compare/v18.1.1...v18.1.2) (2020-03-26) - - -### Bug Fixes - -* **array, nargs:** support -o=--value and --option=--value format ([#262](https://www.github.com/yargs/yargs-parser/issues/262)) ([41d3f81](https://www.github.com/yargs/yargs-parser/commit/41d3f8139e116706b28de9b0de3433feb08d2f13)) - -### [18.1.1](https://www.github.com/yargs/yargs-parser/compare/v18.1.0...v18.1.1) (2020-03-16) - - -### Bug Fixes - -* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential -prototype pollution vulnerability. This was reported by the Snyk Security Research Team.([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2)) - -## [18.1.0](https://www.github.com/yargs/yargs-parser/compare/v18.0.0...v18.1.0) (2020-03-07) - - -### Features - -* introduce single-digit boolean aliases ([#255](https://www.github.com/yargs/yargs-parser/issues/255)) ([9c60265](https://www.github.com/yargs/yargs-parser/commit/9c60265fd7a03cb98e6df3e32c8c5e7508d9f56f)) - -## [18.0.0](https://www.github.com/yargs/yargs-parser/compare/v17.1.0...v18.0.0) (2020-03-02) - - -### ⚠ BREAKING CHANGES - -* the narg count is now enforced when parsing arrays. - -### Features - -* NaN can now be provided as a value for nargs, indicating "at least" one value is expected for array ([#251](https://www.github.com/yargs/yargs-parser/issues/251)) ([9db4be8](https://www.github.com/yargs/yargs-parser/commit/9db4be81417a2c7097128db34d86fe70ef4af70c)) - -## [17.1.0](https://www.github.com/yargs/yargs-parser/compare/v17.0.1...v17.1.0) (2020-03-01) - - -### Features - -* introduce greedy-arrays config, for specifying whether arrays consume multiple positionals ([#249](https://www.github.com/yargs/yargs-parser/issues/249)) ([60e880a](https://www.github.com/yargs/yargs-parser/commit/60e880a837046314d89fa4725f923837fd33a9eb)) - -### [17.0.1](https://www.github.com/yargs/yargs-parser/compare/v17.0.0...v17.0.1) (2020-02-29) - - -### Bug Fixes - -* normalized keys were not enumerable ([#247](https://www.github.com/yargs/yargs-parser/issues/247)) ([57119f9](https://www.github.com/yargs/yargs-parser/commit/57119f9f17cf27499bd95e61c2f72d18314f11ba)) - -## [17.0.0](https://www.github.com/yargs/yargs-parser/compare/v16.1.0...v17.0.0) (2020-02-10) - - -### ⚠ BREAKING CHANGES - -* this reverts parsing behavior of booleans to that of yargs@14 -* objects used during parsing are now created with a null -prototype. There may be some scenarios where this change in behavior -leaks externally. - -### Features - -* boolean arguments will not be collected into an implicit array ([#236](https://www.github.com/yargs/yargs-parser/issues/236)) ([34c4e19](https://www.github.com/yargs/yargs-parser/commit/34c4e19bae4e7af63e3cb6fa654a97ed476e5eb5)) -* introduce nargs-eats-options config option ([#246](https://www.github.com/yargs/yargs-parser/issues/246)) ([d50822a](https://www.github.com/yargs/yargs-parser/commit/d50822ac10e1b05f2e9643671ca131ac251b6732)) - - -### Bug Fixes - -* address bugs with "uknown-options-as-args" ([bc023e3](https://www.github.com/yargs/yargs-parser/commit/bc023e3b13e20a118353f9507d1c999bf388a346)) -* array should take precedence over nargs, but enforce nargs ([#243](https://www.github.com/yargs/yargs-parser/issues/243)) ([4cbc188](https://www.github.com/yargs/yargs-parser/commit/4cbc188b7abb2249529a19c090338debdad2fe6c)) -* support keys that collide with object prototypes ([#234](https://www.github.com/yargs/yargs-parser/issues/234)) ([1587b6d](https://www.github.com/yargs/yargs-parser/commit/1587b6d91db853a9109f1be6b209077993fee4de)) -* unknown options terminated with digits now handled by unknown-options-as-args ([#238](https://www.github.com/yargs/yargs-parser/issues/238)) ([d36cdfa](https://www.github.com/yargs/yargs-parser/commit/d36cdfa854254d7c7e0fe1d583818332ac46c2a5)) - -## [16.1.0](https://www.github.com/yargs/yargs-parser/compare/v16.0.0...v16.1.0) (2019-11-01) - - -### ⚠ BREAKING CHANGES - -* populate error if incompatible narg/count or array/count options are used (#191) - -### Features - -* options that have had their default value used are now tracked ([#211](https://www.github.com/yargs/yargs-parser/issues/211)) ([a525234](https://www.github.com/yargs/yargs-parser/commit/a525234558c847deedd73f8792e0a3b77b26e2c0)) -* populate error if incompatible narg/count or array/count options are used ([#191](https://www.github.com/yargs/yargs-parser/issues/191)) ([84a401f](https://www.github.com/yargs/yargs-parser/commit/84a401f0fa3095e0a19661670d1570d0c3b9d3c9)) - - -### Reverts - -* revert 16.0.0 CHANGELOG entry ([920320a](https://www.github.com/yargs/yargs-parser/commit/920320ad9861bbfd58eda39221ae211540fc1daf)) - -## [15.0.0](https://github.com/yargs/yargs-parser/compare/v14.0.0...v15.0.0) (2019-10-07) - - -### Features - -* rework `collect-unknown-options` into `unknown-options-as-args`, providing more comprehensive functionality ([ef771ca](https://github.com/yargs/yargs-parser/commit/ef771ca)) - - -### BREAKING CHANGES - -* rework `collect-unknown-options` into `unknown-options-as-args`, providing more comprehensive functionality - - - -## [14.0.0](https://github.com/yargs/yargs-parser/compare/v13.1.1...v14.0.0) (2019-09-06) - - -### Bug Fixes - -* boolean arrays with default values ([#185](https://github.com/yargs/yargs-parser/issues/185)) ([7d42572](https://github.com/yargs/yargs-parser/commit/7d42572)) -* boolean now behaves the same as other array types ([#184](https://github.com/yargs/yargs-parser/issues/184)) ([17ca3bd](https://github.com/yargs/yargs-parser/commit/17ca3bd)) -* eatNargs() for 'opt.narg === 0' and boolean typed options ([#188](https://github.com/yargs/yargs-parser/issues/188)) ([c5a1db0](https://github.com/yargs/yargs-parser/commit/c5a1db0)) -* maybeCoerceNumber now takes precedence over coerce return value ([#182](https://github.com/yargs/yargs-parser/issues/182)) ([2f26436](https://github.com/yargs/yargs-parser/commit/2f26436)) -* take into account aliases when appending arrays from config object ([#199](https://github.com/yargs/yargs-parser/issues/199)) ([f8a2d3f](https://github.com/yargs/yargs-parser/commit/f8a2d3f)) - - -### Features - -* add configuration option to "collect-unknown-options" ([#181](https://github.com/yargs/yargs-parser/issues/181)) ([7909cc4](https://github.com/yargs/yargs-parser/commit/7909cc4)) -* maybeCoerceNumber() now takes into account arrays ([#187](https://github.com/yargs/yargs-parser/issues/187)) ([31c204b](https://github.com/yargs/yargs-parser/commit/31c204b)) - - -### BREAKING CHANGES - -* unless "parse-numbers" is set to "false", arrays of numeric strings are now parsed as numbers, rather than strings. -* we have dropped the broken "defaulted" functionality; we would like to revisit adding this in the future. -* maybeCoerceNumber now takes precedence over coerce return value (#182) - - - -### [13.1.1](https://www.github.com/yargs/yargs-parser/compare/v13.1.0...v13.1.1) (2019-06-10) - - -### Bug Fixes - -* convert values to strings when tokenizing ([#167](https://www.github.com/yargs/yargs-parser/issues/167)) ([57b7883](https://www.github.com/yargs/yargs-parser/commit/57b7883)) -* nargs should allow duplicates when duplicate-arguments-array=false ([#164](https://www.github.com/yargs/yargs-parser/issues/164)) ([47ccb0b](https://www.github.com/yargs/yargs-parser/commit/47ccb0b)) -* should populate "_" when given config with "short-option-groups" false ([#179](https://www.github.com/yargs/yargs-parser/issues/179)) ([6055974](https://www.github.com/yargs/yargs-parser/commit/6055974)) - -## [13.1.0](https://github.com/yargs/yargs-parser/compare/v13.0.0...v13.1.0) (2019-05-05) - - -### Features - -* add `strip-aliased` and `strip-dashed` configuration options. ([#172](https://github.com/yargs/yargs-parser/issues/172)) ([a3936aa](https://github.com/yargs/yargs-parser/commit/a3936aa)) -* support boolean which do not consume next argument. ([#171](https://github.com/yargs/yargs-parser/issues/171)) ([0ae7fcb](https://github.com/yargs/yargs-parser/commit/0ae7fcb)) - - - - -# [13.0.0](https://github.com/yargs/yargs-parser/compare/v12.0.0...v13.0.0) (2019-02-02) - - -### Features - -* don't coerce number from string with leading '0' or '+' ([#158](https://github.com/yargs/yargs-parser/issues/158)) ([18d0fd5](https://github.com/yargs/yargs-parser/commit/18d0fd5)) - - -### BREAKING CHANGES - -* options with leading '+' or '0' now parse as strings - - - - -# [12.0.0](https://github.com/yargs/yargs-parser/compare/v11.1.1...v12.0.0) (2019-01-29) - - -### Bug Fixes - -* better handling of quoted strings ([#153](https://github.com/yargs/yargs-parser/issues/153)) ([2fb71b2](https://github.com/yargs/yargs-parser/commit/2fb71b2)) - - -### Features - -* default value is now used if no right-hand value provided for numbers/strings ([#156](https://github.com/yargs/yargs-parser/issues/156)) ([5a7c46a](https://github.com/yargs/yargs-parser/commit/5a7c46a)) - - -### BREAKING CHANGES - -* a flag with no right-hand value no longer populates defaulted options with `undefined`. -* quotes at beginning and endings of strings are not removed during parsing. - - - - -## [11.1.1](https://github.com/yargs/yargs-parser/compare/v11.1.0...v11.1.1) (2018-11-19) - - -### Bug Fixes - -* ensure empty string is added into argv._ ([#140](https://github.com/yargs/yargs-parser/issues/140)) ([79cda98](https://github.com/yargs/yargs-parser/commit/79cda98)) - - -### Reverts - -* make requiresArg work in conjunction with arrays ([#136](https://github.com/yargs/yargs-parser/issues/136)) ([f4a3063](https://github.com/yargs/yargs-parser/commit/f4a3063)) - - - - -# [11.1.0](https://github.com/yargs/yargs-parser/compare/v11.0.0...v11.1.0) (2018-11-10) - - -### Bug Fixes - -* handling of one char alias ([#139](https://github.com/yargs/yargs-parser/issues/139)) ([ee56e31](https://github.com/yargs/yargs-parser/commit/ee56e31)) - - -### Features - -* add halt-at-non-option configuration option ([#130](https://github.com/yargs/yargs-parser/issues/130)) ([a849fce](https://github.com/yargs/yargs-parser/commit/a849fce)) - - - - -# [11.0.0](https://github.com/yargs/yargs-parser/compare/v10.1.0...v11.0.0) (2018-10-06) - - -### Bug Fixes - -* flatten-duplicate-arrays:false for more than 2 arrays ([#128](https://github.com/yargs/yargs-parser/issues/128)) ([2bc395f](https://github.com/yargs/yargs-parser/commit/2bc395f)) -* hyphenated flags combined with dot notation broke parsing ([#131](https://github.com/yargs/yargs-parser/issues/131)) ([dc788da](https://github.com/yargs/yargs-parser/commit/dc788da)) -* make requiresArg work in conjunction with arrays ([#136](https://github.com/yargs/yargs-parser/issues/136)) ([77ae1d4](https://github.com/yargs/yargs-parser/commit/77ae1d4)) - - -### Chores - -* update dependencies ([6dc42a1](https://github.com/yargs/yargs-parser/commit/6dc42a1)) - - -### Features - -* also add camelCase array options ([#125](https://github.com/yargs/yargs-parser/issues/125)) ([08c0117](https://github.com/yargs/yargs-parser/commit/08c0117)) -* array.type can now be provided, supporting coercion ([#132](https://github.com/yargs/yargs-parser/issues/132)) ([4b8cfce](https://github.com/yargs/yargs-parser/commit/4b8cfce)) - - -### BREAKING CHANGES - -* drops Node 4 support -* the argv object is now populated differently (correctly) when hyphens and dot notation are used in conjunction. - - - - -# [10.1.0](https://github.com/yargs/yargs-parser/compare/v10.0.0...v10.1.0) (2018-06-29) - - -### Features - -* add `set-placeholder-key` configuration ([#123](https://github.com/yargs/yargs-parser/issues/123)) ([19386ee](https://github.com/yargs/yargs-parser/commit/19386ee)) - - - - -# [10.0.0](https://github.com/yargs/yargs-parser/compare/v9.0.2...v10.0.0) (2018-04-04) - - -### Bug Fixes - -* do not set boolean flags if not defined in `argv` ([#119](https://github.com/yargs/yargs-parser/issues/119)) ([f6e6599](https://github.com/yargs/yargs-parser/commit/f6e6599)) - - -### BREAKING CHANGES - -* `boolean` flags defined without a `default` value will now behave like other option type and won't be set in the parsed results when the user doesn't set the corresponding CLI arg. - -Previous behavior: -```js -var parse = require('yargs-parser'); - -parse('--flag', {boolean: ['flag']}); -// => { _: [], flag: true } - -parse('--no-flag', {boolean: ['flag']}); -// => { _: [], flag: false } - -parse('', {boolean: ['flag']}); -// => { _: [], flag: false } -``` - -New behavior: -```js -var parse = require('yargs-parser'); - -parse('--flag', {boolean: ['flag']}); -// => { _: [], flag: true } - -parse('--no-flag', {boolean: ['flag']}); -// => { _: [], flag: false } - -parse('', {boolean: ['flag']}); -// => { _: [] } => flag not set similarly to other option type -``` - - - - -## [9.0.2](https://github.com/yargs/yargs-parser/compare/v9.0.1...v9.0.2) (2018-01-20) - - -### Bug Fixes - -* nargs was still aggressively consuming too many arguments ([9b28aad](https://github.com/yargs/yargs-parser/commit/9b28aad)) - - - - -## [9.0.1](https://github.com/yargs/yargs-parser/compare/v9.0.0...v9.0.1) (2018-01-20) - - -### Bug Fixes - -* nargs was consuming too many arguments ([4fef206](https://github.com/yargs/yargs-parser/commit/4fef206)) - - - - -# [9.0.0](https://github.com/yargs/yargs-parser/compare/v8.1.0...v9.0.0) (2018-01-20) - - -### Features - -* narg arguments no longer consume flag arguments ([#114](https://github.com/yargs/yargs-parser/issues/114)) ([60bb9b3](https://github.com/yargs/yargs-parser/commit/60bb9b3)) - - -### BREAKING CHANGES - -* arguments of form --foo, -abc, will no longer be consumed by nargs - - - - -# [8.1.0](https://github.com/yargs/yargs-parser/compare/v8.0.0...v8.1.0) (2017-12-20) - - -### Bug Fixes - -* allow null config values ([#108](https://github.com/yargs/yargs-parser/issues/108)) ([d8b14f9](https://github.com/yargs/yargs-parser/commit/d8b14f9)) -* ensure consistent parsing of dot-notation arguments ([#102](https://github.com/yargs/yargs-parser/issues/102)) ([c9bd79c](https://github.com/yargs/yargs-parser/commit/c9bd79c)) -* implement [@antoniom](https://github.com/antoniom)'s fix for camel-case expansion ([3087e1d](https://github.com/yargs/yargs-parser/commit/3087e1d)) -* only run coercion functions once, despite aliases. ([#76](https://github.com/yargs/yargs-parser/issues/76)) ([#103](https://github.com/yargs/yargs-parser/issues/103)) ([507aaef](https://github.com/yargs/yargs-parser/commit/507aaef)) -* scientific notation circumvented bounds check ([#110](https://github.com/yargs/yargs-parser/issues/110)) ([3571f57](https://github.com/yargs/yargs-parser/commit/3571f57)) -* tokenizer should ignore spaces at the beginning of the argString ([#106](https://github.com/yargs/yargs-parser/issues/106)) ([f34ead9](https://github.com/yargs/yargs-parser/commit/f34ead9)) - - -### Features - -* make combining arrays a configurable option ([#111](https://github.com/yargs/yargs-parser/issues/111)) ([c8bf536](https://github.com/yargs/yargs-parser/commit/c8bf536)) -* merge array from arguments with array from config ([#83](https://github.com/yargs/yargs-parser/issues/83)) ([806ddd6](https://github.com/yargs/yargs-parser/commit/806ddd6)) - - - - -# [8.0.0](https://github.com/yargs/yargs-parser/compare/v7.0.0...v8.0.0) (2017-10-05) - - -### Bug Fixes - -* Ignore multiple spaces between arguments. ([#100](https://github.com/yargs/yargs-parser/issues/100)) ([d137227](https://github.com/yargs/yargs-parser/commit/d137227)) - - -### Features - -* allow configuration of prefix for boolean negation ([#94](https://github.com/yargs/yargs-parser/issues/94)) ([00bde7d](https://github.com/yargs/yargs-parser/commit/00bde7d)) -* reworking how numbers are parsed ([#104](https://github.com/yargs/yargs-parser/issues/104)) ([fba00eb](https://github.com/yargs/yargs-parser/commit/fba00eb)) - - -### BREAKING CHANGES - -* strings that fail `Number.isSafeInteger()` are no longer coerced into numbers. - - - - -# [7.0.0](https://github.com/yargs/yargs-parser/compare/v6.0.1...v7.0.0) (2017-05-02) - - -### Chores - -* revert populate-- logic ([#91](https://github.com/yargs/yargs-parser/issues/91)) ([6003e6d](https://github.com/yargs/yargs-parser/commit/6003e6d)) - - -### BREAKING CHANGES - -* populate-- now defaults to false. - - - - -## [6.0.1](https://github.com/yargs/yargs-parser/compare/v6.0.0...v6.0.1) (2017-05-01) - - -### Bug Fixes - -* default '--' to undefined when not provided; this is closer to the array API ([#90](https://github.com/yargs/yargs-parser/issues/90)) ([4e739cc](https://github.com/yargs/yargs-parser/commit/4e739cc)) - - - - -# [6.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v6.0.0) (2017-05-01) - - -### Bug Fixes - -* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f)) -* parsing hints should apply for dot notation keys ([#86](https://github.com/yargs/yargs-parser/issues/86)) ([3e47d62](https://github.com/yargs/yargs-parser/commit/3e47d62)) - - -### Chores - -* upgrade to newest version of camelcase ([#87](https://github.com/yargs/yargs-parser/issues/87)) ([f1903aa](https://github.com/yargs/yargs-parser/commit/f1903aa)) - - -### Features - -* add -- option which allows arguments after the -- flag to be returned separated from positional arguments ([#84](https://github.com/yargs/yargs-parser/issues/84)) ([2572ca8](https://github.com/yargs/yargs-parser/commit/2572ca8)) -* when parsing stops, we now populate "--" by default ([#88](https://github.com/yargs/yargs-parser/issues/88)) ([cd666db](https://github.com/yargs/yargs-parser/commit/cd666db)) - - -### BREAKING CHANGES - -* rather than placing arguments in "_", when parsing is stopped via "--"; we now populate an array called "--" by default. -* camelcase now requires Node 4+. -* environment variables will now override config files (args, env, config-file, config-object) - - - - -# [5.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v5.0.0) (2017-02-18) - - -### Bug Fixes - -* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f)) - - -### BREAKING CHANGES - -* environment variables will now override config files (args, env, config-file, config-object) - - - - -## [4.2.1](https://github.com/yargs/yargs-parser/compare/v4.2.0...v4.2.1) (2017-01-02) - - -### Bug Fixes - -* flatten/duplicate regression ([#75](https://github.com/yargs/yargs-parser/issues/75)) ([68d68a0](https://github.com/yargs/yargs-parser/commit/68d68a0)) - - - - -# [4.2.0](https://github.com/yargs/yargs-parser/compare/v4.1.0...v4.2.0) (2016-12-01) - - -### Bug Fixes - -* inner objects in configs had their keys appended to top-level key when dot-notation was disabled ([#72](https://github.com/yargs/yargs-parser/issues/72)) ([0b1b5f9](https://github.com/yargs/yargs-parser/commit/0b1b5f9)) - - -### Features - -* allow multiple arrays to be provided, rather than always combining ([#71](https://github.com/yargs/yargs-parser/issues/71)) ([0f0fb2d](https://github.com/yargs/yargs-parser/commit/0f0fb2d)) - - - - -# [4.1.0](https://github.com/yargs/yargs-parser/compare/v4.0.2...v4.1.0) (2016-11-07) - - -### Features - -* apply coercions to default options ([#65](https://github.com/yargs/yargs-parser/issues/65)) ([c79052b](https://github.com/yargs/yargs-parser/commit/c79052b)) -* handle dot notation boolean options ([#63](https://github.com/yargs/yargs-parser/issues/63)) ([02c3545](https://github.com/yargs/yargs-parser/commit/02c3545)) - - - - -## [4.0.2](https://github.com/yargs/yargs-parser/compare/v4.0.1...v4.0.2) (2016-09-30) - - -### Bug Fixes - -* whoops, let's make the assign not change the Object key order ([29d069a](https://github.com/yargs/yargs-parser/commit/29d069a)) - - - - -## [4.0.1](https://github.com/yargs/yargs-parser/compare/v4.0.0...v4.0.1) (2016-09-30) - - -### Bug Fixes - -* lodash.assign was deprecated ([#59](https://github.com/yargs/yargs-parser/issues/59)) ([5e7eb11](https://github.com/yargs/yargs-parser/commit/5e7eb11)) - - - - -# [4.0.0](https://github.com/yargs/yargs-parser/compare/v3.2.0...v4.0.0) (2016-09-26) - - -### Bug Fixes - -* coerce should be applied to the final objects and arrays created ([#57](https://github.com/yargs/yargs-parser/issues/57)) ([4ca69da](https://github.com/yargs/yargs-parser/commit/4ca69da)) - - -### BREAKING CHANGES - -* coerce is no longer applied to individual arguments in an implicit array. - - - - -# [3.2.0](https://github.com/yargs/yargs-parser/compare/v3.1.0...v3.2.0) (2016-08-13) - - -### Features - -* coerce full array instead of each element ([#51](https://github.com/yargs/yargs-parser/issues/51)) ([cc4dc56](https://github.com/yargs/yargs-parser/commit/cc4dc56)) - - - - -# [3.1.0](https://github.com/yargs/yargs-parser/compare/v3.0.0...v3.1.0) (2016-08-09) - - -### Bug Fixes - -* address pkgConf parsing bug outlined in [#37](https://github.com/yargs/yargs-parser/issues/37) ([#45](https://github.com/yargs/yargs-parser/issues/45)) ([be76ee6](https://github.com/yargs/yargs-parser/commit/be76ee6)) -* better parsing of negative values ([#44](https://github.com/yargs/yargs-parser/issues/44)) ([2e43692](https://github.com/yargs/yargs-parser/commit/2e43692)) -* check aliases when guessing defaults for arguments fixes [#41](https://github.com/yargs/yargs-parser/issues/41) ([#43](https://github.com/yargs/yargs-parser/issues/43)) ([f3e4616](https://github.com/yargs/yargs-parser/commit/f3e4616)) - - -### Features - -* added coerce option, for providing specialized argument parsing ([#42](https://github.com/yargs/yargs-parser/issues/42)) ([7b49cd2](https://github.com/yargs/yargs-parser/commit/7b49cd2)) - - - - -# [3.0.0](https://github.com/yargs/yargs-parser/compare/v2.4.1...v3.0.0) (2016-08-07) - - -### Bug Fixes - -* parsing issue with numeric character in group of options ([#19](https://github.com/yargs/yargs-parser/issues/19)) ([f743236](https://github.com/yargs/yargs-parser/commit/f743236)) -* upgraded lodash.assign ([5d7fdf4](https://github.com/yargs/yargs-parser/commit/5d7fdf4)) - -### BREAKING CHANGES - -* subtle change to how values are parsed in a group of single-character arguments. -* _first released in 3.1.0, better handling of negative values should be considered a breaking change._ - - - - -## [2.4.1](https://github.com/yargs/yargs-parser/compare/v2.4.0...v2.4.1) (2016-07-16) - - -### Bug Fixes - -* **count:** do not increment a default value ([#39](https://github.com/yargs/yargs-parser/issues/39)) ([b04a189](https://github.com/yargs/yargs-parser/commit/b04a189)) - - - - -# [2.4.0](https://github.com/yargs/yargs-parser/compare/v2.3.0...v2.4.0) (2016-04-11) - - -### Features - -* **environment:** Support nested options in environment variables ([#26](https://github.com/yargs/yargs-parser/issues/26)) thanks [@elas7](https://github.com/elas7) \o/ ([020778b](https://github.com/yargs/yargs-parser/commit/020778b)) - - - - -# [2.3.0](https://github.com/yargs/yargs-parser/compare/v2.2.0...v2.3.0) (2016-04-09) - - -### Bug Fixes - -* **boolean:** fix for boolean options with non boolean defaults (#20) ([2dbe86b](https://github.com/yargs/yargs-parser/commit/2dbe86b)), closes [(#20](https://github.com/(/issues/20) -* **package:** remove tests from tarball ([0353c0d](https://github.com/yargs/yargs-parser/commit/0353c0d)) -* **parsing:** handle calling short option with an empty string as the next value. ([a867165](https://github.com/yargs/yargs-parser/commit/a867165)) -* boolean flag when next value contains the strings 'true' or 'false'. ([69941a6](https://github.com/yargs/yargs-parser/commit/69941a6)) -* update dependencies; add standard-version bin for next release (#24) ([822d9d5](https://github.com/yargs/yargs-parser/commit/822d9d5)) - -### Features - -* **configuration:** Allow to pass configuration objects to yargs-parser ([0780900](https://github.com/yargs/yargs-parser/commit/0780900)) -* **normalize:** allow normalize to work with arrays ([e0eaa1a](https://github.com/yargs/yargs-parser/commit/e0eaa1a)) diff --git a/reverse_engineering/node_modules/yargs-parser/LICENSE.txt b/reverse_engineering/node_modules/yargs-parser/LICENSE.txt deleted file mode 100644 index 836440b..0000000 --- a/reverse_engineering/node_modules/yargs-parser/LICENSE.txt +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) 2016, Contributors - -Permission to use, copy, modify, and/or distribute this software -for any purpose with or without fee is hereby granted, provided -that the above copyright notice and this permission notice -appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE -LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/yargs-parser/README.md b/reverse_engineering/node_modules/yargs-parser/README.md deleted file mode 100644 index bae61c2..0000000 --- a/reverse_engineering/node_modules/yargs-parser/README.md +++ /dev/null @@ -1,449 +0,0 @@ -# yargs-parser - -[![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) -[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) -[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) - - -The mighty option parser used by [yargs](https://github.com/yargs/yargs). - -visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. - - - -## Example - -```sh -npm i yargs-parser --save -``` - -```js -var argv = require('yargs-parser')(process.argv.slice(2)) -console.log(argv) -``` - -```sh -node example.js --foo=33 --bar hello -{ _: [], foo: 33, bar: 'hello' } -``` - -_or parse a string!_ - -```js -var argv = require('yargs-parser')('--foo=99 --bar=33') -console.log(argv) -``` - -```sh -{ _: [], foo: 99, bar: 33 } -``` - -Convert an array of mixed types before passing to `yargs-parser`: - -```js -var parse = require('yargs-parser') -parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string -parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings -``` - -## API - -### require('yargs-parser')(args, opts={}) - -Parses command line arguments returning a simple mapping of keys and values. - -**expects:** - -* `args`: a string or array of strings representing the options to parse. -* `opts`: provide a set of hints indicating how `args` should be parsed: - * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. - * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
- Indicate that keys should be parsed as an array and coerced to booleans / numbers:
- `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. - * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. - * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided - (or throws an error). For arrays the function is called only once for the entire array:
- `{coerce: {foo: function (arg) {return modifiedArg}}}`. - * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). - * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:
- `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. - * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). - * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. - * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. - * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. - * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. - * `opts.normalize`: `path.normalize()` will be applied to values set to this key. - * `opts.number`: keys should be treated as numbers. - * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). - -**returns:** - -* `obj`: an object representing the parsed value of `args` - * `key/value`: key value pairs for each argument and their aliases. - * `_`: an array representing the positional arguments. - * [optional] `--`: an array with arguments after the end-of-options flag `--`. - -### require('yargs-parser').detailed(args, opts={}) - -Parses a command line string, returning detailed information required by the -yargs engine. - -**expects:** - -* `args`: a string or array of strings representing options to parse. -* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. - -**returns:** - -* `argv`: an object representing the parsed value of `args` - * `key/value`: key value pairs for each argument and their aliases. - * `_`: an array representing the positional arguments. - * [optional] `--`: an array with arguments after the end-of-options flag `--`. -* `error`: populated with an error object if an exception occurred during parsing. -* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. -* `newAliases`: any new aliases added via camel-case expansion: - * `boolean`: `{ fooBar: true }` -* `defaulted`: any new argument created by `opts.default`, no aliases included. - * `boolean`: `{ foo: true }` -* `configuration`: given by default settings and `opts.configuration`. - - - -### Configuration - -The yargs-parser applies several automated transformations on the keys provided -in `args`. These features can be turned on and off using the `configuration` field -of `opts`. - -```js -var parsed = parser(['--no-dice'], { - configuration: { - 'boolean-negation': false - } -}) -``` - -### short option groups - -* default: `true`. -* key: `short-option-groups`. - -Should a group of short-options be treated as boolean flags? - -```sh -node example.js -abc -{ _: [], a: true, b: true, c: true } -``` - -_if disabled:_ - -```sh -node example.js -abc -{ _: [], abc: true } -``` - -### camel-case expansion - -* default: `true`. -* key: `camel-case-expansion`. - -Should hyphenated arguments be expanded into camel-case aliases? - -```sh -node example.js --foo-bar -{ _: [], 'foo-bar': true, fooBar: true } -``` - -_if disabled:_ - -```sh -node example.js --foo-bar -{ _: [], 'foo-bar': true } -``` - -### dot-notation - -* default: `true` -* key: `dot-notation` - -Should keys that contain `.` be treated as objects? - -```sh -node example.js --foo.bar -{ _: [], foo: { bar: true } } -``` - -_if disabled:_ - -```sh -node example.js --foo.bar -{ _: [], "foo.bar": true } -``` - -### parse numbers - -* default: `true` -* key: `parse-numbers` - -Should keys that look like numbers be treated as such? - -```sh -node example.js --foo=99.3 -{ _: [], foo: 99.3 } -``` - -_if disabled:_ - -```sh -node example.js --foo=99.3 -{ _: [], foo: "99.3" } -``` - -### boolean negation - -* default: `true` -* key: `boolean-negation` - -Should variables prefixed with `--no` be treated as negations? - -```sh -node example.js --no-foo -{ _: [], foo: false } -``` - -_if disabled:_ - -```sh -node example.js --no-foo -{ _: [], "no-foo": true } -``` - -### combine arrays - -* default: `false` -* key: `combine-arrays` - -Should arrays be combined when provided by both command line arguments and -a configuration file. - -### duplicate arguments array - -* default: `true` -* key: `duplicate-arguments-array` - -Should arguments be coerced into an array when duplicated: - -```sh -node example.js -x 1 -x 2 -{ _: [], x: [1, 2] } -``` - -_if disabled:_ - -```sh -node example.js -x 1 -x 2 -{ _: [], x: 2 } -``` - -### flatten duplicate arrays - -* default: `true` -* key: `flatten-duplicate-arrays` - -Should array arguments be coerced into a single array when duplicated: - -```sh -node example.js -x 1 2 -x 3 4 -{ _: [], x: [1, 2, 3, 4] } -``` - -_if disabled:_ - -```sh -node example.js -x 1 2 -x 3 4 -{ _: [], x: [[1, 2], [3, 4]] } -``` - -### greedy arrays - -* default: `true` -* key: `greedy-arrays` - -Should arrays consume more than one positional argument following their flag. - -```sh -node example --arr 1 2 -{ _[], arr: [1, 2] } -``` - -_if disabled:_ - -```sh -node example --arr 1 2 -{ _[2], arr: [1] } -``` - -**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** - -### nargs eats options - -* default: `false` -* key: `nargs-eats-options` - -Should nargs consume dash options as well as positional arguments. - -### negation prefix - -* default: `no-` -* key: `negation-prefix` - -The prefix to use for negated boolean variables. - -```sh -node example.js --no-foo -{ _: [], foo: false } -``` - -_if set to `quux`:_ - -```sh -node example.js --quuxfoo -{ _: [], foo: false } -``` - -### populate -- - -* default: `false`. -* key: `populate--` - -Should unparsed flags be stored in `--` or `_`. - -_If disabled:_ - -```sh -node example.js a -b -- x y -{ _: [ 'a', 'x', 'y' ], b: true } -``` - -_If enabled:_ - -```sh -node example.js a -b -- x y -{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true } -``` - -### set placeholder key - -* default: `false`. -* key: `set-placeholder-key`. - -Should a placeholder be added for keys not set via the corresponding CLI argument? - -_If disabled:_ - -```sh -node example.js -a 1 -c 2 -{ _: [], a: 1, c: 2 } -``` - -_If enabled:_ - -```sh -node example.js -a 1 -c 2 -{ _: [], a: 1, b: undefined, c: 2 } -``` - -### halt at non-option - -* default: `false`. -* key: `halt-at-non-option`. - -Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. - -_If disabled:_ - -```sh -node example.js -a run b -x y -{ _: [ 'b' ], a: 'run', x: 'y' } -``` - -_If enabled:_ - -```sh -node example.js -a run b -x y -{ _: [ 'b', '-x', 'y' ], a: 'run' } -``` - -### strip aliased - -* default: `false` -* key: `strip-aliased` - -Should aliases be removed before returning results? - -_If disabled:_ - -```sh -node example.js --test-field 1 -{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } -``` - -_If enabled:_ - -```sh -node example.js --test-field 1 -{ _: [], 'test-field': 1, testField: 1 } -``` - -### strip dashed - -* default: `false` -* key: `strip-dashed` - -Should dashed keys be removed before returning results? This option has no effect if -`camel-case-expansion` is disabled. - -_If disabled:_ - -```sh -node example.js --test-field 1 -{ _: [], 'test-field': 1, testField: 1 } -``` - -_If enabled:_ - -```sh -node example.js --test-field 1 -{ _: [], testField: 1 } -``` - -### unknown options as args - -* default: `false` -* key: `unknown-options-as-args` - -Should unknown options be treated like regular arguments? An unknown option is one that is not -configured in `opts`. - -_If disabled_ - -```sh -node example.js --unknown-option --known-option 2 --string-option --unknown-option2 -{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } -``` - -_If enabled_ - -```sh -node example.js --unknown-option --known-option 2 --string-option --unknown-option2 -{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } -``` - -## Special Thanks - -The yargs project evolves from optimist and minimist. It owes its -existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ - -## License - -ISC diff --git a/reverse_engineering/node_modules/yargs-parser/index.js b/reverse_engineering/node_modules/yargs-parser/index.js deleted file mode 100644 index c14c1fc..0000000 --- a/reverse_engineering/node_modules/yargs-parser/index.js +++ /dev/null @@ -1,1032 +0,0 @@ -const camelCase = require('camelcase') -const decamelize = require('decamelize') -const path = require('path') -const tokenizeArgString = require('./lib/tokenize-arg-string') -const util = require('util') - -function parse (args, opts) { - opts = Object.assign(Object.create(null), opts) - // allow a string argument to be passed in rather - // than an argv array. - args = tokenizeArgString(args) - - // aliases might have transitive relationships, normalize this. - const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)) - const configuration = Object.assign({ - 'boolean-negation': true, - 'camel-case-expansion': true, - 'combine-arrays': false, - 'dot-notation': true, - 'duplicate-arguments-array': true, - 'flatten-duplicate-arrays': true, - 'greedy-arrays': true, - 'halt-at-non-option': false, - 'nargs-eats-options': false, - 'negation-prefix': 'no-', - 'parse-numbers': true, - 'populate--': false, - 'set-placeholder-key': false, - 'short-option-groups': true, - 'strip-aliased': false, - 'strip-dashed': false, - 'unknown-options-as-args': false - }, opts.configuration) - const defaults = Object.assign(Object.create(null), opts.default) - const configObjects = opts.configObjects || [] - const envPrefix = opts.envPrefix - const notFlagsOption = configuration['populate--'] - const notFlagsArgv = notFlagsOption ? '--' : '_' - const newAliases = Object.create(null) - const defaulted = Object.create(null) - // allow a i18n handler to be passed in, default to a fake one (util.format). - const __ = opts.__ || util.format - const flags = { - aliases: Object.create(null), - arrays: Object.create(null), - bools: Object.create(null), - strings: Object.create(null), - numbers: Object.create(null), - counts: Object.create(null), - normalize: Object.create(null), - configs: Object.create(null), - nargs: Object.create(null), - coercions: Object.create(null), - keys: [] - } - const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/ - const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)') - - ;[].concat(opts.array).filter(Boolean).forEach(function (opt) { - const key = opt.key || opt - - // assign to flags[bools|strings|numbers] - const assignment = Object.keys(opt).map(function (key) { - return ({ - boolean: 'bools', - string: 'strings', - number: 'numbers' - })[key] - }).filter(Boolean).pop() - - // assign key to be coerced - if (assignment) { - flags[assignment][key] = true - } - - flags.arrays[key] = true - flags.keys.push(key) - }) - - ;[].concat(opts.boolean).filter(Boolean).forEach(function (key) { - flags.bools[key] = true - flags.keys.push(key) - }) - - ;[].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true - flags.keys.push(key) - }) - - ;[].concat(opts.number).filter(Boolean).forEach(function (key) { - flags.numbers[key] = true - flags.keys.push(key) - }) - - ;[].concat(opts.count).filter(Boolean).forEach(function (key) { - flags.counts[key] = true - flags.keys.push(key) - }) - - ;[].concat(opts.normalize).filter(Boolean).forEach(function (key) { - flags.normalize[key] = true - flags.keys.push(key) - }) - - Object.keys(opts.narg || {}).forEach(function (k) { - flags.nargs[k] = opts.narg[k] - flags.keys.push(k) - }) - - Object.keys(opts.coerce || {}).forEach(function (k) { - flags.coercions[k] = opts.coerce[k] - flags.keys.push(k) - }) - - if (Array.isArray(opts.config) || typeof opts.config === 'string') { - ;[].concat(opts.config).filter(Boolean).forEach(function (key) { - flags.configs[key] = true - }) - } else { - Object.keys(opts.config || {}).forEach(function (k) { - flags.configs[k] = opts.config[k] - }) - } - - // create a lookup table that takes into account all - // combinations of aliases: {f: ['foo'], foo: ['f']} - extendAliases(opts.key, aliases, opts.default, flags.arrays) - - // apply default values to all aliases. - Object.keys(defaults).forEach(function (key) { - (flags.aliases[key] || []).forEach(function (alias) { - defaults[alias] = defaults[key] - }) - }) - - let error = null - checkConfiguration() - - let notFlags = [] - - const argv = Object.assign(Object.create(null), { _: [] }) - // TODO(bcoe): for the first pass at removing object prototype we didn't - // remove all prototypes from objects returned by this API, we might want - // to gradually move towards doing so. - const argvReturn = {} - - for (let i = 0; i < args.length; i++) { - const arg = args[i] - let broken - let key - let letters - let m - let next - let value - - // any unknown option (except for end-of-options, "--") - if (arg !== '--' && isUnknownOptionAsArg(arg)) { - argv._.push(arg) - // -- separated by = - } else if (arg.match(/^--.+=/) || ( - !configuration['short-option-groups'] && arg.match(/^-.+=/) - )) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - m = arg.match(/^--?([^=]+)=([\s\S]*)$/) - - // arrays format = '--f=a b c' - if (checkAllAliases(m[1], flags.arrays)) { - i = eatArray(i, m[1], args, m[2]) - } else if (checkAllAliases(m[1], flags.nargs) !== false) { - // nargs format = '--f=monkey washing cat' - i = eatNargs(i, m[1], args, m[2]) - } else { - setArg(m[1], m[2]) - } - } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { - key = arg.match(negatedBoolean)[1] - setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false) - - // -- separated by space. - } else if (arg.match(/^--.+/) || ( - !configuration['short-option-groups'] && arg.match(/^-[^-]+/) - )) { - key = arg.match(/^--?(.+)/)[1] - - if (checkAllAliases(key, flags.arrays)) { - // array format = '--foo a b c' - i = eatArray(i, key, args) - } else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '--foo a b c' - // should be truthy even if: flags.nargs[key] === 0 - i = eatNargs(i, key, args) - } else { - next = args[i + 1] - - if (next !== undefined && (!next.match(/^-/) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next) - i++ - } else if (/^(true|false)$/.test(next)) { - setArg(key, next) - i++ - } else { - setArg(key, defaultValue(key)) - } - } - - // dot-notation flag separated by '='. - } else if (arg.match(/^-.\..+=/)) { - m = arg.match(/^-([^=]+)=([\s\S]*)$/) - setArg(m[1], m[2]) - - // dot-notation flag separated by space. - } else if (arg.match(/^-.\..+/) && !arg.match(negative)) { - next = args[i + 1] - key = arg.match(/^-(.\..+)/)[1] - - if (next !== undefined && !next.match(/^-/) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next) - i++ - } else { - setArg(key, defaultValue(key)) - } - } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { - letters = arg.slice(1, -1).split('') - broken = false - - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2) - - if (letters[j + 1] && letters[j + 1] === '=') { - value = arg.slice(j + 3) - key = letters[j] - - if (checkAllAliases(key, flags.arrays)) { - // array format = '-f=a b c' - i = eatArray(i, key, args, value) - } else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '-f=monkey washing cat' - i = eatNargs(i, key, args, value) - } else { - setArg(key, value) - } - - broken = true - break - } - - if (next === '-') { - setArg(letters[j], next) - continue - } - - // current letter is an alphabetic character and next value is a number - if (/[A-Za-z]/.test(letters[j]) && - /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next) - broken = true - break - } - - if (letters[j + 1] && letters[j + 1].match(/\W/)) { - setArg(letters[j], next) - broken = true - break - } else { - setArg(letters[j], defaultValue(letters[j])) - } - } - - key = arg.slice(-1)[0] - - if (!broken && key !== '-') { - if (checkAllAliases(key, flags.arrays)) { - // array format = '-f a b c' - i = eatArray(i, key, args) - } else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '-f a b c' - // should be truthy even if: flags.nargs[key] === 0 - i = eatNargs(i, key, args) - } else { - next = args[i + 1] - - if (next !== undefined && (!/^(-|--)[^-]/.test(next) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next) - i++ - } else if (/^(true|false)$/.test(next)) { - setArg(key, next) - i++ - } else { - setArg(key, defaultValue(key)) - } - } - } - } else if (arg.match(/^-[0-9]$/) && - arg.match(negative) && - checkAllAliases(arg.slice(1), flags.bools)) { - // single-digit boolean alias, e.g: xargs -0 - key = arg.slice(1) - setArg(key, defaultValue(key)) - } else if (arg === '--') { - notFlags = args.slice(i + 1) - break - } else if (configuration['halt-at-non-option']) { - notFlags = args.slice(i) - break - } else { - argv._.push(maybeCoerceNumber('_', arg)) - } - } - - // order of precedence: - // 1. command line arg - // 2. value from env var - // 3. value from config file - // 4. value from config objects - // 5. configured default value - applyEnvVars(argv, true) // special case: check env vars that point to config file - applyEnvVars(argv, false) - setConfig(argv) - setConfigObjects() - applyDefaultsAndAliases(argv, flags.aliases, defaults, true) - applyCoercions(argv) - if (configuration['set-placeholder-key']) setPlaceholderKeys(argv) - - // for any counts either not in args or without an explicit default, set to 0 - Object.keys(flags.counts).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) setArg(key, 0) - }) - - // '--' defaults to undefined. - if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = [] - notFlags.forEach(function (key) { - argv[notFlagsArgv].push(key) - }) - - if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { - Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { - delete argv[key] - }) - } - - if (configuration['strip-aliased']) { - ;[].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { - if (configuration['camel-case-expansion']) { - delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')] - } - - delete argv[alias] - }) - } - - // how many arguments should we consume, based - // on the nargs option? - function eatNargs (i, key, args, argAfterEqualSign) { - let ii - let toEat = checkAllAliases(key, flags.nargs) - // NaN has a special meaning for the array type, indicating that one or - // more values are expected. - toEat = isNaN(toEat) ? 1 : toEat - - if (toEat === 0) { - if (!isUndefined(argAfterEqualSign)) { - error = Error(__('Argument unexpected for: %s', key)) - } - setArg(key, defaultValue(key)) - return i - } - - let available = isUndefined(argAfterEqualSign) ? 0 : 1 - if (configuration['nargs-eats-options']) { - // classic behavior, yargs eats positional and dash arguments. - if (args.length - (i + 1) + available < toEat) { - error = Error(__('Not enough arguments following: %s', key)) - } - available = toEat - } else { - // nargs will not consume flag arguments, e.g., -abc, --foo, - // and terminates when one is observed. - for (ii = i + 1; ii < args.length; ii++) { - if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) available++ - else break - } - if (available < toEat) error = Error(__('Not enough arguments following: %s', key)) - } - - let consumed = Math.min(available, toEat) - if (!isUndefined(argAfterEqualSign) && consumed > 0) { - setArg(key, argAfterEqualSign) - consumed-- - } - for (ii = i + 1; ii < (consumed + i + 1); ii++) { - setArg(key, args[ii]) - } - - return (i + consumed) - } - - // if an option is an array, eat all non-hyphenated arguments - // following it... YUM! - // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] - function eatArray (i, key, args, argAfterEqualSign) { - let argsToSet = [] - let next = argAfterEqualSign || args[i + 1] - // If both array and nargs are configured, enforce the nargs count: - const nargsCount = checkAllAliases(key, flags.nargs) - - if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { - argsToSet.push(true) - } else if (isUndefined(next) || - (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { - // for keys without value ==> argsToSet remains an empty [] - // set user default value, if available - if (defaults[key] !== undefined) { - const defVal = defaults[key] - argsToSet = Array.isArray(defVal) ? defVal : [defVal] - } - } else { - // value in --option=value is eaten as is - if (!isUndefined(argAfterEqualSign)) { - argsToSet.push(processValue(key, argAfterEqualSign)) - } - for (let ii = i + 1; ii < args.length; ii++) { - if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || - (nargsCount && argsToSet.length >= nargsCount)) break - next = args[ii] - if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) break - i = ii - argsToSet.push(processValue(key, next)) - } - } - - // If both array and nargs are configured, create an error if less than - // nargs positionals were found. NaN has special meaning, indicating - // that at least one value is required (more are okay). - if ((nargsCount && argsToSet.length < nargsCount) || - (isNaN(nargsCount) && argsToSet.length === 0)) { - error = Error(__('Not enough arguments following: %s', key)) - } - - setArg(key, argsToSet) - return i - } - - function setArg (key, val) { - if (/-/.test(key) && configuration['camel-case-expansion']) { - const alias = key.split('.').map(function (prop) { - return camelCase(prop) - }).join('.') - addNewAlias(key, alias) - } - - const value = processValue(key, val) - const splitKey = key.split('.') - setKey(argv, splitKey, value) - - // handle populating aliases of the full key - if (flags.aliases[key]) { - flags.aliases[key].forEach(function (x) { - x = x.split('.') - setKey(argv, x, value) - }) - } - - // handle populating aliases of the first element of the dot-notation key - if (splitKey.length > 1 && configuration['dot-notation']) { - ;(flags.aliases[splitKey[0]] || []).forEach(function (x) { - x = x.split('.') - - // expand alias with nested objects in key - const a = [].concat(splitKey) - a.shift() // nuke the old key. - x = x.concat(a) - - // populate alias only if is not already an alias of the full key - // (already populated above) - if (!(flags.aliases[key] || []).includes(x.join('.'))) { - setKey(argv, x, value) - } - }) - } - - // Set normalize getter and setter when key is in 'normalize' but isn't an array - if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { - const keys = [key].concat(flags.aliases[key] || []) - keys.forEach(function (key) { - Object.defineProperty(argvReturn, key, { - enumerable: true, - get () { - return val - }, - set (value) { - val = typeof value === 'string' ? path.normalize(value) : value - } - }) - }) - } - } - - function addNewAlias (key, alias) { - if (!(flags.aliases[key] && flags.aliases[key].length)) { - flags.aliases[key] = [alias] - newAliases[alias] = true - } - if (!(flags.aliases[alias] && flags.aliases[alias].length)) { - addNewAlias(alias, key) - } - } - - function processValue (key, val) { - // strings may be quoted, clean this up as we assign values. - if (typeof val === 'string' && - (val[0] === "'" || val[0] === '"') && - val[val.length - 1] === val[0] - ) { - val = val.substring(1, val.length - 1) - } - - // handle parsing boolean arguments --foo=true --bar false. - if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { - if (typeof val === 'string') val = val === 'true' - } - - let value = Array.isArray(val) - ? val.map(function (v) { return maybeCoerceNumber(key, v) }) - : maybeCoerceNumber(key, val) - - // increment a count given as arg (either no value or value parsed as boolean) - if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { - value = increment - } - - // Set normalized value when key is in 'normalize' and in 'arrays' - if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { - if (Array.isArray(val)) value = val.map(path.normalize) - else value = path.normalize(val) - } - return value - } - - function maybeCoerceNumber (key, value) { - if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { - const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && ( - Number.isSafeInteger(Math.floor(value)) - ) - if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value) - } - return value - } - - // set args from config.json file, this should be - // applied last so that defaults can be applied. - function setConfig (argv) { - const configLookup = Object.create(null) - - // expand defaults/aliases, in-case any happen to reference - // the config.json file. - applyDefaultsAndAliases(configLookup, flags.aliases, defaults) - - Object.keys(flags.configs).forEach(function (configKey) { - const configPath = argv[configKey] || configLookup[configKey] - if (configPath) { - try { - let config = null - const resolvedConfigPath = path.resolve(process.cwd(), configPath) - - if (typeof flags.configs[configKey] === 'function') { - try { - config = flags.configs[configKey](resolvedConfigPath) - } catch (e) { - config = e - } - if (config instanceof Error) { - error = config - return - } - } else { - config = require(resolvedConfigPath) - } - - setConfigObject(config) - } catch (ex) { - if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath)) - } - } - }) - } - - // set args from config object. - // it recursively checks nested objects. - function setConfigObject (config, prev) { - Object.keys(config).forEach(function (key) { - const value = config[key] - const fullKey = prev ? prev + '.' + key : key - - // if the value is an inner object and we have dot-notation - // enabled, treat inner objects in config the same as - // heavily nested dot notations (foo.bar.apple). - if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { - // if the value is an object but not an array, check nested object - setConfigObject(value, fullKey) - } else { - // setting arguments via CLI takes precedence over - // values within the config file. - if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { - setArg(fullKey, value) - } - } - }) - } - - // set all config objects passed in opts - function setConfigObjects () { - if (typeof configObjects === 'undefined') return - configObjects.forEach(function (configObject) { - setConfigObject(configObject) - }) - } - - function applyEnvVars (argv, configOnly) { - if (typeof envPrefix === 'undefined') return - - const prefix = typeof envPrefix === 'string' ? envPrefix : '' - Object.keys(process.env).forEach(function (envVar) { - if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { - // get array of nested keys and convert them to camel case - const keys = envVar.split('__').map(function (key, i) { - if (i === 0) { - key = key.substring(prefix.length) - } - return camelCase(key) - }) - - if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { - setArg(keys.join('.'), process.env[envVar]) - } - } - }) - } - - function applyCoercions (argv) { - let coerce - const applied = new Set() - Object.keys(argv).forEach(function (key) { - if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases - coerce = checkAllAliases(key, flags.coercions) - if (typeof coerce === 'function') { - try { - const value = maybeCoerceNumber(key, coerce(argv[key])) - ;([].concat(flags.aliases[key] || [], key)).forEach(ali => { - applied.add(ali) - argv[ali] = value - }) - } catch (err) { - error = err - } - } - } - }) - } - - function setPlaceholderKeys (argv) { - flags.keys.forEach((key) => { - // don't set placeholder keys for dot notation options 'foo.bar'. - if (~key.indexOf('.')) return - if (typeof argv[key] === 'undefined') argv[key] = undefined - }) - return argv - } - - function applyDefaultsAndAliases (obj, aliases, defaults, canLog = false) { - Object.keys(defaults).forEach(function (key) { - if (!hasKey(obj, key.split('.'))) { - setKey(obj, key.split('.'), defaults[key]) - if (canLog) defaulted[key] = true - - ;(aliases[key] || []).forEach(function (x) { - if (hasKey(obj, x.split('.'))) return - setKey(obj, x.split('.'), defaults[key]) - }) - } - }) - } - - function hasKey (obj, keys) { - let o = obj - - if (!configuration['dot-notation']) keys = [keys.join('.')] - - keys.slice(0, -1).forEach(function (key) { - o = (o[key] || {}) - }) - - const key = keys[keys.length - 1] - - if (typeof o !== 'object') return false - else return key in o - } - - function setKey (obj, keys, value) { - let o = obj - - if (!configuration['dot-notation']) keys = [keys.join('.')] - - keys.slice(0, -1).forEach(function (key, index) { - // TODO(bcoe): in the next major version of yargs, switch to - // Object.create(null) for dot notation: - key = sanitizeKey(key) - - if (typeof o === 'object' && o[key] === undefined) { - o[key] = {} - } - - if (typeof o[key] !== 'object' || Array.isArray(o[key])) { - // ensure that o[key] is an array, and that the last item is an empty object. - if (Array.isArray(o[key])) { - o[key].push({}) - } else { - o[key] = [o[key], {}] - } - - // we want to update the empty object at the end of the o[key] array, so set o to that object - o = o[key][o[key].length - 1] - } else { - o = o[key] - } - }) - - // TODO(bcoe): in the next major version of yargs, switch to - // Object.create(null) for dot notation: - const key = sanitizeKey(keys[keys.length - 1]) - - const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays) - const isValueArray = Array.isArray(value) - let duplicate = configuration['duplicate-arguments-array'] - - // nargs has higher priority than duplicate - if (!duplicate && checkAllAliases(key, flags.nargs)) { - duplicate = true - if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { - o[key] = undefined - } - } - - if (value === increment) { - o[key] = increment(o[key]) - } else if (Array.isArray(o[key])) { - if (duplicate && isTypeArray && isValueArray) { - o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]) - } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { - o[key] = value - } else { - o[key] = o[key].concat([value]) - } - } else if (o[key] === undefined && isTypeArray) { - o[key] = isValueArray ? value : [value] - } else if (duplicate && !( - o[key] === undefined || - checkAllAliases(key, flags.counts) || - checkAllAliases(key, flags.bools) - )) { - o[key] = [o[key], value] - } else { - o[key] = value - } - } - - // extend the aliases list with inferred aliases. - function extendAliases (...args) { - args.forEach(function (obj) { - Object.keys(obj || {}).forEach(function (key) { - // short-circuit if we've already added a key - // to the aliases array, for example it might - // exist in both 'opts.default' and 'opts.key'. - if (flags.aliases[key]) return - - flags.aliases[key] = [].concat(aliases[key] || []) - // For "--option-name", also set argv.optionName - flags.aliases[key].concat(key).forEach(function (x) { - if (/-/.test(x) && configuration['camel-case-expansion']) { - const c = camelCase(x) - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c) - newAliases[c] = true - } - } - }) - // For "--optionName", also set argv['option-name'] - flags.aliases[key].concat(key).forEach(function (x) { - if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { - const c = decamelize(x, '-') - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c) - newAliases[c] = true - } - } - }) - flags.aliases[key].forEach(function (x) { - flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { - return x !== y - })) - }) - }) - }) - } - - // return the 1st set flag for any of a key's aliases (or false if no flag set) - function checkAllAliases (key, flag) { - const toCheck = [].concat(flags.aliases[key] || [], key) - const keys = Object.keys(flag) - const setAlias = toCheck.find(key => keys.includes(key)) - return setAlias ? flag[setAlias] : false - } - - function hasAnyFlag (key) { - const toCheck = [].concat(Object.keys(flags).map(k => flags[k])) - return toCheck.some(function (flag) { - return Array.isArray(flag) ? flag.includes(key) : flag[key] - }) - } - - function hasFlagsMatching (arg, ...patterns) { - const toCheck = [].concat(...patterns) - return toCheck.some(function (pattern) { - const match = arg.match(pattern) - return match && hasAnyFlag(match[1]) - }) - } - - // based on a simplified version of the short flag group parsing logic - function hasAllShortFlags (arg) { - // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group - if (arg.match(negative) || !arg.match(/^-[^-]+/)) { return false } - let hasAllFlags = true - let next - const letters = arg.slice(1).split('') - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2) - - if (!hasAnyFlag(letters[j])) { - hasAllFlags = false - break - } - - if ((letters[j + 1] && letters[j + 1] === '=') || - next === '-' || - (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || - (letters[j + 1] && letters[j + 1].match(/\W/))) { - break - } - } - return hasAllFlags - } - - function isUnknownOptionAsArg (arg) { - return configuration['unknown-options-as-args'] && isUnknownOption(arg) - } - - function isUnknownOption (arg) { - // ignore negative numbers - if (arg.match(negative)) { return false } - // if this is a short option group and all of them are configured, it isn't unknown - if (hasAllShortFlags(arg)) { return false } - // e.g. '--count=2' - const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/ - // e.g. '-a' or '--arg' - const normalFlag = /^-+([^=]+?)$/ - // e.g. '-a-' - const flagEndingInHyphen = /^-+([^=]+?)-$/ - // e.g. '-abc123' - const flagEndingInDigits = /^-+([^=]+?\d+)$/ - // e.g. '-a/usr/local' - const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/ - // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method - return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters) - } - - // make a best effor to pick a default value - // for an option based on name and type. - function defaultValue (key) { - if (!checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts) && - `${key}` in defaults) { - return defaults[key] - } else { - return defaultForType(guessType(key)) - } - } - - // return a default value, given the type of a flag., - // e.g., key of type 'string' will default to '', rather than 'true'. - function defaultForType (type) { - const def = { - boolean: true, - string: '', - number: undefined, - array: [] - } - - return def[type] - } - - // given a flag, enforce a default type. - function guessType (key) { - let type = 'boolean' - if (checkAllAliases(key, flags.strings)) type = 'string' - else if (checkAllAliases(key, flags.numbers)) type = 'number' - else if (checkAllAliases(key, flags.bools)) type = 'boolean' - else if (checkAllAliases(key, flags.arrays)) type = 'array' - return type - } - - function isNumber (x) { - if (x === null || x === undefined) return false - // if loaded from config, may already be a number. - if (typeof x === 'number') return true - // hexadecimal. - if (/^0x[0-9a-f]+$/i.test(x)) return true - // don't treat 0123 as a number; as it drops the leading '0'. - if (x.length > 1 && x[0] === '0') return false - return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x) - } - - function isUndefined (num) { - return num === undefined - } - - // check user configuration settings for inconsistencies - function checkConfiguration () { - // count keys should not be set as array/narg - Object.keys(flags.counts).find(key => { - if (checkAllAliases(key, flags.arrays)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)) - return true - } else if (checkAllAliases(key, flags.nargs)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)) - return true - } - }) - } - - return { - argv: Object.assign(argvReturn, argv), - error: error, - aliases: Object.assign({}, flags.aliases), - newAliases: Object.assign({}, newAliases), - defaulted: Object.assign({}, defaulted), - configuration: configuration - } -} - -// if any aliases reference each other, we should -// merge them together. -function combineAliases (aliases) { - const aliasArrays = [] - const combined = Object.create(null) - let change = true - - // turn alias lookup hash {key: ['alias1', 'alias2']} into - // a simple array ['key', 'alias1', 'alias2'] - Object.keys(aliases).forEach(function (key) { - aliasArrays.push( - [].concat(aliases[key], key) - ) - }) - - // combine arrays until zero changes are - // made in an iteration. - while (change) { - change = false - for (let i = 0; i < aliasArrays.length; i++) { - for (let ii = i + 1; ii < aliasArrays.length; ii++) { - const intersect = aliasArrays[i].filter(function (v) { - return aliasArrays[ii].indexOf(v) !== -1 - }) - - if (intersect.length) { - aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]) - aliasArrays.splice(ii, 1) - change = true - break - } - } - } - } - - // map arrays back to the hash-lookup (de-dupe while - // we're at it). - aliasArrays.forEach(function (aliasArray) { - aliasArray = aliasArray.filter(function (v, i, self) { - return self.indexOf(v) === i - }) - combined[aliasArray.pop()] = aliasArray - }) - - return combined -} - -// this function should only be called when a count is given as an arg -// it is NOT called to set a default value -// thus we can start the count at 1 instead of 0 -function increment (orig) { - return orig !== undefined ? orig + 1 : 1 -} - -function Parser (args, opts) { - const result = parse(args.slice(), opts) - return result.argv -} - -// parse arguments and return detailed -// meta information, aliases, etc. -Parser.detailed = function (args, opts) { - return parse(args.slice(), opts) -} - -// TODO(bcoe): in the next major version of yargs, switch to -// Object.create(null) for dot notation: -function sanitizeKey (key) { - if (key === '__proto__') return '___proto___' - return key -} - -module.exports = Parser diff --git a/reverse_engineering/node_modules/yargs-parser/lib/tokenize-arg-string.js b/reverse_engineering/node_modules/yargs-parser/lib/tokenize-arg-string.js deleted file mode 100644 index 260c67c..0000000 --- a/reverse_engineering/node_modules/yargs-parser/lib/tokenize-arg-string.js +++ /dev/null @@ -1,40 +0,0 @@ -// take an un-split argv string and tokenize it. -module.exports = function (argString) { - if (Array.isArray(argString)) { - return argString.map(e => typeof e !== 'string' ? e + '' : e) - } - - argString = argString.trim() - - let i = 0 - let prevC = null - let c = null - let opening = null - const args = [] - - for (let ii = 0; ii < argString.length; ii++) { - prevC = c - c = argString.charAt(ii) - - // split on spaces unless we're in quotes. - if (c === ' ' && !opening) { - if (!(prevC === ' ')) { - i++ - } - continue - } - - // don't split the string if we're in matching - // opening or closing single and double quotes. - if (c === opening) { - opening = null - } else if ((c === "'" || c === '"') && !opening) { - opening = c - } - - if (!args[i]) args[i] = '' - args[i] += c - } - - return args -} diff --git a/reverse_engineering/node_modules/yargs-parser/package.json b/reverse_engineering/node_modules/yargs-parser/package.json deleted file mode 100644 index 636ff17..0000000 --- a/reverse_engineering/node_modules/yargs-parser/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "yargs-parser", - "version": "18.1.3", - "description": "the mighty option parser used by yargs", - "main": "index.js", - "scripts": { - "fix": "standard --fix", - "test": "c8 --reporter=text --reporter=html mocha test/*.js", - "posttest": "standard", - "coverage": "c8 report --check-coverage check-coverage --lines=100 --branches=97 --statements=100" - }, - "repository": { - "type": "git", - "url": "https://github.com/yargs/yargs-parser.git" - }, - "keywords": [ - "argument", - "parser", - "yargs", - "command", - "cli", - "parsing", - "option", - "args", - "argument" - ], - "author": "Ben Coe ", - "license": "ISC", - "devDependencies": { - "c8": "^7.0.1", - "chai": "^4.2.0", - "mocha": "^7.0.0", - "standard": "^14.3.1" - }, - "dependencies": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - }, - "files": [ - "lib", - "index.js" - ], - "engines": { - "node": ">=6" - } -} diff --git a/reverse_engineering/node_modules/yargs/CHANGELOG.md b/reverse_engineering/node_modules/yargs/CHANGELOG.md deleted file mode 100644 index a010cf3..0000000 --- a/reverse_engineering/node_modules/yargs/CHANGELOG.md +++ /dev/null @@ -1,420 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -## [15.4.0](https://www.github.com/yargs/yargs/compare/v15.3.1...v15.4.0) (2020-06-30) - - -### Features - -* adds deprecation option for commands ([027a636](https://www.github.com/yargs/yargs/commit/027a6365b737e13116811a8ef43670196e1fa00a)) -* support array of examples ([#1682](https://www.github.com/yargs/yargs/issues/1682)) ([225ab82](https://www.github.com/yargs/yargs/commit/225ab8271938bed3a48d23175f3d580ce8cd1306)) - - -### Bug Fixes - -* **docs:** describe usage of `.check()` in more detail ([932cd11](https://www.github.com/yargs/yargs/commit/932cd1177e93f5cc99edfe57a4028e30717bf8fb)) -* **i18n:** Japanese translation phrasing ([#1619](https://www.github.com/yargs/yargs/issues/1619)) ([0894175](https://www.github.com/yargs/yargs/commit/089417550ef5a5b8ce3578dd2a989191300b64cd)) -* **strict mode:** report default command unknown arguments ([#1626](https://www.github.com/yargs/yargs/issues/1626)) ([69f29a9](https://www.github.com/yargs/yargs/commit/69f29a9cd429d4bb99481238305390107ac75b02)) -* **usage:** translate 'options' group only when displaying help ([#1600](https://www.github.com/yargs/yargs/issues/1600)) ([e60b39b](https://www.github.com/yargs/yargs/commit/e60b39b9d3a912c06db43f87c86ba894142b6c1c)) - - -### Reverts - -* Revert "chore(deps): update dependency eslint to v7 (#1656)" (#1673) ([34949f8](https://www.github.com/yargs/yargs/commit/34949f89ee7cdf88f7b315659df4b5f62f714842)), closes [#1656](https://www.github.com/yargs/yargs/issues/1656) [#1673](https://www.github.com/yargs/yargs/issues/1673) - -### [15.3.1](https://www.github.com/yargs/yargs/compare/v15.3.0...v15.3.1) (2020-03-16) - - -### Bug Fixes - -* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential -prototype pollution vulnerability. This was reported by the Snyk Security Research Team. ([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2)) - -## [15.3.0](https://www.github.com/yargs/yargs/compare/v15.2.0...v15.3.0) (2020-03-08) - - -### Features - -* **yargs-parser:** introduce single-digit boolean aliases ([#1576](https://www.github.com/yargs/yargs/issues/1576)) ([3af7f04](https://www.github.com/yargs/yargs/commit/3af7f04cdbfcbd4b3f432aca5144d43f21958c39)) -* add usage for single-digit boolean aliases ([#1580](https://www.github.com/yargs/yargs/issues/1580)) ([6014e39](https://www.github.com/yargs/yargs/commit/6014e39bca3a1e8445aa0fb2a435f6181e344c45)) - - -### Bug Fixes - -* address ambiguity between nargs of 1 and requiresArg ([#1572](https://www.github.com/yargs/yargs/issues/1572)) ([a5edc32](https://www.github.com/yargs/yargs/commit/a5edc328ecb3f90d1ba09cfe70a0040f68adf50a)) - -## [15.2.0](https://www.github.com/yargs/yargs/compare/v15.1.0...v15.2.0) (2020-03-01) - - -### ⚠ BREAKING CHANGES - -* **deps:** yargs-parser@17.0.0 no longer implicitly creates arrays out of boolean -arguments when duplicates are provided - -### Features - -* **completion:** takes negated flags into account when boolean-negation is set ([#1509](https://www.github.com/yargs/yargs/issues/1509)) ([7293ad5](https://www.github.com/yargs/yargs/commit/7293ad50d20ea0fb7dd1ac9b925e90e1bd95dea8)) -* **deps:** pull in yargs-parser@17.0.0 ([#1553](https://www.github.com/yargs/yargs/issues/1553)) ([b9409da](https://www.github.com/yargs/yargs/commit/b9409da199ebca515a848489c206b807fab2e65d)) -* deprecateOption ([#1559](https://www.github.com/yargs/yargs/issues/1559)) ([8aae333](https://www.github.com/yargs/yargs/commit/8aae3332251d09fa136db17ef4a40d83fa052bc4)) -* display appropriate $0 for electron apps ([#1536](https://www.github.com/yargs/yargs/issues/1536)) ([d0e4379](https://www.github.com/yargs/yargs/commit/d0e437912917d6a66bb5128992fa2f566a5f830b)) -* introduces strictCommands() subset of strict mode ([#1540](https://www.github.com/yargs/yargs/issues/1540)) ([1d4cca3](https://www.github.com/yargs/yargs/commit/1d4cca395a98b395e6318f0505fc73bef8b01350)) -* **deps:** yargs-parser with 'greedy-array' configuration ([#1569](https://www.github.com/yargs/yargs/issues/1569)) ([a03a320](https://www.github.com/yargs/yargs/commit/a03a320dbf5c0ce33d829a857fc04a651c0bb53e)) - - -### Bug Fixes - -* help always displayed for the first command parsed having an async handler ([#1535](https://www.github.com/yargs/yargs/issues/1535)) ([d585b30](https://www.github.com/yargs/yargs/commit/d585b303a43746201b05c9c9fda94a444634df33)) -* **deps:** fix enumeration for normalized path arguments ([#1567](https://www.github.com/yargs/yargs/issues/1567)) ([0b5b1b0](https://www.github.com/yargs/yargs/commit/0b5b1b0e5f4f9baf393c48e9cc2bc85c1b67a47a)) -* **locales:** only translate default option group name ([acc16de](https://www.github.com/yargs/yargs/commit/acc16de6b846ea7332db753646a9cec76b589162)) -* **locales:** remove extra space in French for 'default' ([#1564](https://www.github.com/yargs/yargs/issues/1564)) ([ecfc2c4](https://www.github.com/yargs/yargs/commit/ecfc2c474575c6cdbc6d273c94c13181bd1dbaa6)) -* **translations:** add French translation for unknown command ([#1563](https://www.github.com/yargs/yargs/issues/1563)) ([18b0b75](https://www.github.com/yargs/yargs/commit/18b0b752424bf560271e670ff95a0f90c8386787)) -* **translations:** fix pluralization in error messages. ([#1557](https://www.github.com/yargs/yargs/issues/1557)) ([94fa38c](https://www.github.com/yargs/yargs/commit/94fa38cbab8d86943e87bf41d368ed56dffa6835)) -* **yargs:** correct support of bundled electron apps ([#1554](https://www.github.com/yargs/yargs/issues/1554)) ([a0b61ac](https://www.github.com/yargs/yargs/commit/a0b61ac21e2b554aa73dbf1a66d4a7af94047c2f)) - -## [15.1.0](https://www.github.com/yargs/yargs/compare/v15.0.2...v15.1.0) (2020-01-02) - - -### Features - -* **lang:** add Finnish localization (language code fi) ([222c8fe](https://www.github.com/yargs/yargs/commit/222c8fef2e2ad46e314c337dec96940f896bec35)) -* complete short options with a single dash ([#1507](https://www.github.com/yargs/yargs/issues/1507)) ([99011ab](https://www.github.com/yargs/yargs/commit/99011ab5ba90232506ece0a17e59e2001a1ab562)) -* onFinishCommand handler ([#1473](https://www.github.com/yargs/yargs/issues/1473)) ([fe380cd](https://www.github.com/yargs/yargs/commit/fe380cd356aa33aef0449facd59c22cab8930ac9)) - - -### Bug Fixes - -* getCompletion() was not working for options ([#1495](https://www.github.com/yargs/yargs/issues/1495)) ([463feb2](https://www.github.com/yargs/yargs/commit/463feb2870158eb9df670222b0f0a40a05cf18d0)) -* misspelling of package.json `engines` field ([0891d0e](https://www.github.com/yargs/yargs/commit/0891d0ed35b30c83a6d9e9f6a5c5f84d13c546a0)) -* populate positionals when unknown-options-as-args is set ([#1508](https://www.github.com/yargs/yargs/issues/1508)) ([bb0f2eb](https://www.github.com/yargs/yargs/commit/bb0f2eb996fa4e19d330b31a01c2036cafa99a7e)), closes [#1444](https://www.github.com/yargs/yargs/issues/1444) -* show 2 dashes on help for single digit option key or alias ([#1493](https://www.github.com/yargs/yargs/issues/1493)) ([63b3dd3](https://www.github.com/yargs/yargs/commit/63b3dd31a455d428902220c1992ae930e18aff5c)) -* **docs:** use recommended cjs import syntax for ts examples ([#1513](https://www.github.com/yargs/yargs/issues/1513)) ([f9a18bf](https://www.github.com/yargs/yargs/commit/f9a18bfd624a5013108084f690cd8a1de794c430)) - -### [15.0.2](https://www.github.com/yargs/yargs/compare/v15.0.1...v15.0.2) (2019-11-19) - - -### Bug Fixes - -* temporary fix for libraries that call Object.freeze() ([#1483](https://www.github.com/yargs/yargs/issues/1483)) ([99c2dc8](https://www.github.com/yargs/yargs/commit/99c2dc850e67c606644f8b0c0bca1a59c87dcbcd)) - -### [15.0.1](https://www.github.com/yargs/yargs/compare/v15.0.0...v15.0.1) (2019-11-16) - - -### Bug Fixes - -* **deps:** cliui, find-up, and string-width, all drop Node 6 support ([#1479](https://www.github.com/yargs/yargs/issues/1479)) ([6a9ebe2](https://www.github.com/yargs/yargs/commit/6a9ebe2d955e3e979e76c07ffbb1c17fef64cb49)) - -## [15.0.0](https://www.github.com/yargs/yargs/compare/v14.2.0...v15.0.0) (2019-11-10) - - -### ⚠ BREAKING CHANGES - -* **deps:** yargs-parser now throws on invalid combinations of config (#1470) -* yargs-parser@16.0.0 drops support for Node 6 -* drop Node 6 support (#1461) -* remove package.json-based parserConfiguration (#1460) - -### Features - -* **deps:** yargs-parser now throws on invalid combinations of config ([#1470](https://www.github.com/yargs/yargs/issues/1470)) ([c10c38c](https://www.github.com/yargs/yargs/commit/c10c38cca04298f96b55a7e374a9a134abefffa7)) -* expose `Parser` from `require('yargs/yargs')` ([#1477](https://www.github.com/yargs/yargs/issues/1477)) ([1840ba2](https://www.github.com/yargs/yargs/commit/1840ba22f1a24c0ece8e32bbd31db4134a080aee)) - - -### Bug Fixes - -* **docs:** TypeScript import to prevent a future major release warning ([#1441](https://www.github.com/yargs/yargs/issues/1441)) ([b1b156a](https://www.github.com/yargs/yargs/commit/b1b156a3eb4ddd6803fbbd56c611a77919293000)) -* stop-parse was not being respected by commands ([#1459](https://www.github.com/yargs/yargs/issues/1459)) ([12c82e6](https://www.github.com/yargs/yargs/commit/12c82e62663e928148a7ee2f51629aa26a0f9bb2)) -* update to yargs-parser with fix for array default values ([#1463](https://www.github.com/yargs/yargs/issues/1463)) ([ebee59d](https://www.github.com/yargs/yargs/commit/ebee59d9022da538410e69a5c025019ed46d13d2)) -* **docs:** update boolean description and examples in docs ([#1474](https://www.github.com/yargs/yargs/issues/1474)) ([afd5b48](https://www.github.com/yargs/yargs/commit/afd5b4871bfeb90d58351ac56c5c44a83ef033e6)) - - -### Miscellaneous Chores - -* drop Node 6 support ([#1461](https://www.github.com/yargs/yargs/issues/1461)) ([2ba8ce0](https://www.github.com/yargs/yargs/commit/2ba8ce05e8fefbeffc6cb7488d9ebf6e86cceb1d)) - - -### Code Refactoring - -* remove package.json-based parserConfiguration ([#1460](https://www.github.com/yargs/yargs/issues/1460)) ([0d3642b](https://www.github.com/yargs/yargs/commit/0d3642b6f829b637938774c0c6ce5f6bfe1afa51)) - -## [14.2.0](https://github.com/yargs/yargs/compare/v14.1.0...v14.2.0) (2019-10-07) - - -### Bug Fixes - -* async middleware was called twice ([#1422](https://github.com/yargs/yargs/issues/1422)) ([9a42b63](https://github.com/yargs/yargs/commit/9a42b63)) -* fix promise check to accept any spec conform object ([#1424](https://github.com/yargs/yargs/issues/1424)) ([0be43d2](https://github.com/yargs/yargs/commit/0be43d2)) -* groups were not being maintained for nested commands ([#1430](https://github.com/yargs/yargs/issues/1430)) ([d38650e](https://github.com/yargs/yargs/commit/d38650e)) -* **docs:** broken markdown link ([#1426](https://github.com/yargs/yargs/issues/1426)) ([236e24e](https://github.com/yargs/yargs/commit/236e24e)) -* support merging deeply nested configuration ([#1423](https://github.com/yargs/yargs/issues/1423)) ([bae66fe](https://github.com/yargs/yargs/commit/bae66fe)) - - -### Features - -* **deps:** introduce yargs-parser with support for unknown-options-as-args ([#1440](https://github.com/yargs/yargs/issues/1440)) ([4d21520](https://github.com/yargs/yargs/commit/4d21520)) - -## [14.1.0](https://github.com/yargs/yargs/compare/v14.0.0...v14.1.0) (2019-09-06) - - -### Bug Fixes - -* **docs:** fix incorrect parserConfiguration documentation ([2a99124](https://github.com/yargs/yargs/commit/2a99124)) -* detect zsh when zsh isnt run as a login prompt ([#1395](https://github.com/yargs/yargs/issues/1395)) ([8792d13](https://github.com/yargs/yargs/commit/8792d13)) -* populate correct value on yargs.parsed and stop warning on access ([#1412](https://github.com/yargs/yargs/issues/1412)) ([bb0eb52](https://github.com/yargs/yargs/commit/bb0eb52)) -* showCompletionScript was logging script twice ([#1388](https://github.com/yargs/yargs/issues/1388)) ([07c8537](https://github.com/yargs/yargs/commit/07c8537)) -* strict() should not ignore hyphenated arguments ([#1414](https://github.com/yargs/yargs/issues/1414)) ([b774b5e](https://github.com/yargs/yargs/commit/b774b5e)) -* **docs:** formalize existing callback argument to showHelp ([#1386](https://github.com/yargs/yargs/issues/1386)) ([d217764](https://github.com/yargs/yargs/commit/d217764)) - - -### Features - -* make it possible to merge configurations when extending other config. ([#1411](https://github.com/yargs/yargs/issues/1411)) ([5d7ad98](https://github.com/yargs/yargs/commit/5d7ad98)) - -## [14.0.0](https://github.com/yargs/yargs/compare/v13.3.0...v14.0.0) (2019-07-30) - - -### ⚠ BREAKING CHANGES - -* we now only officially support yargs.$0 parameter and discourage direct access to yargs.parsed -* previously to this fix methods like `yargs.getOptions()` contained the state of the last command to execute. -* do not allow additional positionals in strict mode - -### Bug Fixes - -* calling parse multiple times now appropriately maintains state ([#1137](https://github.com/yargs/yargs/issues/1137)) ([#1369](https://github.com/yargs/yargs/issues/1369)) ([026b151](https://github.com/yargs/yargs/commit/026b151)) -* prefer user supplied script name in usage ([#1383](https://github.com/yargs/yargs/issues/1383)) ([28c74b9](https://github.com/yargs/yargs/commit/28c74b9)) -* **deps:** use decamelize from npm instead of vendored copy ([#1377](https://github.com/yargs/yargs/issues/1377)) ([015eeb9](https://github.com/yargs/yargs/commit/015eeb9)) -* **examples:** fix usage-options.js to reflect current API ([#1375](https://github.com/yargs/yargs/issues/1375)) ([6e5b76b](https://github.com/yargs/yargs/commit/6e5b76b)) -* do not allow additional positionals in strict mode ([35d777c](https://github.com/yargs/yargs/commit/35d777c)) -* properties accessed on singleton now reflect current state of instance ([#1366](https://github.com/yargs/yargs/issues/1366)) ([409d35b](https://github.com/yargs/yargs/commit/409d35b)) -* tolerate null prototype for config objects with `extends` ([#1376](https://github.com/yargs/yargs/issues/1376)) ([3d26d11](https://github.com/yargs/yargs/commit/3d26d11)), closes [#1372](https://github.com/yargs/yargs/issues/1372) -* yargs.parsed now populated before returning, when yargs.parse() called with no args (#1382) ([e3981fd](https://github.com/yargs/yargs/commit/e3981fd)), closes [#1382](https://github.com/yargs/yargs/issues/1382) - -### Features - -* adds support for multiple epilog messages ([#1384](https://github.com/yargs/yargs/issues/1384)) ([07a5554](https://github.com/yargs/yargs/commit/07a5554)) -* allow completionCommand to be set via showCompletionScript ([#1385](https://github.com/yargs/yargs/issues/1385)) ([5562853](https://github.com/yargs/yargs/commit/5562853)) - -## [13.3.0](https://www.github.com/yargs/yargs/compare/v13.2.4...v13.3.0) (2019-06-10) - - -### Bug Fixes - -* **deps:** yargs-parser update addressing several parsing bugs ([#1357](https://www.github.com/yargs/yargs/issues/1357)) ([e230d5b](https://www.github.com/yargs/yargs/commit/e230d5b)) - - -### Features - -* **i18n:** swap out os-locale dependency for simple inline implementation ([#1356](https://www.github.com/yargs/yargs/issues/1356)) ([4dfa19b](https://www.github.com/yargs/yargs/commit/4dfa19b)) -* support defaultDescription for positional arguments ([812048c](https://www.github.com/yargs/yargs/commit/812048c)) - -### [13.2.4](https://github.com/yargs/yargs/compare/v13.2.3...v13.2.4) (2019-05-13) - - -### Bug Fixes - -* **i18n:** rename unclear 'implication failed' to 'missing dependent arguments' ([#1317](https://github.com/yargs/yargs/issues/1317)) ([bf46813](https://github.com/yargs/yargs/commit/bf46813)) - - - -### [13.2.3](https://github.com/yargs/yargs/compare/v13.2.2...v13.2.3) (2019-05-05) - - -### Bug Fixes - -* **deps:** upgrade cliui for compatibility with latest chalk. ([#1330](https://github.com/yargs/yargs/issues/1330)) ([b20db65](https://github.com/yargs/yargs/commit/b20db65)) -* address issues with dutch translation ([#1316](https://github.com/yargs/yargs/issues/1316)) ([0295132](https://github.com/yargs/yargs/commit/0295132)) - - -### Tests - -* accept differently formatted output ([#1327](https://github.com/yargs/yargs/issues/1327)) ([c294d1b](https://github.com/yargs/yargs/commit/c294d1b)) - - - -## [13.2.2](https://github.com/yargs/yargs/compare/v13.2.1...v13.2.2) (2019-03-06) - - - -## [13.2.1](https://github.com/yargs/yargs/compare/v13.2.0...v13.2.1) (2019-02-18) - - -### Bug Fixes - -* add zsh script to files array ([3180224](https://github.com/yargs/yargs/commit/3180224)) -* support options/sub-commands in zsh completion ([0a96394](https://github.com/yargs/yargs/commit/0a96394)) - - -# [13.2.0](https://github.com/yargs/yargs/compare/v13.1.0...v13.2.0) (2019-02-15) - - -### Features - -* zsh auto completion ([#1292](https://github.com/yargs/yargs/issues/1292)) ([16c5d25](https://github.com/yargs/yargs/commit/16c5d25)), closes [#1156](https://github.com/yargs/yargs/issues/1156) - - - -# [13.1.0](https://github.com/yargs/yargs/compare/v13.0.0...v13.1.0) (2019-02-12) - - -### Features - -* add applyBeforeValidation, for applying sync middleware before validation ([5be206a](https://github.com/yargs/yargs/commit/5be206a)) - - - - -# [13.0.0](https://github.com/yargs/yargs/compare/v12.0.5...v13.0.0) (2019-02-02) - - -### Bug Fixes - -* **deps:** Update os-locale to avoid security vulnerability ([#1270](https://github.com/yargs/yargs/issues/1270)) ([27bf739](https://github.com/yargs/yargs/commit/27bf739)) -* **validation:** Use the error as a message when none exists otherwise ([#1268](https://github.com/yargs/yargs/issues/1268)) ([0510fe6](https://github.com/yargs/yargs/commit/0510fe6)) -* better bash path completion ([#1272](https://github.com/yargs/yargs/issues/1272)) ([da75ea2](https://github.com/yargs/yargs/commit/da75ea2)) -* middleware added multiple times due to reference bug ([#1282](https://github.com/yargs/yargs/issues/1282)) ([64af518](https://github.com/yargs/yargs/commit/64af518)) - - -### Chores - -* ~drop Node 6 from testing matrix ([#1287](https://github.com/yargs/yargs/issues/1287)) ([ef16792](https://github.com/yargs/yargs/commit/ef16792))~ - * _opting to not drop Node 6 support until April, [see](https://github.com/nodejs/Release)._ -* update dependencies ([#1284](https://github.com/yargs/yargs/issues/1284)) ([f25de4f](https://github.com/yargs/yargs/commit/f25de4f)) - - -### Features - -* Add `.parserConfiguration()` method, deprecating package.json config ([#1262](https://github.com/yargs/yargs/issues/1262)) ([3c6869a](https://github.com/yargs/yargs/commit/3c6869a)) -* adds config option for sorting command output ([#1256](https://github.com/yargs/yargs/issues/1256)) ([6916ce9](https://github.com/yargs/yargs/commit/6916ce9)) -* options/positionals with leading '+' and '0' no longer parse as numbers ([#1286](https://github.com/yargs/yargs/issues/1286)) ([e9dc3aa](https://github.com/yargs/yargs/commit/e9dc3aa)) -* support promises in middleware ([f3a4e4f](https://github.com/yargs/yargs/commit/f3a4e4f)) - - -### BREAKING CHANGES - -* options with leading '+' or '0' now parse as strings -* dropping Node 6 which hits end of life in April 2019 -* see [yargs-parser@12.0.0 CHANGELOG](https://github.com/yargs/yargs-parser/blob/master/CHANGELOG.md#breaking-changes) -* we now warn if the yargs stanza package.json is used. - - - - -## [12.0.5](https://github.com/yargs/yargs/compare/v12.0.4...v12.0.5) (2018-11-19) - - -### Bug Fixes - -* allows camel-case, variadic arguments, and strict mode to be combined ([#1247](https://github.com/yargs/yargs/issues/1247)) ([eacc035](https://github.com/yargs/yargs/commit/eacc035)) - - - - -## [12.0.4](https://github.com/yargs/yargs/compare/v12.0.3...v12.0.4) (2018-11-10) - - -### Bug Fixes - -* don't load config when processing positionals ([5d0dc92](https://github.com/yargs/yargs/commit/5d0dc92)) - - - - -## [12.0.3](https://github.com/yargs/yargs/compare/v12.0.2...v12.0.3) (2018-10-06) - - -### Bug Fixes - -* $0 contains first arg in bundled electron apps ([#1206](https://github.com/yargs/yargs/issues/1206)) ([567820b](https://github.com/yargs/yargs/commit/567820b)) -* accept single function for middleware ([66fd6f7](https://github.com/yargs/yargs/commit/66fd6f7)), closes [#1214](https://github.com/yargs/yargs/issues/1214) [#1214](https://github.com/yargs/yargs/issues/1214) -* hide `hidden` options from help output even if they are in a group ([#1221](https://github.com/yargs/yargs/issues/1221)) ([da54028](https://github.com/yargs/yargs/commit/da54028)) -* improve Norwegian Bokmål translations ([#1208](https://github.com/yargs/yargs/issues/1208)) ([a458fa4](https://github.com/yargs/yargs/commit/a458fa4)) -* improve Norwegian Nynorsk translations ([#1207](https://github.com/yargs/yargs/issues/1207)) ([d422eb5](https://github.com/yargs/yargs/commit/d422eb5)) - - - - -## [12.0.2](https://github.com/yargs/yargs/compare/v12.0.1...v12.0.2) (2018-09-04) - - -### Bug Fixes - -* middleware should work regardless of when method is called ([664b265](https://github.com/yargs/yargs/commit/664b265)), closes [#1178](https://github.com/yargs/yargs/issues/1178) -* translation not working when using __ with a single parameter ([#1183](https://github.com/yargs/yargs/issues/1183)) ([f449aea](https://github.com/yargs/yargs/commit/f449aea)) -* upgrade os-locale to version that addresses license issue ([#1195](https://github.com/yargs/yargs/issues/1195)) ([efc0970](https://github.com/yargs/yargs/commit/efc0970)) - - - - -## [12.0.1](https://github.com/yargs/yargs/compare/v12.0.0...v12.0.1) (2018-06-29) - - - - -# [12.0.0](https://github.com/yargs/yargs/compare/v11.1.0...v12.0.0) (2018-06-26) - - -### Bug Fixes - -* .argv and .parse() now invoke identical code path ([#1126](https://github.com/yargs/yargs/issues/1126)) ([f13ebf4](https://github.com/yargs/yargs/commit/f13ebf4)) -* remove the trailing white spaces from the help output ([#1090](https://github.com/yargs/yargs/issues/1090)) ([3f0746c](https://github.com/yargs/yargs/commit/3f0746c)) -* **completion:** Avoid default command and recommendations during completion ([#1123](https://github.com/yargs/yargs/issues/1123)) ([036e7c5](https://github.com/yargs/yargs/commit/036e7c5)) - - -### Chores - -* test Node.js 6, 8 and 10 ([#1160](https://github.com/yargs/yargs/issues/1160)) ([84f9d2b](https://github.com/yargs/yargs/commit/84f9d2b)) -* upgrade to version of yargs-parser that does not populate value for unset boolean ([#1104](https://github.com/yargs/yargs/issues/1104)) ([d4705f4](https://github.com/yargs/yargs/commit/d4705f4)) - - -### Features - -* add support for global middleware, useful for shared tasks like metrics ([#1119](https://github.com/yargs/yargs/issues/1119)) ([9d71ac7](https://github.com/yargs/yargs/commit/9d71ac7)) -* allow setting scriptName $0 ([#1143](https://github.com/yargs/yargs/issues/1143)) ([a2f2eae](https://github.com/yargs/yargs/commit/a2f2eae)) -* remove `setPlaceholderKeys` ([#1105](https://github.com/yargs/yargs/issues/1105)) ([6ee2c82](https://github.com/yargs/yargs/commit/6ee2c82)) - - -### BREAKING CHANGES - -* Options absent from `argv` (not set via CLI argument) are now absent from the parsed result object rather than being set with `undefined` -* drop Node 4 from testing matrix, such that we'll gradually start drifting away from supporting Node 4. -* yargs-parser does not populate 'false' when boolean flag is not passed -* tests that assert against help output will need to be updated - - - - -# [11.1.0](https://github.com/yargs/yargs/compare/v11.0.0...v11.1.0) (2018-03-04) - - -### Bug Fixes - -* choose correct config directory when require.main does not exist ([#1056](https://github.com/yargs/yargs/issues/1056)) ([a04678c](https://github.com/yargs/yargs/commit/a04678c)) - - -### Features - -* allow hidden options to be displayed with --show-hidden ([#1061](https://github.com/yargs/yargs/issues/1061)) ([ea862ae](https://github.com/yargs/yargs/commit/ea862ae)) -* extend *.rc files in addition to json ([#1080](https://github.com/yargs/yargs/issues/1080)) ([11691a6](https://github.com/yargs/yargs/commit/11691a6)) - - - - -# [11.0.0](https://github.com/yargs/yargs/compare/v10.1.2...v11.0.0) (2018-01-22) - - -### Bug Fixes - -* Set implicit nargs=1 when type=number requiresArg=true ([#1050](https://github.com/yargs/yargs/issues/1050)) ([2b56812](https://github.com/yargs/yargs/commit/2b56812)) - - -### Features - -* requiresArg is now simply an alias for nargs(1) ([#1054](https://github.com/yargs/yargs/issues/1054)) ([a3ddacc](https://github.com/yargs/yargs/commit/a3ddacc)) - - -### BREAKING CHANGES - -* requiresArg now has significantly different error output, matching nargs. - -[Historical Versions](/docs/CHANGELOG-historical.md) diff --git a/reverse_engineering/node_modules/yargs/LICENSE b/reverse_engineering/node_modules/yargs/LICENSE deleted file mode 100644 index b0145ca..0000000 --- a/reverse_engineering/node_modules/yargs/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/yargs/README.md b/reverse_engineering/node_modules/yargs/README.md deleted file mode 100644 index 0db992b..0000000 --- a/reverse_engineering/node_modules/yargs/README.md +++ /dev/null @@ -1,140 +0,0 @@ -

- -

-

Yargs

-

- Yargs be a node.js library fer hearties tryin' ter parse optstrings -

- -
- -[![Build Status][travis-image]][travis-url] -[![NPM version][npm-image]][npm-url] -[![js-standard-style][standard-image]][standard-url] -[![Coverage][coverage-image]][coverage-url] -[![Conventional Commits][conventional-commits-image]][conventional-commits-url] -[![Slack][slack-image]][slack-url] - -## Description : -Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. - -It gives you: - -* commands and (grouped) options (`my-program.js serve --port=5000`). -* a dynamically generated help menu based on your arguments. - -> - -* bash-completion shortcuts for commands and options. -* and [tons more](/docs/api.md). - -## Installation - -Stable version: -```bash -npm i yargs -``` - -Bleeding edge version with the most recent features: -```bash -npm i yargs@next -``` - -## Usage : - -### Simple Example - -```javascript -#!/usr/bin/env node -const {argv} = require('yargs') - -if (argv.ships > 3 && argv.distance < 53.5) { - console.log('Plunder more riffiwobbles!') -} else { - console.log('Retreat from the xupptumblers!') -} -``` - -```bash -$ ./plunder.js --ships=4 --distance=22 -Plunder more riffiwobbles! - -$ ./plunder.js --ships 12 --distance 98.7 -Retreat from the xupptumblers! -``` - -### Complex Example - -```javascript -#!/usr/bin/env node -require('yargs') // eslint-disable-line - .command('serve [port]', 'start the server', (yargs) => { - yargs - .positional('port', { - describe: 'port to bind on', - default: 5000 - }) - }, (argv) => { - if (argv.verbose) console.info(`start server on :${argv.port}`) - serve(argv.port) - }) - .option('verbose', { - alias: 'v', - type: 'boolean', - description: 'Run with verbose logging' - }) - .argv -``` - -Run the example above with `--help` to see the help for the application. - -## TypeScript - -yargs has type definitions at [@types/yargs][type-definitions]. - -``` -npm i @types/yargs --save-dev -``` - -See usage examples in [docs](/docs/typescript.md). - -## Webpack - -See usage examples of yargs with webpack in [docs](/docs/webpack.md). - -## Community : - -Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). - -## Documentation : - -### Table of Contents - -* [Yargs' API](/docs/api.md) -* [Examples](/docs/examples.md) -* [Parsing Tricks](/docs/tricks.md) - * [Stop the Parser](/docs/tricks.md#stop) - * [Negating Boolean Arguments](/docs/tricks.md#negate) - * [Numbers](/docs/tricks.md#numbers) - * [Arrays](/docs/tricks.md#arrays) - * [Objects](/docs/tricks.md#objects) - * [Quotes](/docs/tricks.md#quotes) -* [Advanced Topics](/docs/advanced.md) - * [Composing Your App Using Commands](/docs/advanced.md#commands) - * [Building Configurable CLI Apps](/docs/advanced.md#configuration) - * [Customizing Yargs' Parser](/docs/advanced.md#customizing) -* [Contributing](/contributing.md) - -[travis-url]: https://travis-ci.org/yargs/yargs -[travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg -[npm-url]: https://www.npmjs.com/package/yargs -[npm-image]: https://img.shields.io/npm/v/yargs.svg -[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg -[standard-url]: http://standardjs.com/ -[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg -[conventional-commits-url]: https://conventionalcommits.org/ -[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg -[slack-url]: http://devtoolscommunity.herokuapp.com -[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs -[coverage-image]: https://img.shields.io/nycrc/yargs/yargs -[coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc diff --git a/reverse_engineering/node_modules/yargs/build/lib/apply-extends.d.ts b/reverse_engineering/node_modules/yargs/build/lib/apply-extends.d.ts deleted file mode 100644 index 5a9aca7..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/apply-extends.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Dictionary } from './common-types'; -export declare function applyExtends(config: Dictionary, cwd: string, mergeExtends?: boolean): Dictionary; diff --git a/reverse_engineering/node_modules/yargs/build/lib/apply-extends.js b/reverse_engineering/node_modules/yargs/build/lib/apply-extends.js deleted file mode 100644 index 005734a..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/apply-extends.js +++ /dev/null @@ -1,65 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.applyExtends = void 0; -const fs = require("fs"); -const path = require("path"); -const yerror_1 = require("./yerror"); -let previouslyVisitedConfigs = []; -function checkForCircularExtends(cfgPath) { - if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { - throw new yerror_1.YError(`Circular extended configurations: '${cfgPath}'.`); - } -} -function getPathToDefaultConfig(cwd, pathToExtend) { - return path.resolve(cwd, pathToExtend); -} -function mergeDeep(config1, config2) { - const target = {}; - function isObject(obj) { - return obj && typeof obj === 'object' && !Array.isArray(obj); - } - Object.assign(target, config1); - for (const key of Object.keys(config2)) { - if (isObject(config2[key]) && isObject(target[key])) { - target[key] = mergeDeep(config1[key], config2[key]); - } - else { - target[key] = config2[key]; - } - } - return target; -} -function applyExtends(config, cwd, mergeExtends = false) { - let defaultConfig = {}; - if (Object.prototype.hasOwnProperty.call(config, 'extends')) { - if (typeof config.extends !== 'string') - return defaultConfig; - const isPath = /\.json|\..*rc$/.test(config.extends); - let pathToDefault = null; - if (!isPath) { - try { - pathToDefault = require.resolve(config.extends); - } - catch (err) { - // most likely this simply isn't a module. - } - } - else { - pathToDefault = getPathToDefaultConfig(cwd, config.extends); - } - // maybe the module uses key for some other reason, - // err on side of caution. - if (!pathToDefault && !isPath) - return config; - if (!pathToDefault) - throw new yerror_1.YError(`Unable to find extended config '${config.extends}' in '${cwd}'.`); - checkForCircularExtends(pathToDefault); - previouslyVisitedConfigs.push(pathToDefault); - defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends); - delete config.extends; - defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault), mergeExtends); - } - previouslyVisitedConfigs = []; - return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config); -} -exports.applyExtends = applyExtends; diff --git a/reverse_engineering/node_modules/yargs/build/lib/argsert.d.ts b/reverse_engineering/node_modules/yargs/build/lib/argsert.d.ts deleted file mode 100644 index 6f7a83f..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/argsert.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare function argsert(callerArguments: any[], length?: number): void; -export declare function argsert(expected: string, callerArguments: any[], length?: number): void; diff --git a/reverse_engineering/node_modules/yargs/build/lib/argsert.js b/reverse_engineering/node_modules/yargs/build/lib/argsert.js deleted file mode 100644 index 40cb091..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/argsert.js +++ /dev/null @@ -1,65 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.argsert = void 0; -const yerror_1 = require("./yerror"); -const parse_command_1 = require("./parse-command"); -const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; -function argsert(arg1, arg2, arg3) { - function parseArgs() { - return typeof arg1 === 'object' - ? [{ demanded: [], optional: [] }, arg1, arg2] - : [parse_command_1.parseCommand(`cmd ${arg1}`), arg2, arg3]; - } - // TODO: should this eventually raise an exception. - try { - // preface the argument description with "cmd", so - // that we can run it through yargs' command parser. - let position = 0; - let [parsed, callerArguments, length] = parseArgs(); - const args = [].slice.call(callerArguments); - while (args.length && args[args.length - 1] === undefined) - args.pop(); - length = length || args.length; - if (length < parsed.demanded.length) { - throw new yerror_1.YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); - } - const totalCommands = parsed.demanded.length + parsed.optional.length; - if (length > totalCommands) { - throw new yerror_1.YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); - } - parsed.demanded.forEach((demanded) => { - const arg = args.shift(); - const observedType = guessType(arg); - const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); - if (matchingTypes.length === 0) - argumentTypeError(observedType, demanded.cmd, position); - position += 1; - }); - parsed.optional.forEach((optional) => { - if (args.length === 0) - return; - const arg = args.shift(); - const observedType = guessType(arg); - const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); - if (matchingTypes.length === 0) - argumentTypeError(observedType, optional.cmd, position); - position += 1; - }); - } - catch (err) { - console.warn(err.stack); - } -} -exports.argsert = argsert; -function guessType(arg) { - if (Array.isArray(arg)) { - return 'array'; - } - else if (arg === null) { - return 'null'; - } - return typeof arg; -} -function argumentTypeError(observedType, allowedTypes, position) { - throw new yerror_1.YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); -} diff --git a/reverse_engineering/node_modules/yargs/build/lib/command.d.ts b/reverse_engineering/node_modules/yargs/build/lib/command.d.ts deleted file mode 100644 index 9db6ab5..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/command.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/// -import { Dictionary } from './common-types'; -import { Middleware } from './middleware'; -import { Positional } from './parse-command'; -import { RequireDirectoryOptions } from 'require-directory'; -import { UsageInstance } from './usage'; -import { ValidationInstance } from './validation'; -import { YargsInstance, Options, OptionDefinition, Context, Arguments, DetailedArguments } from './yargs'; -export declare function command(yargs: YargsInstance, usage: UsageInstance, validation: ValidationInstance, globalMiddleware?: Middleware[]): CommandInstance; -/** Instance of the command module. */ -export interface CommandInstance { - addDirectory(dir: string, context: Context, req: NodeRequireFunction, callerFile: string, opts?: RequireDirectoryOptions): void; - addHandler(handler: CommandHandlerDefinition): void; - addHandler(cmd: string | string[], description: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, commandMiddleware?: Middleware[], deprecated?: boolean): void; - cmdToParseOptions(cmdString: string): Positionals; - freeze(): void; - getCommandHandlers(): Dictionary; - getCommands(): string[]; - hasDefaultCommand(): boolean; - reset(): CommandInstance; - runCommand(command: string | null, yargs: YargsInstance, parsed: DetailedArguments, commandIndex?: number): Arguments | Promise; - runDefaultBuilderOn(yargs: YargsInstance): void; - unfreeze(): void; -} -export interface CommandHandlerDefinition extends Partial> { - aliases?: string[]; - builder?: CommandBuilder | CommandBuilderDefinition; - command?: string | string[]; - desc?: CommandHandler['description']; - describe?: CommandHandler['description']; -} -export declare function isCommandHandlerDefinition(cmd: string | string[] | CommandHandlerDefinition): cmd is CommandHandlerDefinition; -export interface CommandBuilderDefinition { - builder?: CommandBuilder; - deprecated?: boolean; - handler: CommandHandlerCallback; - middlewares?: Middleware[]; -} -export declare function isCommandBuilderDefinition(builder?: CommandBuilder | CommandBuilderDefinition): builder is CommandBuilderDefinition; -export interface CommandHandlerCallback { - (argv: Arguments): any; -} -export interface CommandHandler { - builder: CommandBuilder; - demanded: Positional[]; - deprecated?: boolean; - description?: string | false; - handler: CommandHandlerCallback; - middlewares: Middleware[]; - optional: Positional[]; - original: string; -} -export declare type CommandBuilder = CommandBuilderCallback | Dictionary; -interface CommandBuilderCallback { - (y: YargsInstance): YargsInstance | void; -} -export declare function isCommandBuilderCallback(builder: CommandBuilder): builder is CommandBuilderCallback; -interface Positionals extends Pick { - demand: Dictionary; -} -export interface FinishCommandHandler { - (handlerResult: any): any; -} -export {}; diff --git a/reverse_engineering/node_modules/yargs/build/lib/command.js b/reverse_engineering/node_modules/yargs/build/lib/command.js deleted file mode 100644 index d90c455..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/command.js +++ /dev/null @@ -1,416 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isCommandBuilderCallback = exports.isCommandBuilderDefinition = exports.isCommandHandlerDefinition = exports.command = void 0; -const common_types_1 = require("./common-types"); -const is_promise_1 = require("./is-promise"); -const middleware_1 = require("./middleware"); -const parse_command_1 = require("./parse-command"); -const path = require("path"); -const util_1 = require("util"); -const yargs_1 = require("./yargs"); -const requireDirectory = require("require-directory"); -const whichModule = require("which-module"); -const Parser = require("yargs-parser"); -const DEFAULT_MARKER = /(^\*)|(^\$0)/; -// handles parsing positional arguments, -// and populating argv with said positional -// arguments. -function command(yargs, usage, validation, globalMiddleware = []) { - const self = {}; - let handlers = {}; - let aliasMap = {}; - let defaultCommand; - self.addHandler = function addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { - let aliases = []; - const middlewares = middleware_1.commandMiddlewareFactory(commandMiddleware); - handler = handler || (() => { }); - if (Array.isArray(cmd)) { - aliases = cmd.slice(1); - cmd = cmd[0]; - } - else if (isCommandHandlerDefinition(cmd)) { - let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd); - if (cmd.aliases) - command = [].concat(command).concat(cmd.aliases); - self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); - return; - } - // allow a module to be provided instead of separate builder and handler - if (isCommandBuilderDefinition(builder)) { - self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); - return; - } - // parse positionals out of cmd string - const parsedCommand = parse_command_1.parseCommand(cmd); - // remove positional args from aliases only - aliases = aliases.map(alias => parse_command_1.parseCommand(alias).cmd); - // check for default and filter out '*'' - let isDefault = false; - const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => { - if (DEFAULT_MARKER.test(c)) { - isDefault = true; - return false; - } - return true; - }); - // standardize on $0 for default command. - if (parsedAliases.length === 0 && isDefault) - parsedAliases.push('$0'); - // shift cmd and aliases after filtering out '*' - if (isDefault) { - parsedCommand.cmd = parsedAliases[0]; - aliases = parsedAliases.slice(1); - cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); - } - // populate aliasMap - aliases.forEach((alias) => { - aliasMap[alias] = parsedCommand.cmd; - }); - if (description !== false) { - usage.command(cmd, description, isDefault, aliases, deprecated); - } - handlers[parsedCommand.cmd] = { - original: cmd, - description, - handler, - builder: builder || {}, - middlewares, - deprecated, - demanded: parsedCommand.demanded, - optional: parsedCommand.optional - }; - if (isDefault) - defaultCommand = handlers[parsedCommand.cmd]; - }; - self.addDirectory = function addDirectory(dir, context, req, callerFile, opts) { - opts = opts || {}; - // disable recursion to support nested directories of subcommands - if (typeof opts.recurse !== 'boolean') - opts.recurse = false; - // exclude 'json', 'coffee' from require-directory defaults - if (!Array.isArray(opts.extensions)) - opts.extensions = ['js']; - // allow consumer to define their own visitor function - const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o; - // call addHandler via visitor function - opts.visit = function visit(obj, joined, filename) { - const visited = parentVisit(obj, joined, filename); - // allow consumer to skip modules with their own visitor - if (visited) { - // check for cyclic reference - // each command file path should only be seen once per execution - if (~context.files.indexOf(joined)) - return visited; - // keep track of visited files in context.files - context.files.push(joined); - self.addHandler(visited); - } - return visited; - }; - requireDirectory({ require: req, filename: callerFile }, dir, opts); - }; - // lookup module object from require()d command and derive name - // if module was not require()d and no name given, throw error - function moduleName(obj) { - const mod = whichModule(obj); - if (!mod) - throw new Error(`No command name given for module: ${util_1.inspect(obj)}`); - return commandFromFilename(mod.filename); - } - // derive command name from filename - function commandFromFilename(filename) { - return path.basename(filename, path.extname(filename)); - } - function extractDesc({ describe, description, desc }) { - for (const test of [describe, description, desc]) { - if (typeof test === 'string' || test === false) - return test; - common_types_1.assertNotStrictEqual(test, true); - } - return false; - } - self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap)); - self.getCommandHandlers = () => handlers; - self.hasDefaultCommand = () => !!defaultCommand; - self.runCommand = function runCommand(command, yargs, parsed, commandIndex) { - let aliases = parsed.aliases; - const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand; - const currentContext = yargs.getContext(); - let numFiles = currentContext.files.length; - const parentCommands = currentContext.commands.slice(); - // what does yargs look like after the builder is run? - let innerArgv = parsed.argv; - let positionalMap = {}; - if (command) { - currentContext.commands.push(command); - currentContext.fullCommands.push(commandHandler.original); - } - const builder = commandHandler.builder; - if (isCommandBuilderCallback(builder)) { - // a function can be provided, which builds - // up a yargs chain and possibly returns it. - const builderOutput = builder(yargs.reset(parsed.aliases)); - const innerYargs = yargs_1.isYargsInstance(builderOutput) ? builderOutput : yargs; - if (shouldUpdateUsage(innerYargs)) { - innerYargs.getUsageInstance().usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); - } - innerArgv = innerYargs._parseArgs(null, null, true, commandIndex); - aliases = innerYargs.parsed.aliases; - } - else if (isCommandBuilderOptionDefinitions(builder)) { - // as a short hand, an object can instead be provided, specifying - // the options that a command takes. - const innerYargs = yargs.reset(parsed.aliases); - if (shouldUpdateUsage(innerYargs)) { - innerYargs.getUsageInstance().usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); - } - Object.keys(commandHandler.builder).forEach((key) => { - innerYargs.option(key, builder[key]); - }); - innerArgv = innerYargs._parseArgs(null, null, true, commandIndex); - aliases = innerYargs.parsed.aliases; - } - if (!yargs._hasOutput()) { - positionalMap = populatePositionals(commandHandler, innerArgv, currentContext); - } - const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares); - middleware_1.applyMiddleware(innerArgv, yargs, middlewares, true); - // we apply validation post-hoc, so that custom - // checks get passed populated positional arguments. - if (!yargs._hasOutput()) { - yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error, !command); - } - if (commandHandler.handler && !yargs._hasOutput()) { - yargs._setHasOutput(); - // to simplify the parsing of positionals in commands, - // we temporarily populate '--' rather than _, with arguments - const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; - if (!populateDoubleDash) - yargs._copyDoubleDash(innerArgv); - innerArgv = middleware_1.applyMiddleware(innerArgv, yargs, middlewares, false); - let handlerResult; - if (is_promise_1.isPromise(innerArgv)) { - handlerResult = innerArgv.then(argv => commandHandler.handler(argv)); - } - else { - handlerResult = commandHandler.handler(innerArgv); - } - const handlerFinishCommand = yargs.getHandlerFinishCommand(); - if (is_promise_1.isPromise(handlerResult)) { - yargs.getUsageInstance().cacheHelpMessage(); - handlerResult - .then(value => { - if (handlerFinishCommand) { - handlerFinishCommand(value); - } - }) - .catch(error => { - try { - yargs.getUsageInstance().fail(null, error); - } - catch (err) { - // fail's throwing would cause an unhandled rejection. - } - }) - .then(() => { - yargs.getUsageInstance().clearCachedHelpMessage(); - }); - } - else { - if (handlerFinishCommand) { - handlerFinishCommand(handlerResult); - } - } - } - if (command) { - currentContext.commands.pop(); - currentContext.fullCommands.pop(); - } - numFiles = currentContext.files.length - numFiles; - if (numFiles > 0) - currentContext.files.splice(numFiles * -1, numFiles); - return innerArgv; - }; - function shouldUpdateUsage(yargs) { - return !yargs.getUsageInstance().getUsageDisabled() && - yargs.getUsageInstance().getUsage().length === 0; - } - function usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { - const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original; - const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c); }); - pc.push(c); - return `$0 ${pc.join(' ')}`; - } - self.runDefaultBuilderOn = function (yargs) { - common_types_1.assertNotStrictEqual(defaultCommand, undefined); - if (shouldUpdateUsage(yargs)) { - // build the root-level command string from the default string. - const commandString = DEFAULT_MARKER.test(defaultCommand.original) - ? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); - yargs.getUsageInstance().usage(commandString, defaultCommand.description); - } - const builder = defaultCommand.builder; - if (isCommandBuilderCallback(builder)) { - builder(yargs); - } - else { - Object.keys(builder).forEach((key) => { - yargs.option(key, builder[key]); - }); - } - }; - // transcribe all positional arguments "command [apple]" - // onto argv. - function populatePositionals(commandHandler, argv, context) { - argv._ = argv._.slice(context.commands.length); // nuke the current commands - const demanded = commandHandler.demanded.slice(0); - const optional = commandHandler.optional.slice(0); - const positionalMap = {}; - validation.positionalCount(demanded.length, argv._.length); - while (demanded.length) { - const demand = demanded.shift(); - populatePositional(demand, argv, positionalMap); - } - while (optional.length) { - const maybe = optional.shift(); - populatePositional(maybe, argv, positionalMap); - } - argv._ = context.commands.concat(argv._); - postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original)); - return positionalMap; - } - function populatePositional(positional, argv, positionalMap) { - const cmd = positional.cmd[0]; - if (positional.variadic) { - positionalMap[cmd] = argv._.splice(0).map(String); - } - else { - if (argv._.length) - positionalMap[cmd] = [String(argv._.shift())]; - } - } - // we run yargs-parser against the positional arguments - // applying the same parsing logic used for flags. - function postProcessPositionals(argv, positionalMap, parseOptions) { - // combine the parsing hints we've inferred from the command - // string with explicitly configured parsing hints. - const options = Object.assign({}, yargs.getOptions()); - options.default = Object.assign(parseOptions.default, options.default); - for (const key of Object.keys(parseOptions.alias)) { - options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); - } - options.array = options.array.concat(parseOptions.array); - delete options.config; // don't load config when processing positionals. - const unparsed = []; - Object.keys(positionalMap).forEach((key) => { - positionalMap[key].map((value) => { - if (options.configuration['unknown-options-as-args']) - options.key[key] = true; - unparsed.push(`--${key}`); - unparsed.push(value); - }); - }); - // short-circuit parse. - if (!unparsed.length) - return; - const config = Object.assign({}, options.configuration, { - 'populate--': true - }); - const parsed = Parser.detailed(unparsed, Object.assign({}, options, { - configuration: config - })); - if (parsed.error) { - yargs.getUsageInstance().fail(parsed.error.message, parsed.error); - } - else { - // only copy over positional keys (don't overwrite - // flag arguments that were already parsed). - const positionalKeys = Object.keys(positionalMap); - Object.keys(positionalMap).forEach((key) => { - positionalKeys.push(...parsed.aliases[key]); - }); - Object.keys(parsed.argv).forEach((key) => { - if (positionalKeys.indexOf(key) !== -1) { - // any new aliases need to be placed in positionalMap, which - // is used for validation. - if (!positionalMap[key]) - positionalMap[key] = parsed.argv[key]; - argv[key] = parsed.argv[key]; - } - }); - } - } - self.cmdToParseOptions = function (cmdString) { - const parseOptions = { - array: [], - default: {}, - alias: {}, - demand: {} - }; - const parsed = parse_command_1.parseCommand(cmdString); - parsed.demanded.forEach((d) => { - const [cmd, ...aliases] = d.cmd; - if (d.variadic) { - parseOptions.array.push(cmd); - parseOptions.default[cmd] = []; - } - parseOptions.alias[cmd] = aliases; - parseOptions.demand[cmd] = true; - }); - parsed.optional.forEach((o) => { - const [cmd, ...aliases] = o.cmd; - if (o.variadic) { - parseOptions.array.push(cmd); - parseOptions.default[cmd] = []; - } - parseOptions.alias[cmd] = aliases; - }); - return parseOptions; - }; - self.reset = () => { - handlers = {}; - aliasMap = {}; - defaultCommand = undefined; - return self; - }; - // used by yargs.parse() to freeze - // the state of commands such that - // we can apply .parse() multiple times - // with the same yargs instance. - const frozens = []; - self.freeze = () => { - frozens.push({ - handlers, - aliasMap, - defaultCommand - }); - }; - self.unfreeze = () => { - const frozen = frozens.pop(); - common_types_1.assertNotStrictEqual(frozen, undefined); - ({ - handlers, - aliasMap, - defaultCommand - } = frozen); - }; - return self; -} -exports.command = command; -function isCommandHandlerDefinition(cmd) { - return typeof cmd === 'object'; -} -exports.isCommandHandlerDefinition = isCommandHandlerDefinition; -function isCommandBuilderDefinition(builder) { - return typeof builder === 'object' && - !!builder.builder && - typeof builder.handler === 'function'; -} -exports.isCommandBuilderDefinition = isCommandBuilderDefinition; -function isCommandBuilderCallback(builder) { - return typeof builder === 'function'; -} -exports.isCommandBuilderCallback = isCommandBuilderCallback; -function isCommandBuilderOptionDefinitions(builder) { - return typeof builder === 'object'; -} diff --git a/reverse_engineering/node_modules/yargs/build/lib/common-types.d.ts b/reverse_engineering/node_modules/yargs/build/lib/common-types.d.ts deleted file mode 100644 index f83c0dd..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/common-types.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * An object whose all properties have the same type. - */ -export declare type Dictionary = { - [key: string]: T; -}; -/** - * Returns the keys of T that match Dictionary and are not arrays. - */ -export declare type DictionaryKeyof = Exclude>, KeyOf>; -/** - * Returns the keys of T that match U. - */ -export declare type KeyOf = Exclude<{ - [K in keyof T]: T[K] extends U ? K : never; -}[keyof T], undefined>; -/** - * An array whose first element is not undefined. - */ -export declare type NotEmptyArray = [T, ...T[]]; -/** - * Returns the type of a Dictionary or array values. - */ -export declare type ValueOf = T extends (infer U)[] ? U : T[keyof T]; -/** - * Typing wrapper around assert.notStrictEqual() - */ -export declare function assertNotStrictEqual(actual: T | N, expected: N, message?: string | Error): asserts actual is Exclude; -/** - * Asserts actual is a single key, not a key array or a key map. - */ -export declare function assertSingleKey(actual: string | string[] | Dictionary): asserts actual is string; -/** - * Typing wrapper around Object.keys() - */ -export declare function objectKeys(object: T): (keyof T)[]; diff --git a/reverse_engineering/node_modules/yargs/build/lib/common-types.js b/reverse_engineering/node_modules/yargs/build/lib/common-types.js deleted file mode 100644 index 3064cbf..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/common-types.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.objectKeys = exports.assertSingleKey = exports.assertNotStrictEqual = void 0; -const assert_1 = require("assert"); -/** - * Typing wrapper around assert.notStrictEqual() - */ -function assertNotStrictEqual(actual, expected, message) { - assert_1.notStrictEqual(actual, expected, message); -} -exports.assertNotStrictEqual = assertNotStrictEqual; -/** - * Asserts actual is a single key, not a key array or a key map. - */ -function assertSingleKey(actual) { - assert_1.strictEqual(typeof actual, 'string'); -} -exports.assertSingleKey = assertSingleKey; -/** - * Typing wrapper around Object.keys() - */ -function objectKeys(object) { - return Object.keys(object); -} -exports.objectKeys = objectKeys; diff --git a/reverse_engineering/node_modules/yargs/build/lib/completion-templates.d.ts b/reverse_engineering/node_modules/yargs/build/lib/completion-templates.d.ts deleted file mode 100644 index 67bcd30..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/completion-templates.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const completionShTemplate = "###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n args=(\"${COMP_WORDS[@]}\")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions \"${args[@]}\")\n\n COMPREPLY=( $(compgen -W \"${type_list}\" -- ${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ ${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o default -F _yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n"; -export declare const completionZshTemplate = "###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$'\n' reply=($(COMP_CWORD=\"$((CURRENT-1))\" COMP_LINE=\"$BUFFER\" COMP_POINT=\"$CURSOR\" {{app_path}} --get-yargs-completions \"${words[@]}\"))\n IFS=$si\n _describe 'values' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n"; diff --git a/reverse_engineering/node_modules/yargs/build/lib/completion-templates.js b/reverse_engineering/node_modules/yargs/build/lib/completion-templates.js deleted file mode 100644 index 3ee0e06..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/completion-templates.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.completionZshTemplate = exports.completionShTemplate = void 0; -exports.completionShTemplate = `###-begin-{{app_name}}-completions-### -# -# yargs command completion script -# -# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc -# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. -# -_yargs_completions() -{ - local cur_word args type_list - - cur_word="\${COMP_WORDS[COMP_CWORD]}" - args=("\${COMP_WORDS[@]}") - - # ask yargs to generate completions. - type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") - - COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) - - # if no match was found, fall back to filename completion - if [ \${#COMPREPLY[@]} -eq 0 ]; then - COMPREPLY=() - fi - - return 0 -} -complete -o default -F _yargs_completions {{app_name}} -###-end-{{app_name}}-completions-### -`; -exports.completionZshTemplate = `###-begin-{{app_name}}-completions-### -# -# yargs command completion script -# -# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc -# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX. -# -_{{app_name}}_yargs_completions() -{ - local reply - local si=$IFS - IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) - IFS=$si - _describe 'values' reply -} -compdef _{{app_name}}_yargs_completions {{app_name}} -###-end-{{app_name}}-completions-### -`; diff --git a/reverse_engineering/node_modules/yargs/build/lib/completion.d.ts b/reverse_engineering/node_modules/yargs/build/lib/completion.d.ts deleted file mode 100644 index 176a91b..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/completion.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { CommandInstance } from './command'; -import { UsageInstance } from './usage'; -import { YargsInstance } from './yargs'; -import { Arguments, DetailedArguments } from 'yargs-parser'; -export declare function completion(yargs: YargsInstance, usage: UsageInstance, command: CommandInstance): CompletionInstance; -/** Instance of the completion module. */ -export interface CompletionInstance { - completionKey: string; - generateCompletionScript($0: string, cmd: string): string; - getCompletion(args: string[], done: (completions: string[]) => any): any; - registerFunction(fn: CompletionFunction): void; - setParsed(parsed: DetailedArguments): void; -} -export declare type CompletionFunction = SyncCompletionFunction | AsyncCompletionFunction; -interface SyncCompletionFunction { - (current: string, argv: Arguments): string[] | Promise; -} -interface AsyncCompletionFunction { - (current: string, argv: Arguments, done: (completions: string[]) => any): any; -} -export {}; diff --git a/reverse_engineering/node_modules/yargs/build/lib/completion.js b/reverse_engineering/node_modules/yargs/build/lib/completion.js deleted file mode 100644 index d65925a..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/completion.js +++ /dev/null @@ -1,135 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.completion = void 0; -const command_1 = require("./command"); -const templates = require("./completion-templates"); -const is_promise_1 = require("./is-promise"); -const parse_command_1 = require("./parse-command"); -const path = require("path"); -const common_types_1 = require("./common-types"); -// add bash completions to your -// yargs-powered applications. -function completion(yargs, usage, command) { - const self = { - completionKey: 'get-yargs-completions' - }; - let aliases; - self.setParsed = function setParsed(parsed) { - aliases = parsed.aliases; - }; - const zshShell = (process.env.SHELL && process.env.SHELL.indexOf('zsh') !== -1) || - (process.env.ZSH_NAME && process.env.ZSH_NAME.indexOf('zsh') !== -1); - // get a list of completion commands. - // 'args' is the array of strings from the line to be completed - self.getCompletion = function getCompletion(args, done) { - const completions = []; - const current = args.length ? args[args.length - 1] : ''; - const argv = yargs.parse(args, true); - const parentCommands = yargs.getContext().commands; - // a custom completion function can be provided - // to completion(). - function runCompletionFunction(argv) { - common_types_1.assertNotStrictEqual(completionFunction, null); - if (isSyncCompletionFunction(completionFunction)) { - const result = completionFunction(current, argv); - // promise based completion function. - if (is_promise_1.isPromise(result)) { - return result.then((list) => { - process.nextTick(() => { done(list); }); - }).catch((err) => { - process.nextTick(() => { throw err; }); - }); - } - // synchronous completion function. - return done(result); - } - else { - // asynchronous completion function - return completionFunction(current, argv, (completions) => { - done(completions); - }); - } - } - if (completionFunction) { - return is_promise_1.isPromise(argv) ? argv.then(runCompletionFunction) : runCompletionFunction(argv); - } - const handlers = command.getCommandHandlers(); - for (let i = 0, ii = args.length; i < ii; ++i) { - if (handlers[args[i]] && handlers[args[i]].builder) { - const builder = handlers[args[i]].builder; - if (command_1.isCommandBuilderCallback(builder)) { - const y = yargs.reset(); - builder(y); - return y.argv; - } - } - } - if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current) { - usage.getCommands().forEach((usageCommand) => { - const commandName = parse_command_1.parseCommand(usageCommand[0]).cmd; - if (args.indexOf(commandName) === -1) { - if (!zshShell) { - completions.push(commandName); - } - else { - const desc = usageCommand[1] || ''; - completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); - } - } - }); - } - if (current.match(/^-/) || (current === '' && completions.length === 0)) { - const descs = usage.getDescriptions(); - const options = yargs.getOptions(); - Object.keys(options.key).forEach((key) => { - const negable = !!options.configuration['boolean-negation'] && options.boolean.includes(key); - // If the key and its aliases aren't in 'args', add the key to 'completions' - let keyAndAliases = [key].concat(aliases[key] || []); - if (negable) - keyAndAliases = keyAndAliases.concat(keyAndAliases.map(key => `no-${key}`)); - function completeOptionKey(key) { - const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1); - if (notInArgs) { - const startsByTwoDashes = (s) => /^--/.test(s); - const isShortOption = (s) => /^[^0-9]$/.test(s); - const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; - if (!zshShell) { - completions.push(dashes + key); - } - else { - const desc = descs[key] || ''; - completions.push(dashes + `${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`); - } - } - } - completeOptionKey(key); - if (negable && !!options.default[key]) - completeOptionKey(`no-${key}`); - }); - } - done(completions); - }; - // generate the completion script to add to your .bashrc. - self.generateCompletionScript = function generateCompletionScript($0, cmd) { - let script = zshShell ? templates.completionZshTemplate : templates.completionShTemplate; - const name = path.basename($0); - // add ./to applications not yet installed as bin. - if ($0.match(/\.js$/)) - $0 = `./${$0}`; - script = script.replace(/{{app_name}}/g, name); - script = script.replace(/{{completion_command}}/g, cmd); - return script.replace(/{{app_path}}/g, $0); - }; - // register a function to perform your own custom - // completions., this function can be either - // synchrnous or asynchronous. - let completionFunction = null; - self.registerFunction = (fn) => { - completionFunction = fn; - }; - return self; -} -exports.completion = completion; -function isSyncCompletionFunction(completionFunction) { - return completionFunction.length < 3; -} diff --git a/reverse_engineering/node_modules/yargs/build/lib/is-promise.d.ts b/reverse_engineering/node_modules/yargs/build/lib/is-promise.d.ts deleted file mode 100644 index 19b5566..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/is-promise.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function isPromise(maybePromise: T | Promise): maybePromise is Promise; diff --git a/reverse_engineering/node_modules/yargs/build/lib/is-promise.js b/reverse_engineering/node_modules/yargs/build/lib/is-promise.js deleted file mode 100644 index c24f9a8..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/is-promise.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isPromise = void 0; -function isPromise(maybePromise) { - return !!maybePromise && - !!maybePromise.then && - (typeof maybePromise.then === 'function'); -} -exports.isPromise = isPromise; diff --git a/reverse_engineering/node_modules/yargs/build/lib/levenshtein.d.ts b/reverse_engineering/node_modules/yargs/build/lib/levenshtein.d.ts deleted file mode 100644 index 08b6b7f..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/levenshtein.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function levenshtein(a: string, b: string): number; diff --git a/reverse_engineering/node_modules/yargs/build/lib/levenshtein.js b/reverse_engineering/node_modules/yargs/build/lib/levenshtein.js deleted file mode 100644 index 84c0831..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/levenshtein.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -/* -Copyright (c) 2011 Andrei Mackenzie - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.levenshtein = void 0; -// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed. -// gist, which can be found here: https://gist.github.com/andrei-m/982927 -// Compute the edit distance between the two given strings -function levenshtein(a, b) { - if (a.length === 0) - return b.length; - if (b.length === 0) - return a.length; - const matrix = []; - // increment along the first column of each row - let i; - for (i = 0; i <= b.length; i++) { - matrix[i] = [i]; - } - // increment each column in the first row - let j; - for (j = 0; j <= a.length; j++) { - matrix[0][j] = j; - } - // Fill in the rest of the matrix - for (i = 1; i <= b.length; i++) { - for (j = 1; j <= a.length; j++) { - if (b.charAt(i - 1) === a.charAt(j - 1)) { - matrix[i][j] = matrix[i - 1][j - 1]; - } - else { - matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution - Math.min(matrix[i][j - 1] + 1, // insertion - matrix[i - 1][j] + 1)); // deletion - } - } - } - return matrix[b.length][a.length]; -} -exports.levenshtein = levenshtein; diff --git a/reverse_engineering/node_modules/yargs/build/lib/middleware.d.ts b/reverse_engineering/node_modules/yargs/build/lib/middleware.d.ts deleted file mode 100644 index 8fa7c34..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/middleware.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { YargsInstance, Arguments } from './yargs'; -export declare function globalMiddlewareFactory(globalMiddleware: Middleware[], context: T): (callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean) => T; -export declare function commandMiddlewareFactory(commandMiddleware?: MiddlewareCallback[]): Middleware[]; -export declare function applyMiddleware(argv: Arguments | Promise, yargs: YargsInstance, middlewares: Middleware[], beforeValidation: boolean): Arguments | Promise; -export interface MiddlewareCallback { - (argv: Arguments, yargs: YargsInstance): Partial | Promise>; -} -export interface Middleware extends MiddlewareCallback { - applyBeforeValidation: boolean; -} diff --git a/reverse_engineering/node_modules/yargs/build/lib/middleware.js b/reverse_engineering/node_modules/yargs/build/lib/middleware.js deleted file mode 100644 index e93b6d2..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/middleware.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.applyMiddleware = exports.commandMiddlewareFactory = exports.globalMiddlewareFactory = void 0; -const argsert_1 = require("./argsert"); -const is_promise_1 = require("./is-promise"); -function globalMiddlewareFactory(globalMiddleware, context) { - return function (callback, applyBeforeValidation = false) { - argsert_1.argsert(' [boolean]', [callback, applyBeforeValidation], arguments.length); - if (Array.isArray(callback)) { - for (let i = 0; i < callback.length; i++) { - if (typeof callback[i] !== 'function') { - throw Error('middleware must be a function'); - } - callback[i].applyBeforeValidation = applyBeforeValidation; - } - Array.prototype.push.apply(globalMiddleware, callback); - } - else if (typeof callback === 'function') { - callback.applyBeforeValidation = applyBeforeValidation; - globalMiddleware.push(callback); - } - return context; - }; -} -exports.globalMiddlewareFactory = globalMiddlewareFactory; -function commandMiddlewareFactory(commandMiddleware) { - if (!commandMiddleware) - return []; - return commandMiddleware.map(middleware => { - middleware.applyBeforeValidation = false; - return middleware; - }); -} -exports.commandMiddlewareFactory = commandMiddlewareFactory; -function applyMiddleware(argv, yargs, middlewares, beforeValidation) { - const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true'); - return middlewares - .reduce((acc, middleware) => { - if (middleware.applyBeforeValidation !== beforeValidation) { - return acc; - } - if (is_promise_1.isPromise(acc)) { - return acc - .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) - .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); - } - else { - const result = middleware(acc, yargs); - if (beforeValidation && is_promise_1.isPromise(result)) - throw beforeValidationError; - return is_promise_1.isPromise(result) - ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) - : Object.assign(acc, result); - } - }, argv); -} -exports.applyMiddleware = applyMiddleware; diff --git a/reverse_engineering/node_modules/yargs/build/lib/obj-filter.d.ts b/reverse_engineering/node_modules/yargs/build/lib/obj-filter.d.ts deleted file mode 100644 index 031ae28..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/obj-filter.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function objFilter(original?: T, filter?: (k: keyof T, v: T[keyof T]) => boolean): T; diff --git a/reverse_engineering/node_modules/yargs/build/lib/obj-filter.js b/reverse_engineering/node_modules/yargs/build/lib/obj-filter.js deleted file mode 100644 index 790f947..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/obj-filter.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.objFilter = void 0; -const common_types_1 = require("./common-types"); -function objFilter(original = {}, filter = () => true) { - const obj = {}; - common_types_1.objectKeys(original).forEach((key) => { - if (filter(key, original[key])) { - obj[key] = original[key]; - } - }); - return obj; -} -exports.objFilter = objFilter; diff --git a/reverse_engineering/node_modules/yargs/build/lib/parse-command.d.ts b/reverse_engineering/node_modules/yargs/build/lib/parse-command.d.ts deleted file mode 100644 index fc57836..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/parse-command.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { NotEmptyArray } from './common-types'; -export declare function parseCommand(cmd: string): ParsedCommand; -export interface ParsedCommand { - cmd: string; - demanded: Positional[]; - optional: Positional[]; -} -export interface Positional { - cmd: NotEmptyArray; - variadic: boolean; -} diff --git a/reverse_engineering/node_modules/yargs/build/lib/parse-command.js b/reverse_engineering/node_modules/yargs/build/lib/parse-command.js deleted file mode 100644 index aaf2327..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/parse-command.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseCommand = void 0; -function parseCommand(cmd) { - const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); - const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); - const bregex = /\.*[\][<>]/g; - const firstCommand = splitCommand.shift(); - if (!firstCommand) - throw new Error(`No command found in: ${cmd}`); - const parsedCommand = { - cmd: firstCommand.replace(bregex, ''), - demanded: [], - optional: [] - }; - splitCommand.forEach((cmd, i) => { - let variadic = false; - cmd = cmd.replace(/\s/g, ''); - if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) - variadic = true; - if (/^\[/.test(cmd)) { - parsedCommand.optional.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic - }); - } - else { - parsedCommand.demanded.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic - }); - } - }); - return parsedCommand; -} -exports.parseCommand = parseCommand; diff --git a/reverse_engineering/node_modules/yargs/build/lib/process-argv.d.ts b/reverse_engineering/node_modules/yargs/build/lib/process-argv.d.ts deleted file mode 100644 index 18fd43b..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/process-argv.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare function getProcessArgvWithoutBin(): string[]; -export declare function getProcessArgvBin(): string; diff --git a/reverse_engineering/node_modules/yargs/build/lib/process-argv.js b/reverse_engineering/node_modules/yargs/build/lib/process-argv.js deleted file mode 100644 index a9201dd..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/process-argv.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getProcessArgvBin = exports.getProcessArgvWithoutBin = void 0; -function getProcessArgvBinIndex() { - // The binary name is the first command line argument for: - // - bundled Electron apps: bin argv1 argv2 ... argvn - if (isBundledElectronApp()) - return 0; - // or the second one (default) for: - // - standard node apps: node bin.js argv1 argv2 ... argvn - // - unbundled Electron apps: electron bin.js argv1 arg2 ... argvn - return 1; -} -function isBundledElectronApp() { - // process.defaultApp is either set by electron in an electron unbundled app, or undefined - // see https://github.com/electron/electron/blob/master/docs/api/process.md#processdefaultapp-readonly - return isElectronApp() && !process.defaultApp; -} -function isElectronApp() { - // process.versions.electron is either set by electron, or undefined - // see https://github.com/electron/electron/blob/master/docs/api/process.md#processversionselectron-readonly - return !!process.versions.electron; -} -function getProcessArgvWithoutBin() { - return process.argv.slice(getProcessArgvBinIndex() + 1); -} -exports.getProcessArgvWithoutBin = getProcessArgvWithoutBin; -function getProcessArgvBin() { - return process.argv[getProcessArgvBinIndex()]; -} -exports.getProcessArgvBin = getProcessArgvBin; diff --git a/reverse_engineering/node_modules/yargs/build/lib/usage.d.ts b/reverse_engineering/node_modules/yargs/build/lib/usage.d.ts deleted file mode 100644 index d9dd1fa..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/usage.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Dictionary } from './common-types'; -import { YargsInstance } from './yargs'; -import { YError } from './yerror'; -import { Y18N } from 'y18n'; -export declare function usage(yargs: YargsInstance, y18n: Y18N): UsageInstance; -/** Instance of the usage module. */ -export interface UsageInstance { - cacheHelpMessage(): void; - clearCachedHelpMessage(): void; - command(cmd: string, description: string | undefined, isDefault: boolean, aliases: string[], deprecated?: boolean): void; - deferY18nLookup(str: string): string; - describe(keys: string | string[] | Dictionary, desc?: string): void; - epilog(msg: string): void; - example(cmd: string, description?: string): void; - fail(msg?: string | null, err?: YError | string): void; - failFn(f: FailureFunction): void; - freeze(): void; - functionDescription(fn: { - name?: string; - }): string; - getCommands(): [string, string, boolean, string[], boolean][]; - getDescriptions(): Dictionary; - getPositionalGroupName(): string; - getUsage(): [string, string][]; - getUsageDisabled(): boolean; - help(): string; - reset(localLookup: Dictionary): UsageInstance; - showHelp(level: 'error' | 'log' | ((message: string) => void)): void; - showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance; - showVersion(): void; - stringifiedValues(values?: any[], separator?: string): string; - unfreeze(): void; - usage(msg: string | null, description?: string | false): UsageInstance; - version(ver: any): void; - wrap(cols: number | null | undefined): void; -} -export interface FailureFunction { - (msg: string | undefined | null, err: YError | string | undefined, usage: UsageInstance): void; -} -export interface FrozenUsageInstance { - failMessage: string | undefined | null; - failureOutput: boolean; - usages: [string, string][]; - usageDisabled: boolean; - epilogs: string[]; - examples: [string, string][]; - commands: [string, string, boolean, string[], boolean][]; - descriptions: Dictionary; -} diff --git a/reverse_engineering/node_modules/yargs/build/lib/usage.js b/reverse_engineering/node_modules/yargs/build/lib/usage.js deleted file mode 100644 index 73f7b24..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/usage.js +++ /dev/null @@ -1,540 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.usage = void 0; -// this file handles outputting usage instructions, -// failures, etc. keeps logging in one place. -const common_types_1 = require("./common-types"); -const obj_filter_1 = require("./obj-filter"); -const path = require("path"); -const yerror_1 = require("./yerror"); -const decamelize = require("decamelize"); -const setBlocking = require("set-blocking"); -const stringWidth = require("string-width"); -function usage(yargs, y18n) { - const __ = y18n.__; - const self = {}; - // methods for ouputting/building failure message. - const fails = []; - self.failFn = function failFn(f) { - fails.push(f); - }; - let failMessage = null; - let showHelpOnFail = true; - self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { - function parseFunctionArgs() { - return typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; - } - const [enabled, message] = parseFunctionArgs(); - failMessage = message; - showHelpOnFail = enabled; - return self; - }; - let failureOutput = false; - self.fail = function fail(msg, err) { - const logger = yargs._getLoggerInstance(); - if (fails.length) { - for (let i = fails.length - 1; i >= 0; --i) { - fails[i](msg, err, self); - } - } - else { - if (yargs.getExitProcess()) - setBlocking(true); - // don't output failure message more than once - if (!failureOutput) { - failureOutput = true; - if (showHelpOnFail) { - yargs.showHelp('error'); - logger.error(); - } - if (msg || err) - logger.error(msg || err); - if (failMessage) { - if (msg || err) - logger.error(''); - logger.error(failMessage); - } - } - err = err || new yerror_1.YError(msg); - if (yargs.getExitProcess()) { - return yargs.exit(1); - } - else if (yargs._hasParseCallback()) { - return yargs.exit(1, err); - } - else { - throw err; - } - } - }; - // methods for ouputting/building help (usage) message. - let usages = []; - let usageDisabled = false; - self.usage = (msg, description) => { - if (msg === null) { - usageDisabled = true; - usages = []; - return self; - } - usageDisabled = false; - usages.push([msg, description || '']); - return self; - }; - self.getUsage = () => { - return usages; - }; - self.getUsageDisabled = () => { - return usageDisabled; - }; - self.getPositionalGroupName = () => { - return __('Positionals:'); - }; - let examples = []; - self.example = (cmd, description) => { - examples.push([cmd, description || '']); - }; - let commands = []; - self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { - // the last default wins, so cancel out any previously set default - if (isDefault) { - commands = commands.map((cmdArray) => { - cmdArray[2] = false; - return cmdArray; - }); - } - commands.push([cmd, description || '', isDefault, aliases, deprecated]); - }; - self.getCommands = () => commands; - let descriptions = {}; - self.describe = function describe(keyOrKeys, desc) { - if (Array.isArray(keyOrKeys)) { - keyOrKeys.forEach((k) => { - self.describe(k, desc); - }); - } - else if (typeof keyOrKeys === 'object') { - Object.keys(keyOrKeys).forEach((k) => { - self.describe(k, keyOrKeys[k]); - }); - } - else { - descriptions[keyOrKeys] = desc; - } - }; - self.getDescriptions = () => descriptions; - let epilogs = []; - self.epilog = (msg) => { - epilogs.push(msg); - }; - let wrapSet = false; - let wrap; - self.wrap = (cols) => { - wrapSet = true; - wrap = cols; - }; - function getWrap() { - if (!wrapSet) { - wrap = windowWidth(); - wrapSet = true; - } - return wrap; - } - const deferY18nLookupPrefix = '__yargsString__:'; - self.deferY18nLookup = str => deferY18nLookupPrefix + str; - self.help = function help() { - if (cachedHelpMessage) - return cachedHelpMessage; - normalizeAliases(); - // handle old demanded API - const base$0 = yargs.customScriptName ? yargs.$0 : path.basename(yargs.$0); - const demandedOptions = yargs.getDemandedOptions(); - const demandedCommands = yargs.getDemandedCommands(); - const deprecatedOptions = yargs.getDeprecatedOptions(); - const groups = yargs.getGroups(); - const options = yargs.getOptions(); - let keys = []; - keys = keys.concat(Object.keys(descriptions)); - keys = keys.concat(Object.keys(demandedOptions)); - keys = keys.concat(Object.keys(demandedCommands)); - keys = keys.concat(Object.keys(options.default)); - keys = keys.filter(filterHiddenOptions); - keys = Object.keys(keys.reduce((acc, key) => { - if (key !== '_') - acc[key] = true; - return acc; - }, {})); - const theWrap = getWrap(); - const ui = require('cliui')({ - width: theWrap, - wrap: !!theWrap - }); - // the usage string. - if (!usageDisabled) { - if (usages.length) { - // user-defined usage. - usages.forEach((usage) => { - ui.div(`${usage[0].replace(/\$0/g, base$0)}`); - if (usage[1]) { - ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); - } - }); - ui.div(); - } - else if (commands.length) { - let u = null; - // demonstrate how commands are used. - if (demandedCommands._) { - u = `${base$0} <${__('command')}>\n`; - } - else { - u = `${base$0} [${__('command')}]\n`; - } - ui.div(`${u}`); - } - } - // your application's commands, i.e., non-option - // arguments populated in '_'. - if (commands.length) { - ui.div(__('Commands:')); - const context = yargs.getContext(); - const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''; - if (yargs.getParserConfiguration()['sort-commands'] === true) { - commands = commands.sort((a, b) => a[0].localeCompare(b[0])); - } - commands.forEach((command) => { - const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; // drop $0 from default commands. - ui.span({ - text: commandString, - padding: [0, 2, 0, 2], - width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4 - }, { text: command[1] }); - const hints = []; - if (command[2]) - hints.push(`[${__('default')}]`); - if (command[3] && command[3].length) { - hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); - } - if (command[4]) { - if (typeof command[4] === 'string') { - hints.push(`[${__('deprecated: %s', command[4])}]`); - } - else { - hints.push(`[${__('deprecated')}]`); - } - } - if (hints.length) { - ui.div({ text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right' }); - } - else { - ui.div(); - } - }); - ui.div(); - } - // perform some cleanup on the keys array, making it - // only include top-level keys not their aliases. - const aliasKeys = (Object.keys(options.alias) || []) - .concat(Object.keys(yargs.parsed.newAliases) || []); - keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); - // populate 'Options:' group with any keys that have not - // explicitly had a group set. - const defaultGroup = __('Options:'); - if (!groups[defaultGroup]) - groups[defaultGroup] = []; - addUngroupedKeys(keys, options.alias, groups, defaultGroup); - // display 'Options:' table along with any custom tables: - Object.keys(groups).forEach((groupName) => { - if (!groups[groupName].length) - return; - // if we've grouped the key 'f', but 'f' aliases 'foobar', - // normalizedKeys should contain only 'foobar'. - const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => { - if (~aliasKeys.indexOf(key)) - return key; - for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { - if (~(options.alias[aliasKey] || []).indexOf(key)) - return aliasKey; - } - return key; - }); - if (normalizedKeys.length < 1) - return; - ui.div(groupName); - // actually generate the switches string --foo, -f, --bar. - const switches = normalizedKeys.reduce((acc, key) => { - acc[key] = [key].concat(options.alias[key] || []) - .map(sw => { - // for the special positional group don't - // add '--' or '-' prefix. - if (groupName === self.getPositionalGroupName()) - return sw; - else { - return ( - // matches yargs-parser logic in which single-digits - // aliases declared with a boolean type are now valid - /^[0-9]$/.test(sw) - ? ~options.boolean.indexOf(key) ? '-' : '--' - : sw.length > 1 ? '--' : '-') + sw; - } - }) - .join(', '); - return acc; - }, {}); - normalizedKeys.forEach((key) => { - const kswitch = switches[key]; - let desc = descriptions[key] || ''; - let type = null; - if (~desc.lastIndexOf(deferY18nLookupPrefix)) - desc = __(desc.substring(deferY18nLookupPrefix.length)); - if (~options.boolean.indexOf(key)) - type = `[${__('boolean')}]`; - if (~options.count.indexOf(key)) - type = `[${__('count')}]`; - if (~options.string.indexOf(key)) - type = `[${__('string')}]`; - if (~options.normalize.indexOf(key)) - type = `[${__('string')}]`; - if (~options.array.indexOf(key)) - type = `[${__('array')}]`; - if (~options.number.indexOf(key)) - type = `[${__('number')}]`; - const deprecatedExtra = (deprecated) => typeof deprecated === 'string' - ? `[${__('deprecated: %s', deprecated)}]` - : `[${__('deprecated')}]`; - const extra = [ - (key in deprecatedOptions) ? deprecatedExtra(deprecatedOptions[key]) : null, - type, - (key in demandedOptions) ? `[${__('required')}]` : null, - options.choices && options.choices[key] ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` : null, - defaultString(options.default[key], options.defaultDescription[key]) - ].filter(Boolean).join(' '); - ui.span({ text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4 }, desc); - if (extra) - ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); - else - ui.div(); - }); - ui.div(); - }); - // describe some common use-cases for your application. - if (examples.length) { - ui.div(__('Examples:')); - examples.forEach((example) => { - example[0] = example[0].replace(/\$0/g, base$0); - }); - examples.forEach((example) => { - if (example[1] === '') { - ui.div({ - text: example[0], - padding: [0, 2, 0, 2] - }); - } - else { - ui.div({ - text: example[0], - padding: [0, 2, 0, 2], - width: maxWidth(examples, theWrap) + 4 - }, { - text: example[1] - }); - } - }); - ui.div(); - } - // the usage string. - if (epilogs.length > 0) { - const e = epilogs.map(epilog => epilog.replace(/\$0/g, base$0)).join('\n'); - ui.div(`${e}\n`); - } - // Remove the trailing white spaces - return ui.toString().replace(/\s*$/, ''); - }; - // return the maximum width of a string - // in the left-hand column of a table. - function maxWidth(table, theWrap, modifier) { - let width = 0; - // table might be of the form [leftColumn], - // or {key: leftColumn} - if (!Array.isArray(table)) { - table = Object.values(table).map(v => [v]); - } - table.forEach((v) => { - width = Math.max(stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]), width); - }); - // if we've enabled 'wrap' we should limit - // the max-width of the left-column. - if (theWrap) - width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); - return width; - } - // make sure any options set for aliases, - // are copied to the keys being aliased. - function normalizeAliases() { - // handle old demanded API - const demandedOptions = yargs.getDemandedOptions(); - const options = yargs.getOptions(); - (Object.keys(options.alias) || []).forEach((key) => { - options.alias[key].forEach((alias) => { - // copy descriptions. - if (descriptions[alias]) - self.describe(key, descriptions[alias]); - // copy demanded. - if (alias in demandedOptions) - yargs.demandOption(key, demandedOptions[alias]); - // type messages. - if (~options.boolean.indexOf(alias)) - yargs.boolean(key); - if (~options.count.indexOf(alias)) - yargs.count(key); - if (~options.string.indexOf(alias)) - yargs.string(key); - if (~options.normalize.indexOf(alias)) - yargs.normalize(key); - if (~options.array.indexOf(alias)) - yargs.array(key); - if (~options.number.indexOf(alias)) - yargs.number(key); - }); - }); - } - // if yargs is executing an async handler, we take a snapshot of the - // help message to display on failure: - let cachedHelpMessage; - self.cacheHelpMessage = function () { - cachedHelpMessage = this.help(); - }; - // however this snapshot must be cleared afterwards - // not to be be used by next calls to parse - self.clearCachedHelpMessage = function () { - cachedHelpMessage = undefined; - }; - // given a set of keys, place any keys that are - // ungrouped under the 'Options:' grouping. - function addUngroupedKeys(keys, aliases, groups, defaultGroup) { - let groupedKeys = []; - let toCheck = null; - Object.keys(groups).forEach((group) => { - groupedKeys = groupedKeys.concat(groups[group]); - }); - keys.forEach((key) => { - toCheck = [key].concat(aliases[key]); - if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { - groups[defaultGroup].push(key); - } - }); - return groupedKeys; - } - function filterHiddenOptions(key) { - return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt]; - } - self.showHelp = (level) => { - const logger = yargs._getLoggerInstance(); - if (!level) - level = 'error'; - const emit = typeof level === 'function' ? level : logger[level]; - emit(self.help()); - }; - self.functionDescription = (fn) => { - const description = fn.name ? decamelize(fn.name, '-') : __('generated-value'); - return ['(', description, ')'].join(''); - }; - self.stringifiedValues = function stringifiedValues(values, separator) { - let string = ''; - const sep = separator || ', '; - const array = [].concat(values); - if (!values || !array.length) - return string; - array.forEach((value) => { - if (string.length) - string += sep; - string += JSON.stringify(value); - }); - return string; - }; - // format the default-value-string displayed in - // the right-hand column. - function defaultString(value, defaultDescription) { - let string = `[${__('default:')} `; - if (value === undefined && !defaultDescription) - return null; - if (defaultDescription) { - string += defaultDescription; - } - else { - switch (typeof value) { - case 'string': - string += `"${value}"`; - break; - case 'object': - string += JSON.stringify(value); - break; - default: - string += value; - } - } - return `${string}]`; - } - // guess the width of the console window, max-width 80. - function windowWidth() { - const maxWidth = 80; - // CI is not a TTY - /* c8 ignore next 2 */ - if (typeof process === 'object' && process.stdout && process.stdout.columns) { - return Math.min(maxWidth, process.stdout.columns); - } - else { - return maxWidth; - } - } - // logic for displaying application version. - let version = null; - self.version = (ver) => { - version = ver; - }; - self.showVersion = () => { - const logger = yargs._getLoggerInstance(); - logger.log(version); - }; - self.reset = function reset(localLookup) { - // do not reset wrap here - // do not reset fails here - failMessage = null; - failureOutput = false; - usages = []; - usageDisabled = false; - epilogs = []; - examples = []; - commands = []; - descriptions = obj_filter_1.objFilter(descriptions, k => !localLookup[k]); - return self; - }; - const frozens = []; - self.freeze = function freeze() { - frozens.push({ - failMessage, - failureOutput, - usages, - usageDisabled, - epilogs, - examples, - commands, - descriptions - }); - }; - self.unfreeze = function unfreeze() { - const frozen = frozens.pop(); - common_types_1.assertNotStrictEqual(frozen, undefined); - ({ - failMessage, - failureOutput, - usages, - usageDisabled, - epilogs, - examples, - commands, - descriptions - } = frozen); - }; - return self; -} -exports.usage = usage; diff --git a/reverse_engineering/node_modules/yargs/build/lib/validation.d.ts b/reverse_engineering/node_modules/yargs/build/lib/validation.d.ts deleted file mode 100644 index e2d7854..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/validation.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { Dictionary } from './common-types'; -import { UsageInstance } from './usage'; -import { YargsInstance, Arguments } from './yargs'; -import { DetailedArguments } from 'yargs-parser'; -import { Y18N } from 'y18n'; -export declare function validation(yargs: YargsInstance, usage: UsageInstance, y18n: Y18N): ValidationInstance; -/** Instance of the validation module. */ -export interface ValidationInstance { - check(f: CustomCheck['func'], global: boolean): void; - conflicting(argv: Arguments): void; - conflicts(key: string | Dictionary, value?: string | string[]): void; - customChecks(argv: Arguments, aliases: DetailedArguments['aliases']): void; - freeze(): void; - getConflicting(): Dictionary<(string | undefined)[]>; - getImplied(): Dictionary; - implications(argv: Arguments): void; - implies(key: string | Dictionary, value?: KeyOrPos | KeyOrPos[]): void; - isValidAndSomeAliasIsNotNew(key: string, aliases: DetailedArguments['aliases']): boolean; - limitedChoices(argv: Arguments): void; - nonOptionCount(argv: Arguments): void; - positionalCount(required: number, observed: number): void; - recommendCommands(cmd: string, potentialCommands: string[]): void; - requiredArguments(argv: Arguments): void; - reset(localLookup: Dictionary): ValidationInstance; - unfreeze(): void; - unknownArguments(argv: Arguments, aliases: DetailedArguments['aliases'], positionalMap: Dictionary, isDefaultCommand: boolean): void; - unknownCommands(argv: Arguments): boolean; -} -interface CustomCheck { - func: (argv: Arguments, aliases: DetailedArguments['aliases']) => any; - global: boolean; -} -export declare type KeyOrPos = string | number; -export {}; diff --git a/reverse_engineering/node_modules/yargs/build/lib/validation.js b/reverse_engineering/node_modules/yargs/build/lib/validation.js deleted file mode 100644 index 60c5e43..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/validation.js +++ /dev/null @@ -1,330 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validation = void 0; -const argsert_1 = require("./argsert"); -const common_types_1 = require("./common-types"); -const levenshtein_1 = require("./levenshtein"); -const obj_filter_1 = require("./obj-filter"); -const specialKeys = ['$0', '--', '_']; -// validation-type-stuff, missing params, -// bad implications, custom checks. -function validation(yargs, usage, y18n) { - const __ = y18n.__; - const __n = y18n.__n; - const self = {}; - // validate appropriate # of non-option - // arguments were provided, i.e., '_'. - self.nonOptionCount = function nonOptionCount(argv) { - const demandedCommands = yargs.getDemandedCommands(); - // don't count currently executing commands - const _s = argv._.length - yargs.getContext().commands.length; - if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) { - if (_s < demandedCommands._.min) { - if (demandedCommands._.minMsg !== undefined) { - usage.fail( - // replace $0 with observed, $1 with expected. - demandedCommands._.minMsg - ? demandedCommands._.minMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.min.toString()) - : null); - } - else { - usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s, demandedCommands._.min)); - } - } - else if (_s > demandedCommands._.max) { - if (demandedCommands._.maxMsg !== undefined) { - usage.fail( - // replace $0 with observed, $1 with expected. - demandedCommands._.maxMsg - ? demandedCommands._.maxMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.max.toString()) - : null); - } - else { - usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s, demandedCommands._.max)); - } - } - } - }; - // validate the appropriate # of - // positional arguments were provided: - self.positionalCount = function positionalCount(required, observed) { - if (observed < required) { - usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed, required)); - } - }; - // make sure all the required arguments are present. - self.requiredArguments = function requiredArguments(argv) { - const demandedOptions = yargs.getDemandedOptions(); - let missing = null; - for (const key of Object.keys(demandedOptions)) { - if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === 'undefined') { - missing = missing || {}; - missing[key] = demandedOptions[key]; - } - } - if (missing) { - const customMsgs = []; - for (const key of Object.keys(missing)) { - const msg = missing[key]; - if (msg && customMsgs.indexOf(msg) < 0) { - customMsgs.push(msg); - } - } - const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; - usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); - } - }; - // check for unknown arguments (strict-mode). - self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand) { - const commandKeys = yargs.getCommandInstance().getCommands(); - const unknown = []; - const currentContext = yargs.getContext(); - Object.keys(argv).forEach((key) => { - if (specialKeys.indexOf(key) === -1 && - !Object.prototype.hasOwnProperty.call(positionalMap, key) && - !Object.prototype.hasOwnProperty.call(yargs._getParseContext(), key) && - !self.isValidAndSomeAliasIsNotNew(key, aliases)) { - unknown.push(key); - } - }); - if ((currentContext.commands.length > 0) || (commandKeys.length > 0) || isDefaultCommand) { - argv._.slice(currentContext.commands.length).forEach((key) => { - if (commandKeys.indexOf(key) === -1) { - unknown.push(key); - } - }); - } - if (unknown.length > 0) { - usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', '))); - } - }; - self.unknownCommands = function unknownCommands(argv) { - const commandKeys = yargs.getCommandInstance().getCommands(); - const unknown = []; - const currentContext = yargs.getContext(); - if ((currentContext.commands.length > 0) || (commandKeys.length > 0)) { - argv._.slice(currentContext.commands.length).forEach((key) => { - if (commandKeys.indexOf(key) === -1) { - unknown.push(key); - } - }); - } - if (unknown.length > 0) { - usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); - return true; - } - else { - return false; - } - }; - // check for a key that is not an alias, or for which every alias is new, - // implying that it was invented by the parser, e.g., during camelization - self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { - if (!Object.prototype.hasOwnProperty.call(aliases, key)) { - return false; - } - const newAliases = yargs.parsed.newAliases; - for (const a of [key, ...aliases[key]]) { - if (!Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]) { - return true; - } - } - return false; - }; - // validate arguments limited to enumerated choices - self.limitedChoices = function limitedChoices(argv) { - const options = yargs.getOptions(); - const invalid = {}; - if (!Object.keys(options.choices).length) - return; - Object.keys(argv).forEach((key) => { - if (specialKeys.indexOf(key) === -1 && - Object.prototype.hasOwnProperty.call(options.choices, key)) { - [].concat(argv[key]).forEach((value) => { - // TODO case-insensitive configurability - if (options.choices[key].indexOf(value) === -1 && - value !== undefined) { - invalid[key] = (invalid[key] || []).concat(value); - } - }); - } - }); - const invalidKeys = Object.keys(invalid); - if (!invalidKeys.length) - return; - let msg = __('Invalid values:'); - invalidKeys.forEach((key) => { - msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; - }); - usage.fail(msg); - }; - // custom checks, added using the `check` option on yargs. - let checks = []; - self.check = function check(f, global) { - checks.push({ - func: f, - global - }); - }; - self.customChecks = function customChecks(argv, aliases) { - for (let i = 0, f; (f = checks[i]) !== undefined; i++) { - const func = f.func; - let result = null; - try { - result = func(argv, aliases); - } - catch (err) { - usage.fail(err.message ? err.message : err, err); - continue; - } - if (!result) { - usage.fail(__('Argument check failed: %s', func.toString())); - } - else if (typeof result === 'string' || result instanceof Error) { - usage.fail(result.toString(), result); - } - } - }; - // check implications, argument foo implies => argument bar. - let implied = {}; - self.implies = function implies(key, value) { - argsert_1.argsert(' [array|number|string]', [key, value], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach((k) => { - self.implies(k, key[k]); - }); - } - else { - yargs.global(key); - if (!implied[key]) { - implied[key] = []; - } - if (Array.isArray(value)) { - value.forEach((i) => self.implies(key, i)); - } - else { - common_types_1.assertNotStrictEqual(value, undefined); - implied[key].push(value); - } - } - }; - self.getImplied = function getImplied() { - return implied; - }; - function keyExists(argv, val) { - // convert string '1' to number 1 - const num = Number(val); - val = isNaN(num) ? val : num; - if (typeof val === 'number') { - // check length of argv._ - val = argv._.length >= val; - } - else if (val.match(/^--no-.+/)) { - // check if key/value doesn't exist - val = val.match(/^--no-(.+)/)[1]; - val = !argv[val]; - } - else { - // check if key/value exists - val = argv[val]; - } - return val; - } - self.implications = function implications(argv) { - const implyFail = []; - Object.keys(implied).forEach((key) => { - const origKey = key; - (implied[key] || []).forEach((value) => { - let key = origKey; - const origValue = value; - key = keyExists(argv, key); - value = keyExists(argv, value); - if (key && !value) { - implyFail.push(` ${origKey} -> ${origValue}`); - } - }); - }); - if (implyFail.length) { - let msg = `${__('Implications failed:')}\n`; - implyFail.forEach((value) => { - msg += (value); - }); - usage.fail(msg); - } - }; - let conflicting = {}; - self.conflicts = function conflicts(key, value) { - argsert_1.argsert(' [array|string]', [key, value], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach((k) => { - self.conflicts(k, key[k]); - }); - } - else { - yargs.global(key); - if (!conflicting[key]) { - conflicting[key] = []; - } - if (Array.isArray(value)) { - value.forEach((i) => self.conflicts(key, i)); - } - else { - conflicting[key].push(value); - } - } - }; - self.getConflicting = () => conflicting; - self.conflicting = function conflictingFn(argv) { - Object.keys(argv).forEach((key) => { - if (conflicting[key]) { - conflicting[key].forEach((value) => { - // we default keys to 'undefined' that have been configured, we should not - // apply conflicting check unless they are a value other than 'undefined'. - if (value && argv[key] !== undefined && argv[value] !== undefined) { - usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); - } - }); - } - }); - }; - self.recommendCommands = function recommendCommands(cmd, potentialCommands) { - const threshold = 3; // if it takes more than three edits, let's move on. - potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); - let recommended = null; - let bestDistance = Infinity; - for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { - const d = levenshtein_1.levenshtein(cmd, candidate); - if (d <= threshold && d < bestDistance) { - bestDistance = d; - recommended = candidate; - } - } - if (recommended) - usage.fail(__('Did you mean %s?', recommended)); - }; - self.reset = function reset(localLookup) { - implied = obj_filter_1.objFilter(implied, k => !localLookup[k]); - conflicting = obj_filter_1.objFilter(conflicting, k => !localLookup[k]); - checks = checks.filter(c => c.global); - return self; - }; - const frozens = []; - self.freeze = function freeze() { - frozens.push({ - implied, - checks, - conflicting - }); - }; - self.unfreeze = function unfreeze() { - const frozen = frozens.pop(); - common_types_1.assertNotStrictEqual(frozen, undefined); - ({ - implied, - checks, - conflicting - } = frozen); - }; - return self; -} -exports.validation = validation; diff --git a/reverse_engineering/node_modules/yargs/build/lib/yargs.d.ts b/reverse_engineering/node_modules/yargs/build/lib/yargs.d.ts deleted file mode 100644 index 8e6e27c..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/yargs.d.ts +++ /dev/null @@ -1,274 +0,0 @@ -/// -import { CommandInstance, CommandHandler, CommandBuilderDefinition, CommandBuilder, CommandHandlerCallback, FinishCommandHandler } from './command'; -import { Dictionary } from './common-types'; -import { Arguments as ParserArguments, DetailedArguments as ParserDetailedArguments, Configuration as ParserConfiguration, Options as ParserOptions, ConfigCallback, CoerceCallback } from 'yargs-parser'; -import { YError } from './yerror'; -import { UsageInstance, FailureFunction } from './usage'; -import { CompletionFunction } from './completion'; -import { ValidationInstance, KeyOrPos } from './validation'; -import { Y18N } from 'y18n'; -import { MiddlewareCallback, Middleware } from './middleware'; -import { RequireDirectoryOptions } from 'require-directory'; -export declare function Yargs(processArgs?: string | string[], cwd?: string, parentRequire?: NodeRequire): YargsInstance; -export declare function rebase(base: string, dir: string): string; -/** Instance of the yargs module. */ -export interface YargsInstance { - $0: string; - argv: Arguments; - customScriptName: boolean; - parsed: DetailedArguments | false; - _copyDoubleDash>(argv: T): T; - _getLoggerInstance(): LoggerInstance; - _getParseContext(): Object; - _hasOutput(): boolean; - _hasParseCallback(): boolean; - _parseArgs: { - (args: null, shortCircuit: null, _calledFromCommand: boolean, commandIndex?: number): Arguments | Promise; - (args: string | string[], shortCircuit?: boolean): Arguments | Promise; - }; - _runValidation(argv: Arguments, aliases: Dictionary, positionalMap: Dictionary, parseErrors: Error | null, isDefaultCommand?: boolean): void; - _setHasOutput(): void; - addHelpOpt: { - (opt?: string | false): YargsInstance; - (opt?: string, msg?: string): YargsInstance; - }; - addShowHiddenOpt: { - (opt?: string | false): YargsInstance; - (opt?: string, msg?: string): YargsInstance; - }; - alias: { - (keys: string | string[], aliases: string | string[]): YargsInstance; - (keyAliases: Dictionary): YargsInstance; - }; - array(keys: string | string[]): YargsInstance; - boolean(keys: string | string[]): YargsInstance; - check(f: (argv: Arguments, aliases: Dictionary) => any, _global?: boolean): YargsInstance; - choices: { - (keys: string | string[], choices: string | string[]): YargsInstance; - (keyChoices: Dictionary): YargsInstance; - }; - coerce: { - (keys: string | string[], coerceCallback: CoerceCallback): YargsInstance; - (keyCoerceCallbacks: Dictionary): YargsInstance; - }; - command(cmd: string | string[], description: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, commandMiddleware?: Middleware[], deprecated?: boolean): YargsInstance; - commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance; - completion: { - (cmd?: string, fn?: CompletionFunction): YargsInstance; - (cmd?: string, desc?: string | false, fn?: CompletionFunction): YargsInstance; - }; - config: { - (config: Dictionary): YargsInstance; - (keys?: string | string[], configCallback?: ConfigCallback): YargsInstance; - (keys?: string | string[], msg?: string, configCallback?: ConfigCallback): YargsInstance; - }; - conflicts: { - (key: string, conflictsWith: string | string[]): YargsInstance; - (keyConflicts: Dictionary): YargsInstance; - }; - count(keys: string | string[]): YargsInstance; - default: { - (key: string, value: any, defaultDescription?: string): YargsInstance; - (keys: string[], value: Exclude): YargsInstance; - (keys: Dictionary): YargsInstance; - }; - defaults: YargsInstance['default']; - demand: { - (min: number, max?: number | string, msg?: string): YargsInstance; - (keys: string | string[], msg?: string | true): YargsInstance; - (keys: string | string[], max: string[], msg?: string | true): YargsInstance; - (keyMsgs: Dictionary): YargsInstance; - (keyMsgs: Dictionary, max: string[], msg?: string): YargsInstance; - }; - demandCommand(): YargsInstance; - demandCommand(min: number, minMsg?: string): YargsInstance; - demandCommand(min: number, max: number, minMsg?: string | null, maxMsg?: string | null): YargsInstance; - demandOption: { - (keys: string | string[], msg?: string): YargsInstance; - (keyMsgs: Dictionary): YargsInstance; - }; - deprecateOption(option: string, message?: string | boolean): YargsInstance; - describe: { - (keys: string | string[], description?: string): YargsInstance; - (keyDescriptions: Dictionary): YargsInstance; - }; - detectLocale(detect: boolean): YargsInstance; - env(prefix?: string | false): YargsInstance; - epilog: YargsInstance['epilogue']; - epilogue(msg: string): YargsInstance; - example(cmd: string | [string, string?][], description?: string): YargsInstance; - exit(code: number, err?: YError | string): void; - exitProcess(enabled: boolean): YargsInstance; - fail(f: FailureFunction): YargsInstance; - getCommandInstance(): CommandInstance; - getCompletion(args: string[], done: (completions: string[]) => any): void; - getContext(): Context; - getDemandedCommands(): Options['demandedCommands']; - getDemandedOptions(): Options['demandedOptions']; - getDeprecatedOptions(): Options['deprecatedOptions']; - getDetectLocale(): boolean; - getExitProcess(): boolean; - getGroups(): Dictionary; - getHandlerFinishCommand(): FinishCommandHandler | null; - getOptions(): Options; - getParserConfiguration(): Configuration; - getStrict(): boolean; - getStrictCommands(): boolean; - getUsageInstance(): UsageInstance; - getValidationInstance(): ValidationInstance; - global(keys: string | string[], global?: boolean): YargsInstance; - group(keys: string | string[], groupName: string): YargsInstance; - help: YargsInstance['addHelpOpt']; - hide(key: string): YargsInstance; - implies: { - (key: string, implication: KeyOrPos | KeyOrPos[]): YargsInstance; - (keyImplications: Dictionary): YargsInstance; - }; - locale: { - (): string; - (locale: string): YargsInstance; - }; - middleware(callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean): YargsInstance; - nargs: { - (keys: string | string[], nargs: number): YargsInstance; - (keyNargs: Dictionary): YargsInstance; - }; - normalize(keys: string | string[]): YargsInstance; - number(keys: string | string[]): YargsInstance; - onFinishCommand(f: FinishCommandHandler): YargsInstance; - option: { - (key: string, optionDefinition: OptionDefinition): YargsInstance; - (keyOptionDefinitions: Dictionary): YargsInstance; - }; - options: YargsInstance['option']; - parse: { - (): Arguments | Promise; - (args: string | string[], context: object, parseCallback?: ParseCallback): Arguments | Promise; - (args: string | string[], parseCallback: ParseCallback): Arguments | Promise; - (args: string | string[], shortCircuit: boolean): Arguments | Promise; - }; - parserConfiguration(config: Configuration): YargsInstance; - pkgConf(key: string, rootPath?: string): YargsInstance; - positional(key: string, positionalDefinition: PositionalDefinition): YargsInstance; - recommendCommands(recommend: boolean): YargsInstance; - require: YargsInstance['demand']; - required: YargsInstance['demand']; - requiresArg(keys: string | string[] | Dictionary): YargsInstance; - reset(aliases?: DetailedArguments['aliases']): YargsInstance; - resetOptions(aliases?: DetailedArguments['aliases']): YargsInstance; - scriptName(scriptName: string): YargsInstance; - showCompletionScript($0?: string, cmd?: string): YargsInstance; - showHelp(level: 'error' | 'log' | ((message: string) => void)): YargsInstance; - showHelpOnFail: { - (message?: string): YargsInstance; - (enabled: boolean, message: string): YargsInstance; - }; - showHidden: YargsInstance['addShowHiddenOpt']; - skipValidation(keys: string | string[]): YargsInstance; - strict(enable?: boolean): YargsInstance; - strictCommands(enable?: boolean): YargsInstance; - string(key: string | string[]): YargsInstance; - terminalWidth(): number | null; - updateStrings(obj: Dictionary): YargsInstance; - updateLocale: YargsInstance['updateStrings']; - usage: { - (msg: string | null): YargsInstance; - (msg: string, description: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback): YargsInstance; - }; - version: { - (ver?: string | false): YargsInstance; - (key?: string, ver?: string): YargsInstance; - (key?: string, msg?: string, ver?: string): YargsInstance; - }; - wrap(cols: number | null | undefined): YargsInstance; -} -export declare function isYargsInstance(y: YargsInstance | void): y is YargsInstance; -/** Yargs' context. */ -export interface Context { - commands: string[]; - files: string[]; - fullCommands: string[]; -} -declare type LoggerInstance = Pick; -export interface Options extends ParserOptions { - __: Y18N['__']; - alias: Dictionary; - array: string[]; - boolean: string[]; - choices: Dictionary; - config: Dictionary; - configObjects: Dictionary[]; - configuration: Configuration; - count: string[]; - defaultDescription: Dictionary; - demandedCommands: Dictionary<{ - min: number; - max: number; - minMsg?: string | null; - maxMsg?: string | null; - }>; - demandedOptions: Dictionary; - deprecatedOptions: Dictionary; - hiddenOptions: string[]; - /** Manually set keys */ - key: Dictionary; - local: string[]; - normalize: string[]; - number: string[]; - showHiddenOpt: string; - skipValidation: string[]; - string: string[]; -} -export interface Configuration extends Partial { - /** Should a config object be deep-merged with the object config it extends? */ - 'deep-merge-config'?: boolean; - /** Should commands be sorted in help? */ - 'sort-commands'?: boolean; -} -export interface OptionDefinition { - alias?: string | string[]; - array?: boolean; - boolean?: boolean; - choices?: string | string[]; - coerce?: CoerceCallback; - config?: boolean; - configParser?: ConfigCallback; - conflicts?: string | string[]; - count?: boolean; - default?: any; - defaultDescription?: string; - deprecate?: string | boolean; - deprecated?: OptionDefinition['deprecate']; - desc?: string; - describe?: OptionDefinition['desc']; - description?: OptionDefinition['desc']; - demand?: string | true; - demandOption?: OptionDefinition['demand']; - global?: boolean; - group?: string; - hidden?: boolean; - implies?: string | number | KeyOrPos[]; - nargs?: number; - normalize?: boolean; - number?: boolean; - require?: OptionDefinition['demand']; - required?: OptionDefinition['demand']; - requiresArg?: boolean; - skipValidation?: boolean; - string?: boolean; - type?: 'array' | 'boolean' | 'count' | 'number' | 'string'; -} -interface PositionalDefinition extends Pick { - type?: 'boolean' | 'number' | 'string'; -} -interface ParseCallback { - (err: YError | string | undefined | null, argv: Arguments | Promise, output: string): void; -} -export interface Arguments extends ParserArguments { - /** The script name or node command */ - $0: string; -} -export interface DetailedArguments extends ParserDetailedArguments { - argv: Arguments; -} -export {}; diff --git a/reverse_engineering/node_modules/yargs/build/lib/yargs.js b/reverse_engineering/node_modules/yargs/build/lib/yargs.js deleted file mode 100644 index 316f3d6..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/yargs.js +++ /dev/null @@ -1,1190 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isYargsInstance = exports.rebase = exports.Yargs = void 0; -const command_1 = require("./command"); -const common_types_1 = require("./common-types"); -const yerror_1 = require("./yerror"); -const usage_1 = require("./usage"); -const argsert_1 = require("./argsert"); -const fs = require("fs"); -const completion_1 = require("./completion"); -const path = require("path"); -const validation_1 = require("./validation"); -const obj_filter_1 = require("./obj-filter"); -const apply_extends_1 = require("./apply-extends"); -const middleware_1 = require("./middleware"); -const processArgv = require("./process-argv"); -const is_promise_1 = require("./is-promise"); -const Parser = require("yargs-parser"); -const y18nFactory = require("y18n"); -const setBlocking = require("set-blocking"); -const findUp = require("find-up"); -const requireMainFilename = require("require-main-filename"); -function Yargs(processArgs = [], cwd = process.cwd(), parentRequire = require) { - const self = {}; - let command; - let completion = null; - let groups = {}; - const globalMiddleware = []; - let output = ''; - const preservedGroups = {}; - let usage; - let validation; - let handlerFinishCommand = null; - const y18n = y18nFactory({ - directory: path.resolve(__dirname, '../../locales'), - updateFiles: false - }); - self.middleware = middleware_1.globalMiddlewareFactory(globalMiddleware, self); - self.scriptName = function (scriptName) { - self.customScriptName = true; - self.$0 = scriptName; - return self; - }; - // ignore the node bin, specify this in your - // bin file with #!/usr/bin/env node - let default$0; - if (/\b(node|iojs|electron)(\.exe)?$/.test(process.argv[0])) { - default$0 = process.argv.slice(1, 2); - } - else { - default$0 = process.argv.slice(0, 1); - } - self.$0 = default$0 - .map(x => { - const b = rebase(cwd, x); - return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; - }) - .join(' ').trim(); - if (process.env._ !== undefined && processArgv.getProcessArgvBin() === process.env._) { - self.$0 = process.env._.replace(`${path.dirname(process.execPath)}/`, ''); - } - // use context object to keep track of resets, subcommand execution, etc - // submodules should modify and check the state of context as necessary - const context = { resets: -1, commands: [], fullCommands: [], files: [] }; - self.getContext = () => context; - // puts yargs back into an initial state. any keys - // that have been set to "global" will not be reset - // by this action. - let options; - self.resetOptions = self.reset = function resetOptions(aliases = {}) { - context.resets++; - options = options || {}; - // put yargs back into an initial state, this - // logic is used to build a nested command - // hierarchy. - const tmpOptions = {}; - tmpOptions.local = options.local ? options.local : []; - tmpOptions.configObjects = options.configObjects ? options.configObjects : []; - // if a key has been explicitly set as local, - // we should reset it before passing options to command. - const localLookup = {}; - tmpOptions.local.forEach((l) => { - localLookup[l] = true; - (aliases[l] || []).forEach((a) => { - localLookup[a] = true; - }); - }); - // add all groups not set to local to preserved groups - Object.assign(preservedGroups, Object.keys(groups).reduce((acc, groupName) => { - const keys = groups[groupName].filter(key => !(key in localLookup)); - if (keys.length > 0) { - acc[groupName] = keys; - } - return acc; - }, {})); - // groups can now be reset - groups = {}; - const arrayOptions = [ - 'array', 'boolean', 'string', 'skipValidation', - 'count', 'normalize', 'number', - 'hiddenOptions' - ]; - const objectOptions = [ - 'narg', 'key', 'alias', 'default', 'defaultDescription', - 'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce', - 'deprecatedOptions' - ]; - arrayOptions.forEach(k => { - tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k]); - }); - objectOptions.forEach((k) => { - tmpOptions[k] = obj_filter_1.objFilter(options[k], k => !localLookup[k]); - }); - tmpOptions.envPrefix = options.envPrefix; - options = tmpOptions; - // if this is the first time being executed, create - // instances of all our helpers -- otherwise just reset. - usage = usage ? usage.reset(localLookup) : usage_1.usage(self, y18n); - validation = validation ? validation.reset(localLookup) : validation_1.validation(self, usage, y18n); - command = command ? command.reset() : command_1.command(self, usage, validation, globalMiddleware); - if (!completion) - completion = completion_1.completion(self, usage, command); - completionCommand = null; - output = ''; - exitError = null; - hasOutput = false; - self.parsed = false; - return self; - }; - self.resetOptions(); - // temporary hack: allow "freezing" of reset-able state for parse(msg, cb) - const frozens = []; - function freeze() { - frozens.push({ - options, - configObjects: options.configObjects.slice(0), - exitProcess, - groups, - strict, - strictCommands, - completionCommand, - output, - exitError, - hasOutput, - parsed: self.parsed, - parseFn, - parseContext, - handlerFinishCommand - }); - usage.freeze(); - validation.freeze(); - command.freeze(); - } - function unfreeze() { - const frozen = frozens.pop(); - common_types_1.assertNotStrictEqual(frozen, undefined); - let configObjects; - ({ - options, - configObjects, - exitProcess, - groups, - output, - exitError, - hasOutput, - parsed: self.parsed, - strict, - strictCommands, - completionCommand, - parseFn, - parseContext, - handlerFinishCommand - } = frozen); - options.configObjects = configObjects; - usage.unfreeze(); - validation.unfreeze(); - command.unfreeze(); - } - self.boolean = function (keys) { - argsert_1.argsert('', [keys], arguments.length); - populateParserHintArray('boolean', keys); - return self; - }; - self.array = function (keys) { - argsert_1.argsert('', [keys], arguments.length); - populateParserHintArray('array', keys); - return self; - }; - self.number = function (keys) { - argsert_1.argsert('', [keys], arguments.length); - populateParserHintArray('number', keys); - return self; - }; - self.normalize = function (keys) { - argsert_1.argsert('', [keys], arguments.length); - populateParserHintArray('normalize', keys); - return self; - }; - self.count = function (keys) { - argsert_1.argsert('', [keys], arguments.length); - populateParserHintArray('count', keys); - return self; - }; - self.string = function (keys) { - argsert_1.argsert('', [keys], arguments.length); - populateParserHintArray('string', keys); - return self; - }; - self.requiresArg = function (keys) { - // the 2nd paramter [number] in the argsert the assertion is mandatory - // as populateParserHintSingleValueDictionary recursively calls requiresArg - // with Nan as a 2nd parameter, although we ignore it - argsert_1.argsert(' [number]', [keys], arguments.length); - // If someone configures nargs at the same time as requiresArg, - // nargs should take precedent, - // see: https://github.com/yargs/yargs/pull/1572 - // TODO: make this work with aliases, using a check similar to - // checkAllAliases() in yargs-parser. - if (typeof keys === 'string' && options.narg[keys]) { - return self; - } - else { - populateParserHintSingleValueDictionary(self.requiresArg, 'narg', keys, NaN); - } - return self; - }; - self.skipValidation = function (keys) { - argsert_1.argsert('', [keys], arguments.length); - populateParserHintArray('skipValidation', keys); - return self; - }; - function populateParserHintArray(type, keys) { - keys = [].concat(keys); - keys.forEach((key) => { - key = sanitizeKey(key); - options[type].push(key); - }); - } - self.nargs = function (key, value) { - argsert_1.argsert(' [number]', [key, value], arguments.length); - populateParserHintSingleValueDictionary(self.nargs, 'narg', key, value); - return self; - }; - self.choices = function (key, value) { - argsert_1.argsert(' [string|array]', [key, value], arguments.length); - populateParserHintArrayDictionary(self.choices, 'choices', key, value); - return self; - }; - self.alias = function (key, value) { - argsert_1.argsert(' [string|array]', [key, value], arguments.length); - populateParserHintArrayDictionary(self.alias, 'alias', key, value); - return self; - }; - // TODO: actually deprecate self.defaults. - self.default = self.defaults = function (key, value, defaultDescription) { - argsert_1.argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); - if (defaultDescription) { - common_types_1.assertSingleKey(key); - options.defaultDescription[key] = defaultDescription; - } - if (typeof value === 'function') { - common_types_1.assertSingleKey(key); - if (!options.defaultDescription[key]) - options.defaultDescription[key] = usage.functionDescription(value); - value = value.call(); - } - populateParserHintSingleValueDictionary(self.default, 'default', key, value); - return self; - }; - self.describe = function (key, desc) { - argsert_1.argsert(' [string]', [key, desc], arguments.length); - setKey(key, true); - usage.describe(key, desc); - return self; - }; - function setKey(key, set) { - populateParserHintSingleValueDictionary(setKey, 'key', key, set); - return self; - } - function demandOption(keys, msg) { - argsert_1.argsert(' [string]', [keys, msg], arguments.length); - populateParserHintSingleValueDictionary(self.demandOption, 'demandedOptions', keys, msg); - return self; - } - self.demandOption = demandOption; - self.coerce = function (keys, value) { - argsert_1.argsert(' [function]', [keys, value], arguments.length); - populateParserHintSingleValueDictionary(self.coerce, 'coerce', keys, value); - return self; - }; - function populateParserHintSingleValueDictionary(builder, type, key, value) { - populateParserHintDictionary(builder, type, key, value, (type, key, value) => { - options[type][key] = value; - }); - } - function populateParserHintArrayDictionary(builder, type, key, value) { - populateParserHintDictionary(builder, type, key, value, (type, key, value) => { - options[type][key] = (options[type][key] || []).concat(value); - }); - } - function populateParserHintDictionary(builder, type, key, value, singleKeyHandler) { - if (Array.isArray(key)) { - // an array of keys with one value ['x', 'y', 'z'], function parse () {} - key.forEach((k) => { - builder(k, value); - }); - } - else if (((key) => typeof key === 'object')(key)) { - // an object of key value pairs: {'x': parse () {}, 'y': parse() {}} - for (const k of common_types_1.objectKeys(key)) { - builder(k, key[k]); - } - } - else { - singleKeyHandler(type, sanitizeKey(key), value); - } - } - function sanitizeKey(key) { - if (key === '__proto__') - return '___proto___'; - return key; - } - function deleteFromParserHintObject(optionKey) { - // delete from all parsing hints: - // boolean, array, key, alias, etc. - common_types_1.objectKeys(options).forEach((hintKey) => { - // configObjects is not a parsing hint array - if (((key) => key === 'configObjects')(hintKey)) - return; - const hint = options[hintKey]; - if (Array.isArray(hint)) { - if (~hint.indexOf(optionKey)) - hint.splice(hint.indexOf(optionKey), 1); - } - else if (typeof hint === 'object') { - delete hint[optionKey]; - } - }); - // now delete the description from usage.js. - delete usage.getDescriptions()[optionKey]; - } - self.config = function config(key = 'config', msg, parseFn) { - argsert_1.argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); - // allow a config object to be provided directly. - if ((typeof key === 'object') && !Array.isArray(key)) { - key = apply_extends_1.applyExtends(key, cwd, self.getParserConfiguration()['deep-merge-config']); - options.configObjects = (options.configObjects || []).concat(key); - return self; - } - // allow for a custom parsing function. - if (typeof msg === 'function') { - parseFn = msg; - msg = undefined; - } - self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file')); - (Array.isArray(key) ? key : [key]).forEach((k) => { - options.config[k] = parseFn || true; - }); - return self; - }; - self.example = function (cmd, description) { - argsert_1.argsert(' [string]', [cmd, description], arguments.length); - if (Array.isArray(cmd)) { - cmd.forEach((exampleParams) => self.example(...exampleParams)); - } - else { - usage.example(cmd, description); - } - return self; - }; - self.command = function (cmd, description, builder, handler, middlewares, deprecated) { - argsert_1.argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); - command.addHandler(cmd, description, builder, handler, middlewares, deprecated); - return self; - }; - self.commandDir = function (dir, opts) { - argsert_1.argsert(' [object]', [dir, opts], arguments.length); - const req = parentRequire || require; - command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts); - return self; - }; - // TODO: deprecate self.demand in favor of - // .demandCommand() .demandOption(). - self.demand = self.required = self.require = function demand(keys, max, msg) { - // you can optionally provide a 'max' key, - // which will raise an exception if too many '_' - // options are provided. - if (Array.isArray(max)) { - max.forEach((key) => { - common_types_1.assertNotStrictEqual(msg, true); - demandOption(key, msg); - }); - max = Infinity; - } - else if (typeof max !== 'number') { - msg = max; - max = Infinity; - } - if (typeof keys === 'number') { - common_types_1.assertNotStrictEqual(msg, true); - self.demandCommand(keys, max, msg, msg); - } - else if (Array.isArray(keys)) { - keys.forEach((key) => { - common_types_1.assertNotStrictEqual(msg, true); - demandOption(key, msg); - }); - } - else { - if (typeof msg === 'string') { - demandOption(keys, msg); - } - else if (msg === true || typeof msg === 'undefined') { - demandOption(keys); - } - } - return self; - }; - self.demandCommand = function demandCommand(min = 1, max, minMsg, maxMsg) { - argsert_1.argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); - if (typeof max !== 'number') { - minMsg = max; - max = Infinity; - } - self.global('_', false); - options.demandedCommands._ = { - min, - max, - minMsg, - maxMsg - }; - return self; - }; - self.getDemandedOptions = () => { - argsert_1.argsert([], 0); - return options.demandedOptions; - }; - self.getDemandedCommands = () => { - argsert_1.argsert([], 0); - return options.demandedCommands; - }; - self.deprecateOption = function deprecateOption(option, message) { - argsert_1.argsert(' [string|boolean]', [option, message], arguments.length); - options.deprecatedOptions[option] = message; - return self; - }; - self.getDeprecatedOptions = () => { - argsert_1.argsert([], 0); - return options.deprecatedOptions; - }; - self.implies = function (key, value) { - argsert_1.argsert(' [number|string|array]', [key, value], arguments.length); - validation.implies(key, value); - return self; - }; - self.conflicts = function (key1, key2) { - argsert_1.argsert(' [string|array]', [key1, key2], arguments.length); - validation.conflicts(key1, key2); - return self; - }; - self.usage = function (msg, description, builder, handler) { - argsert_1.argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); - if (description !== undefined) { - common_types_1.assertNotStrictEqual(msg, null); - // .usage() can be used as an alias for defining - // a default command. - if ((msg || '').match(/^\$0( |$)/)) { - return self.command(msg, description, builder, handler); - } - else { - throw new yerror_1.YError('.usage() description must start with $0 if being used as alias for .command()'); - } - } - else { - usage.usage(msg); - return self; - } - }; - self.epilogue = self.epilog = function (msg) { - argsert_1.argsert('', [msg], arguments.length); - usage.epilog(msg); - return self; - }; - self.fail = function (f) { - argsert_1.argsert('', [f], arguments.length); - usage.failFn(f); - return self; - }; - self.onFinishCommand = function (f) { - argsert_1.argsert('', [f], arguments.length); - handlerFinishCommand = f; - return self; - }; - self.getHandlerFinishCommand = () => handlerFinishCommand; - self.check = function (f, _global) { - argsert_1.argsert(' [boolean]', [f, _global], arguments.length); - validation.check(f, _global !== false); - return self; - }; - self.global = function global(globals, global) { - argsert_1.argsert(' [boolean]', [globals, global], arguments.length); - globals = [].concat(globals); - if (global !== false) { - options.local = options.local.filter(l => globals.indexOf(l) === -1); - } - else { - globals.forEach((g) => { - if (options.local.indexOf(g) === -1) - options.local.push(g); - }); - } - return self; - }; - self.pkgConf = function pkgConf(key, rootPath) { - argsert_1.argsert(' [string]', [key, rootPath], arguments.length); - let conf = null; - // prefer cwd to require-main-filename in this method - // since we're looking for e.g. "nyc" config in nyc consumer - // rather than "yargs" config in nyc (where nyc is the main filename) - const obj = pkgUp(rootPath || cwd); - // If an object exists in the key, add it to options.configObjects - if (obj[key] && typeof obj[key] === 'object') { - conf = apply_extends_1.applyExtends(obj[key], rootPath || cwd, self.getParserConfiguration()['deep-merge-config']); - options.configObjects = (options.configObjects || []).concat(conf); - } - return self; - }; - const pkgs = {}; - function pkgUp(rootPath) { - const npath = rootPath || '*'; - if (pkgs[npath]) - return pkgs[npath]; - let obj = {}; - try { - let startDir = rootPath || requireMainFilename(parentRequire); - // When called in an environment that lacks require.main.filename, such as a jest test runner, - // startDir is already process.cwd(), and should not be shortened. - // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it. - if (!rootPath && path.extname(startDir)) { - startDir = path.dirname(startDir); - } - const pkgJsonPath = findUp.sync('package.json', { - cwd: startDir - }); - common_types_1.assertNotStrictEqual(pkgJsonPath, undefined); - obj = JSON.parse(fs.readFileSync(pkgJsonPath).toString()); - } - catch (noop) { } - pkgs[npath] = obj || {}; - return pkgs[npath]; - } - let parseFn = null; - let parseContext = null; - self.parse = function parse(args, shortCircuit, _parseFn) { - argsert_1.argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); - freeze(); - if (typeof args === 'undefined') { - const argv = self._parseArgs(processArgs); - const tmpParsed = self.parsed; - unfreeze(); - // TODO: remove this compatibility hack when we release yargs@15.x: - self.parsed = tmpParsed; - return argv; - } - // a context object can optionally be provided, this allows - // additional information to be passed to a command handler. - if (typeof shortCircuit === 'object') { - parseContext = shortCircuit; - shortCircuit = _parseFn; - } - // by providing a function as a second argument to - // parse you can capture output that would otherwise - // default to printing to stdout/stderr. - if (typeof shortCircuit === 'function') { - parseFn = shortCircuit; - shortCircuit = false; - } - // completion short-circuits the parsing process, - // skipping validation, etc. - if (!shortCircuit) - processArgs = args; - if (parseFn) - exitProcess = false; - const parsed = self._parseArgs(args, !!shortCircuit); - completion.setParsed(self.parsed); - if (parseFn) - parseFn(exitError, parsed, output); - unfreeze(); - return parsed; - }; - self._getParseContext = () => parseContext || {}; - self._hasParseCallback = () => !!parseFn; - self.option = self.options = function option(key, opt) { - argsert_1.argsert(' [object]', [key, opt], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach((k) => { - self.options(k, key[k]); - }); - } - else { - if (typeof opt !== 'object') { - opt = {}; - } - options.key[key] = true; // track manually set keys. - if (opt.alias) - self.alias(key, opt.alias); - const deprecate = opt.deprecate || opt.deprecated; - if (deprecate) { - self.deprecateOption(key, deprecate); - } - const demand = opt.demand || opt.required || opt.require; - // A required option can be specified via "demand: true". - if (demand) { - self.demand(key, demand); - } - if (opt.demandOption) { - self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); - } - if (opt.conflicts) { - self.conflicts(key, opt.conflicts); - } - if ('default' in opt) { - self.default(key, opt.default); - } - if (opt.implies !== undefined) { - self.implies(key, opt.implies); - } - if (opt.nargs !== undefined) { - self.nargs(key, opt.nargs); - } - if (opt.config) { - self.config(key, opt.configParser); - } - if (opt.normalize) { - self.normalize(key); - } - if (opt.choices) { - self.choices(key, opt.choices); - } - if (opt.coerce) { - self.coerce(key, opt.coerce); - } - if (opt.group) { - self.group(key, opt.group); - } - if (opt.boolean || opt.type === 'boolean') { - self.boolean(key); - if (opt.alias) - self.boolean(opt.alias); - } - if (opt.array || opt.type === 'array') { - self.array(key); - if (opt.alias) - self.array(opt.alias); - } - if (opt.number || opt.type === 'number') { - self.number(key); - if (opt.alias) - self.number(opt.alias); - } - if (opt.string || opt.type === 'string') { - self.string(key); - if (opt.alias) - self.string(opt.alias); - } - if (opt.count || opt.type === 'count') { - self.count(key); - } - if (typeof opt.global === 'boolean') { - self.global(key, opt.global); - } - if (opt.defaultDescription) { - options.defaultDescription[key] = opt.defaultDescription; - } - if (opt.skipValidation) { - self.skipValidation(key); - } - const desc = opt.describe || opt.description || opt.desc; - self.describe(key, desc); - if (opt.hidden) { - self.hide(key); - } - if (opt.requiresArg) { - self.requiresArg(key); - } - } - return self; - }; - self.getOptions = () => options; - self.positional = function (key, opts) { - argsert_1.argsert(' ', [key, opts], arguments.length); - if (context.resets === 0) { - throw new yerror_1.YError(".positional() can only be called in a command's builder function"); - } - // .positional() only supports a subset of the configuration - // options available to .option(). - const supportedOpts = ['default', 'defaultDescription', 'implies', 'normalize', - 'choices', 'conflicts', 'coerce', 'type', 'describe', - 'desc', 'description', 'alias']; - opts = obj_filter_1.objFilter(opts, (k, v) => { - let accept = supportedOpts.indexOf(k) !== -1; - // type can be one of string|number|boolean. - if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1) - accept = false; - return accept; - }); - // copy over any settings that can be inferred from the command string. - const fullCommand = context.fullCommands[context.fullCommands.length - 1]; - const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : { - array: [], - alias: {}, - default: {}, - demand: {} - }; - common_types_1.objectKeys(parseOptions).forEach((pk) => { - const parseOption = parseOptions[pk]; - if (Array.isArray(parseOption)) { - if (parseOption.indexOf(key) !== -1) - opts[pk] = true; - } - else { - if (parseOption[key] && !(pk in opts)) - opts[pk] = parseOption[key]; - } - }); - self.group(key, usage.getPositionalGroupName()); - return self.option(key, opts); - }; - self.group = function group(opts, groupName) { - argsert_1.argsert(' ', [opts, groupName], arguments.length); - const existing = preservedGroups[groupName] || groups[groupName]; - if (preservedGroups[groupName]) { - // we now only need to track this group name in groups. - delete preservedGroups[groupName]; - } - const seen = {}; - groups[groupName] = (existing || []).concat(opts).filter((key) => { - if (seen[key]) - return false; - return (seen[key] = true); - }); - return self; - }; - // combine explicit and preserved groups. explicit groups should be first - self.getGroups = () => Object.assign({}, groups, preservedGroups); - // as long as options.envPrefix is not undefined, - // parser will apply env vars matching prefix to argv - self.env = function (prefix) { - argsert_1.argsert('[string|boolean]', [prefix], arguments.length); - if (prefix === false) - delete options.envPrefix; - else - options.envPrefix = prefix || ''; - return self; - }; - self.wrap = function (cols) { - argsert_1.argsert('', [cols], arguments.length); - usage.wrap(cols); - return self; - }; - let strict = false; - self.strict = function (enabled) { - argsert_1.argsert('[boolean]', [enabled], arguments.length); - strict = enabled !== false; - return self; - }; - self.getStrict = () => strict; - let strictCommands = false; - self.strictCommands = function (enabled) { - argsert_1.argsert('[boolean]', [enabled], arguments.length); - strictCommands = enabled !== false; - return self; - }; - self.getStrictCommands = () => strictCommands; - let parserConfig = {}; - self.parserConfiguration = function parserConfiguration(config) { - argsert_1.argsert('', [config], arguments.length); - parserConfig = config; - return self; - }; - self.getParserConfiguration = () => parserConfig; - self.showHelp = function (level) { - argsert_1.argsert('[string|function]', [level], arguments.length); - if (!self.parsed) - self._parseArgs(processArgs); // run parser, if it has not already been executed. - if (command.hasDefaultCommand()) { - context.resets++; // override the restriction on top-level positoinals. - command.runDefaultBuilderOn(self); - } - usage.showHelp(level); - return self; - }; - let versionOpt = null; - self.version = function version(opt, msg, ver) { - const defaultVersionOpt = 'version'; - argsert_1.argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); - // nuke the key previously configured - // to return version #. - if (versionOpt) { - deleteFromParserHintObject(versionOpt); - usage.version(undefined); - versionOpt = null; - } - if (arguments.length === 0) { - ver = guessVersion(); - opt = defaultVersionOpt; - } - else if (arguments.length === 1) { - if (opt === false) { // disable default 'version' key. - return self; - } - ver = opt; - opt = defaultVersionOpt; - } - else if (arguments.length === 2) { - ver = msg; - msg = undefined; - } - versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt; - msg = msg || usage.deferY18nLookup('Show version number'); - usage.version(ver || undefined); - self.boolean(versionOpt); - self.describe(versionOpt, msg); - return self; - }; - function guessVersion() { - const obj = pkgUp(); - return obj.version || 'unknown'; - } - let helpOpt = null; - self.addHelpOpt = self.help = function addHelpOpt(opt, msg) { - const defaultHelpOpt = 'help'; - argsert_1.argsert('[string|boolean] [string]', [opt, msg], arguments.length); - // nuke the key previously configured - // to return help. - if (helpOpt) { - deleteFromParserHintObject(helpOpt); - helpOpt = null; - } - if (arguments.length === 1) { - if (opt === false) - return self; - } - // use arguments, fallback to defaults for opt and msg - helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt; - self.boolean(helpOpt); - self.describe(helpOpt, msg || usage.deferY18nLookup('Show help')); - return self; - }; - const defaultShowHiddenOpt = 'show-hidden'; - options.showHiddenOpt = defaultShowHiddenOpt; - self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt(opt, msg) { - argsert_1.argsert('[string|boolean] [string]', [opt, msg], arguments.length); - if (arguments.length === 1) { - if (opt === false) - return self; - } - const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt; - self.boolean(showHiddenOpt); - self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options')); - options.showHiddenOpt = showHiddenOpt; - return self; - }; - self.hide = function hide(key) { - argsert_1.argsert('', [key], arguments.length); - options.hiddenOptions.push(key); - return self; - }; - self.showHelpOnFail = function showHelpOnFail(enabled, message) { - argsert_1.argsert('[boolean|string] [string]', [enabled, message], arguments.length); - usage.showHelpOnFail(enabled, message); - return self; - }; - var exitProcess = true; - self.exitProcess = function (enabled = true) { - argsert_1.argsert('[boolean]', [enabled], arguments.length); - exitProcess = enabled; - return self; - }; - self.getExitProcess = () => exitProcess; - var completionCommand = null; - self.completion = function (cmd, desc, fn) { - argsert_1.argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); - // a function to execute when generating - // completions can be provided as the second - // or third argument to completion. - if (typeof desc === 'function') { - fn = desc; - desc = undefined; - } - // register the completion command. - completionCommand = cmd || completionCommand || 'completion'; - if (!desc && desc !== false) { - desc = 'generate completion script'; - } - self.command(completionCommand, desc); - // a function can be provided - if (fn) - completion.registerFunction(fn); - return self; - }; - self.showCompletionScript = function ($0, cmd) { - argsert_1.argsert('[string] [string]', [$0, cmd], arguments.length); - $0 = $0 || self.$0; - _logger.log(completion.generateCompletionScript($0, cmd || completionCommand || 'completion')); - return self; - }; - self.getCompletion = function (args, done) { - argsert_1.argsert(' ', [args, done], arguments.length); - completion.getCompletion(args, done); - }; - self.locale = function (locale) { - argsert_1.argsert('[string]', [locale], arguments.length); - if (!locale) { - guessLocale(); - return y18n.getLocale(); - } - detectLocale = false; - y18n.setLocale(locale); - return self; - }; - self.updateStrings = self.updateLocale = function (obj) { - argsert_1.argsert('', [obj], arguments.length); - detectLocale = false; - y18n.updateLocale(obj); - return self; - }; - let detectLocale = true; - self.detectLocale = function (detect) { - argsert_1.argsert('', [detect], arguments.length); - detectLocale = detect; - return self; - }; - self.getDetectLocale = () => detectLocale; - var hasOutput = false; - var exitError = null; - // maybe exit, always capture - // context about why we wanted to exit. - self.exit = (code, err) => { - hasOutput = true; - exitError = err; - if (exitProcess) - process.exit(code); - }; - // we use a custom logger that buffers output, - // so that we can print to non-CLIs, e.g., chat-bots. - const _logger = { - log(...args) { - if (!self._hasParseCallback()) - console.log(...args); - hasOutput = true; - if (output.length) - output += '\n'; - output += args.join(' '); - }, - error(...args) { - if (!self._hasParseCallback()) - console.error(...args); - hasOutput = true; - if (output.length) - output += '\n'; - output += args.join(' '); - } - }; - self._getLoggerInstance = () => _logger; - // has yargs output an error our help - // message in the current execution context. - self._hasOutput = () => hasOutput; - self._setHasOutput = () => { - hasOutput = true; - }; - let recommendCommands; - self.recommendCommands = function (recommend = true) { - argsert_1.argsert('[boolean]', [recommend], arguments.length); - recommendCommands = recommend; - return self; - }; - self.getUsageInstance = () => usage; - self.getValidationInstance = () => validation; - self.getCommandInstance = () => command; - self.terminalWidth = () => { - argsert_1.argsert([], 0); - return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null; - }; - Object.defineProperty(self, 'argv', { - get: () => self._parseArgs(processArgs), - enumerable: true - }); - self._parseArgs = function parseArgs(args, shortCircuit, _calledFromCommand, commandIndex) { - let skipValidation = !!_calledFromCommand; - args = args || processArgs; - options.__ = y18n.__; - options.configuration = self.getParserConfiguration(); - const populateDoubleDash = !!options.configuration['populate--']; - const config = Object.assign({}, options.configuration, { - 'populate--': true - }); - const parsed = Parser.detailed(args, Object.assign({}, options, { - configuration: config - })); - let argv = parsed.argv; - if (parseContext) - argv = Object.assign({}, argv, parseContext); - const aliases = parsed.aliases; - argv.$0 = self.$0; - self.parsed = parsed; - try { - guessLocale(); // guess locale lazily, so that it can be turned off in chain. - // while building up the argv object, there - // are two passes through the parser. If completion - // is being performed short-circuit on the first pass. - if (shortCircuit) { - return (populateDoubleDash || _calledFromCommand) ? argv : self._copyDoubleDash(argv); - } - // if there's a handler associated with a - // command defer processing to it. - if (helpOpt) { - // consider any multi-char helpOpt alias as a valid help command - // unless all helpOpt aliases are single-char - // note that parsed.aliases is a normalized bidirectional map :) - const helpCmds = [helpOpt] - .concat(aliases[helpOpt] || []) - .filter(k => k.length > 1); - // check if help should trigger and strip it from _. - if (~helpCmds.indexOf(argv._[argv._.length - 1])) { - argv._.pop(); - argv[helpOpt] = true; - } - } - const handlerKeys = command.getCommands(); - const requestCompletions = completion.completionKey in argv; - const skipRecommendation = argv[helpOpt] || requestCompletions; - const skipDefaultCommand = skipRecommendation && (handlerKeys.length > 1 || handlerKeys[0] !== '$0'); - if (argv._.length) { - if (handlerKeys.length) { - let firstUnknownCommand; - for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) { - cmd = String(argv._[i]); - if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) { - // commands are executed using a recursive algorithm that executes - // the deepest command first; we keep track of the position in the - // argv._ array that is currently being executed. - const innerArgv = command.runCommand(cmd, self, parsed, i + 1); - return populateDoubleDash ? innerArgv : self._copyDoubleDash(innerArgv); - } - else if (!firstUnknownCommand && cmd !== completionCommand) { - firstUnknownCommand = cmd; - break; - } - } - // run the default command, if defined - if (command.hasDefaultCommand() && !skipDefaultCommand) { - const innerArgv = command.runCommand(null, self, parsed); - return populateDoubleDash ? innerArgv : self._copyDoubleDash(innerArgv); - } - // recommend a command if recommendCommands() has - // been enabled, and no commands were found to execute - if (recommendCommands && firstUnknownCommand && !skipRecommendation) { - validation.recommendCommands(firstUnknownCommand, handlerKeys); - } - } - // generate a completion script for adding to ~/.bashrc. - if (completionCommand && ~argv._.indexOf(completionCommand) && !requestCompletions) { - if (exitProcess) - setBlocking(true); - self.showCompletionScript(); - self.exit(0); - } - } - else if (command.hasDefaultCommand() && !skipDefaultCommand) { - const innerArgv = command.runCommand(null, self, parsed); - return populateDoubleDash ? innerArgv : self._copyDoubleDash(innerArgv); - } - // we must run completions first, a user might - // want to complete the --help or --version option. - if (requestCompletions) { - if (exitProcess) - setBlocking(true); - // we allow for asynchronous completions, - // e.g., loading in a list of commands from an API. - args = [].concat(args); - const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1); - completion.getCompletion(completionArgs, (completions) => { - ; - (completions || []).forEach((completion) => { - _logger.log(completion); - }); - self.exit(0); - }); - return (populateDoubleDash || _calledFromCommand) ? argv : self._copyDoubleDash(argv); - } - // Handle 'help' and 'version' options - // if we haven't already output help! - if (!hasOutput) { - Object.keys(argv).forEach((key) => { - if (key === helpOpt && argv[key]) { - if (exitProcess) - setBlocking(true); - skipValidation = true; - self.showHelp('log'); - self.exit(0); - } - else if (key === versionOpt && argv[key]) { - if (exitProcess) - setBlocking(true); - skipValidation = true; - usage.showVersion(); - self.exit(0); - } - }); - } - // Check if any of the options to skip validation were provided - if (!skipValidation && options.skipValidation.length > 0) { - skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true); - } - // If the help or version options where used and exitProcess is false, - // or if explicitly skipped, we won't run validations. - if (!skipValidation) { - if (parsed.error) - throw new yerror_1.YError(parsed.error.message); - // if we're executed via bash completion, don't - // bother with validation. - if (!requestCompletions) { - self._runValidation(argv, aliases, {}, parsed.error); - } - } - } - catch (err) { - if (err instanceof yerror_1.YError) - usage.fail(err.message, err); - else - throw err; - } - return (populateDoubleDash || _calledFromCommand) ? argv : self._copyDoubleDash(argv); - }; - // to simplify the parsing of positionals in commands, - // we temporarily populate '--' rather than _, with arguments - // after the '--' directive. After the parse, we copy these back. - self._copyDoubleDash = function (argv) { - if (is_promise_1.isPromise(argv) || !argv._ || !argv['--']) - return argv; - argv._.push.apply(argv._, argv['--']); - // TODO(bcoe): refactor command parsing such that this delete is not - // necessary: https://github.com/yargs/yargs/issues/1482 - try { - delete argv['--']; - } - catch (_err) { } - return argv; - }; - self._runValidation = function runValidation(argv, aliases, positionalMap, parseErrors, isDefaultCommand = false) { - if (parseErrors) - throw new yerror_1.YError(parseErrors.message); - validation.nonOptionCount(argv); - validation.requiredArguments(argv); - let failedStrictCommands = false; - if (strictCommands) { - failedStrictCommands = validation.unknownCommands(argv); - } - if (strict && !failedStrictCommands) { - validation.unknownArguments(argv, aliases, positionalMap, isDefaultCommand); - } - validation.customChecks(argv, aliases); - validation.limitedChoices(argv); - validation.implications(argv); - validation.conflicting(argv); - }; - function guessLocale() { - if (!detectLocale) - return; - const locale = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || process.env.LANGUAGE || 'en_US'; - self.locale(locale.replace(/[.:].*/, '')); - } - // an app should almost always have --version and --help, - // if you *really* want to disable this use .help(false)/.version(false). - self.help(); - self.version(); - return self; -} -exports.Yargs = Yargs; -// rebase an absolute path to a relative one with respect to a base directory -// exported for tests -function rebase(base, dir) { - return path.relative(base, dir); -} -exports.rebase = rebase; -function isYargsInstance(y) { - return !!y && (typeof y._parseArgs === 'function'); -} -exports.isYargsInstance = isYargsInstance; diff --git a/reverse_engineering/node_modules/yargs/build/lib/yerror.d.ts b/reverse_engineering/node_modules/yargs/build/lib/yerror.d.ts deleted file mode 100644 index 024d0c7..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/yerror.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare class YError extends Error { - name: string; - constructor(msg?: string | null); -} diff --git a/reverse_engineering/node_modules/yargs/build/lib/yerror.js b/reverse_engineering/node_modules/yargs/build/lib/yerror.js deleted file mode 100644 index 0fa146e..0000000 --- a/reverse_engineering/node_modules/yargs/build/lib/yerror.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.YError = void 0; -class YError extends Error { - constructor(msg) { - super(msg || 'yargs error'); - this.name = 'YError'; - Error.captureStackTrace(this, YError); - } -} -exports.YError = YError; diff --git a/reverse_engineering/node_modules/yargs/index.js b/reverse_engineering/node_modules/yargs/index.js deleted file mode 100644 index 7dc62de..0000000 --- a/reverse_engineering/node_modules/yargs/index.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict' -// classic singleton yargs API, to use yargs -// without running as a singleton do: -// require('yargs/yargs')(process.argv.slice(2)) -const yargs = require('./yargs') -const processArgv = require('./build/lib/process-argv') - -Argv(processArgv.getProcessArgvWithoutBin()) - -module.exports = Argv - -function Argv (processArgs, cwd) { - const argv = yargs(processArgs, cwd, require) - singletonify(argv) - return argv -} - -/* Hack an instance of Argv with process.argv into Argv - so people can do - require('yargs')(['--beeble=1','-z','zizzle']).argv - to parse a list of args and - require('yargs').argv - to get a parsed version of process.argv. -*/ -function singletonify (inst) { - Object.keys(inst).forEach((key) => { - if (key === 'argv') { - Argv.__defineGetter__(key, inst.__lookupGetter__(key)) - } else if (typeof inst[key] === 'function') { - Argv[key] = inst[key].bind(inst) - } else { - Argv.__defineGetter__('$0', () => { - return inst.$0 - }) - Argv.__defineGetter__('parsed', () => { - return inst.parsed - }) - } - }) -} diff --git a/reverse_engineering/node_modules/yargs/locales/be.json b/reverse_engineering/node_modules/yargs/locales/be.json deleted file mode 100644 index e28fa30..0000000 --- a/reverse_engineering/node_modules/yargs/locales/be.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Commands:": "Каманды:", - "Options:": "Опцыі:", - "Examples:": "Прыклады:", - "boolean": "булевы тып", - "count": "падлік", - "string": "радковы тып", - "number": "лік", - "array": "масіў", - "required": "неабходна", - "default": "па змаўчанні", - "default:": "па змаўчанні:", - "choices:": "магчымасці:", - "aliases:": "аліасы:", - "generated-value": "згенераванае значэнне", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", - "other": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", - "other": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s" - }, - "Missing argument value: %s": { - "one": "Не хапае значэння аргументу: %s", - "other": "Не хапае значэнняў аргументаў: %s" - }, - "Missing required argument: %s": { - "one": "Не хапае неабходнага аргументу: %s", - "other": "Не хапае неабходных аргументаў: %s" - }, - "Unknown argument: %s": { - "one": "Невядомы аргумент: %s", - "other": "Невядомыя аргументы: %s" - }, - "Invalid values:": "Несапраўдныя значэння:", - "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", - "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", - "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", - "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", - "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", - "Path to JSON config file": "Шлях да файла канфігурацыі JSON", - "Show help": "Паказаць дапамогу", - "Show version number": "Паказаць нумар версіі", - "Did you mean %s?": "Вы мелі на ўвазе %s?" -} diff --git a/reverse_engineering/node_modules/yargs/locales/de.json b/reverse_engineering/node_modules/yargs/locales/de.json deleted file mode 100644 index dc73ec3..0000000 --- a/reverse_engineering/node_modules/yargs/locales/de.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Commands:": "Kommandos:", - "Options:": "Optionen:", - "Examples:": "Beispiele:", - "boolean": "boolean", - "count": "Zähler", - "string": "string", - "number": "Zahl", - "array": "array", - "required": "erforderlich", - "default": "Standard", - "default:": "Standard:", - "choices:": "Möglichkeiten:", - "aliases:": "Aliase:", - "generated-value": "Generierter-Wert", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", - "other": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", - "other": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt" - }, - "Missing argument value: %s": { - "one": "Fehlender Argumentwert: %s", - "other": "Fehlende Argumentwerte: %s" - }, - "Missing required argument: %s": { - "one": "Fehlendes Argument: %s", - "other": "Fehlende Argumente: %s" - }, - "Unknown argument: %s": { - "one": "Unbekanntes Argument: %s", - "other": "Unbekannte Argumente: %s" - }, - "Invalid values:": "Unzulässige Werte:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", - "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", - "Implications failed:": "Fehlende abhängige Argumente:", - "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", - "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", - "Path to JSON config file": "Pfad zur JSON-Config Datei", - "Show help": "Hilfe anzeigen", - "Show version number": "Version anzeigen", - "Did you mean %s?": "Meintest du %s?" -} diff --git a/reverse_engineering/node_modules/yargs/locales/en.json b/reverse_engineering/node_modules/yargs/locales/en.json deleted file mode 100644 index d794947..0000000 --- a/reverse_engineering/node_modules/yargs/locales/en.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "Commands:": "Commands:", - "Options:": "Options:", - "Examples:": "Examples:", - "boolean": "boolean", - "count": "count", - "string": "string", - "number": "number", - "array": "array", - "required": "required", - "default": "default", - "default:": "default:", - "choices:": "choices:", - "aliases:": "aliases:", - "generated-value": "generated-value", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Not enough non-option arguments: got %s, need at least %s", - "other": "Not enough non-option arguments: got %s, need at least %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Too many non-option arguments: got %s, maximum of %s", - "other": "Too many non-option arguments: got %s, maximum of %s" - }, - "Missing argument value: %s": { - "one": "Missing argument value: %s", - "other": "Missing argument values: %s" - }, - "Missing required argument: %s": { - "one": "Missing required argument: %s", - "other": "Missing required arguments: %s" - }, - "Unknown argument: %s": { - "one": "Unknown argument: %s", - "other": "Unknown arguments: %s" - }, - "Invalid values:": "Invalid values:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", - "Argument check failed: %s": "Argument check failed: %s", - "Implications failed:": "Missing dependent arguments:", - "Not enough arguments following: %s": "Not enough arguments following: %s", - "Invalid JSON config file: %s": "Invalid JSON config file: %s", - "Path to JSON config file": "Path to JSON config file", - "Show help": "Show help", - "Show version number": "Show version number", - "Did you mean %s?": "Did you mean %s?", - "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive", - "Positionals:": "Positionals:", - "command": "command", - "deprecated": "deprecated", - "deprecated: %s": "deprecated: %s" -} diff --git a/reverse_engineering/node_modules/yargs/locales/es.json b/reverse_engineering/node_modules/yargs/locales/es.json deleted file mode 100644 index d77b461..0000000 --- a/reverse_engineering/node_modules/yargs/locales/es.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Commands:": "Comandos:", - "Options:": "Opciones:", - "Examples:": "Ejemplos:", - "boolean": "booleano", - "count": "cuenta", - "string": "cadena de caracteres", - "number": "número", - "array": "tabla", - "required": "requerido", - "default": "defecto", - "default:": "defecto:", - "choices:": "selección:", - "aliases:": "alias:", - "generated-value": "valor-generado", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", - "other": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", - "other": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s" - }, - "Missing argument value: %s": { - "one": "Falta argumento: %s", - "other": "Faltan argumentos: %s" - }, - "Missing required argument: %s": { - "one": "Falta argumento requerido: %s", - "other": "Faltan argumentos requeridos: %s" - }, - "Unknown argument: %s": { - "one": "Argumento desconocido: %s", - "other": "Argumentos desconocidos: %s" - }, - "Invalid values:": "Valores inválidos:", - "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", - "Argument check failed: %s": "Verificación de argumento ha fallado: %s", - "Implications failed:": "Implicaciones fallidas:", - "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", - "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", - "Path to JSON config file": "Ruta al archivo de configuración JSON", - "Show help": "Muestra ayuda", - "Show version number": "Muestra número de versión", - "Did you mean %s?": "Quisiste decir %s?" -} diff --git a/reverse_engineering/node_modules/yargs/locales/fi.json b/reverse_engineering/node_modules/yargs/locales/fi.json deleted file mode 100644 index 0728c57..0000000 --- a/reverse_engineering/node_modules/yargs/locales/fi.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "Commands:": "Komennot:", - "Options:": "Valinnat:", - "Examples:": "Esimerkkejä:", - "boolean": "totuusarvo", - "count": "lukumäärä", - "string": "merkkijono", - "number": "numero", - "array": "taulukko", - "required": "pakollinen", - "default": "oletusarvo", - "default:": "oletusarvo:", - "choices:": "vaihtoehdot:", - "aliases:": "aliakset:", - "generated-value": "generoitu-arvo", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s", - "other": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s", - "other": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s" - }, - "Missing argument value: %s": { - "one": "Argumentin arvo puuttuu: %s", - "other": "Argumentin arvot puuttuvat: %s" - }, - "Missing required argument: %s": { - "one": "Pakollinen argumentti puuttuu: %s", - "other": "Pakollisia argumentteja puuttuu: %s" - }, - "Unknown argument: %s": { - "one": "Tuntematon argumenttn: %s", - "other": "Tuntemattomia argumentteja: %s" - }, - "Invalid values:": "Virheelliset arvot:", - "Argument: %s, Given: %s, Choices: %s": "Argumentti: %s, Annettu: %s, Vaihtoehdot: %s", - "Argument check failed: %s": "Argumentin tarkistus epäonnistui: %s", - "Implications failed:": "Riippuvia argumentteja puuttuu:", - "Not enough arguments following: %s": "Argumentin perässä ei ole tarpeeksi argumentteja: %s", - "Invalid JSON config file: %s": "Epävalidi JSON-asetustiedosto: %s", - "Path to JSON config file": "JSON-asetustiedoston polku", - "Show help": "Näytä ohje", - "Show version number": "Näytä versionumero", - "Did you mean %s?": "Tarkoititko %s?", - "Arguments %s and %s are mutually exclusive" : "Argumentit %s ja %s eivät ole yhteensopivat", - "Positionals:": "Sijaintiparametrit:", - "command": "komento" -} diff --git a/reverse_engineering/node_modules/yargs/locales/fr.json b/reverse_engineering/node_modules/yargs/locales/fr.json deleted file mode 100644 index edd743f..0000000 --- a/reverse_engineering/node_modules/yargs/locales/fr.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "Commands:": "Commandes :", - "Options:": "Options :", - "Examples:": "Exemples :", - "boolean": "booléen", - "count": "compteur", - "string": "chaîne de caractères", - "number": "nombre", - "array": "tableau", - "required": "requis", - "default": "défaut", - "default:": "défaut :", - "choices:": "choix :", - "aliases:": "alias :", - "generated-value": "valeur générée", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Pas assez d'arguments (hors options) : reçu %s, besoin d'au moins %s", - "other": "Pas assez d'arguments (hors options) : reçus %s, besoin d'au moins %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Trop d'arguments (hors options) : reçu %s, maximum de %s", - "other": "Trop d'arguments (hors options) : reçus %s, maximum de %s" - }, - "Missing argument value: %s": { - "one": "Argument manquant : %s", - "other": "Arguments manquants : %s" - }, - "Missing required argument: %s": { - "one": "Argument requis manquant : %s", - "other": "Arguments requis manquants : %s" - }, - "Unknown argument: %s": { - "one": "Argument inconnu : %s", - "other": "Arguments inconnus : %s" - }, - "Unknown command: %s": { - "one": "Commande inconnue : %s", - "other": "Commandes inconnues : %s" - }, - "Invalid values:": "Valeurs invalides :", - "Argument: %s, Given: %s, Choices: %s": "Argument : %s, donné : %s, choix : %s", - "Argument check failed: %s": "Echec de la vérification de l'argument : %s", - "Implications failed:": "Arguments dépendants manquants :", - "Not enough arguments following: %s": "Pas assez d'arguments après : %s", - "Invalid JSON config file: %s": "Fichier de configuration JSON invalide : %s", - "Path to JSON config file": "Chemin du fichier de configuration JSON", - "Show help": "Affiche l'aide", - "Show version number": "Affiche le numéro de version", - "Did you mean %s?": "Vouliez-vous dire %s ?", - "Arguments %s and %s are mutually exclusive" : "Les arguments %s et %s sont mutuellement exclusifs", - "Positionals:": "Arguments positionnels :", - "command": "commande" -} diff --git a/reverse_engineering/node_modules/yargs/locales/hi.json b/reverse_engineering/node_modules/yargs/locales/hi.json deleted file mode 100644 index a9de77c..0000000 --- a/reverse_engineering/node_modules/yargs/locales/hi.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "Commands:": "आदेश:", - "Options:": "विकल्प:", - "Examples:": "उदाहरण:", - "boolean": "सत्यता", - "count": "संख्या", - "string": "वर्णों का तार ", - "number": "अंक", - "array": "सरणी", - "required": "आवश्यक", - "default": "डिफॉल्ट", - "default:": "डिफॉल्ट:", - "choices:": "विकल्प:", - "aliases:": "उपनाम:", - "generated-value": "उत्पन्न-मूल्य", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", - "other": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", - "other": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य" - }, - "Missing argument value: %s": { - "one": "कुछ तर्को के मूल्य गुम हैं: %s", - "other": "कुछ तर्को के मूल्य गुम हैं: %s" - }, - "Missing required argument: %s": { - "one": "आवश्यक तर्क गुम हैं: %s", - "other": "आवश्यक तर्क गुम हैं: %s" - }, - "Unknown argument: %s": { - "one": "अज्ञात तर्क प्राप्त: %s", - "other": "अज्ञात तर्क प्राप्त: %s" - }, - "Invalid values:": "अमान्य मूल्य:", - "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", - "Argument check failed: %s": "तर्क जांच विफल: %s", - "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", - "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", - "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", - "Path to JSON config file": "JSON config फाइल का पथ", - "Show help": "सहायता दिखाएँ", - "Show version number": "Version संख्या दिखाएँ", - "Did you mean %s?": "क्या आपका मतलब है %s?", - "Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं", - "Positionals:": "स्थानीय:", - "command": "आदेश" -} diff --git a/reverse_engineering/node_modules/yargs/locales/hu.json b/reverse_engineering/node_modules/yargs/locales/hu.json deleted file mode 100644 index 21492d0..0000000 --- a/reverse_engineering/node_modules/yargs/locales/hu.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Commands:": "Parancsok:", - "Options:": "Opciók:", - "Examples:": "Példák:", - "boolean": "boolean", - "count": "számláló", - "string": "szöveg", - "number": "szám", - "array": "tömb", - "required": "kötelező", - "default": "alapértelmezett", - "default:": "alapértelmezett:", - "choices:": "lehetőségek:", - "aliases:": "aliaszok:", - "generated-value": "generált-érték", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", - "other": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", - "other": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet" - }, - "Missing argument value: %s": { - "one": "Hiányzó argumentum érték: %s", - "other": "Hiányzó argumentum értékek: %s" - }, - "Missing required argument: %s": { - "one": "Hiányzó kötelező argumentum: %s", - "other": "Hiányzó kötelező argumentumok: %s" - }, - "Unknown argument: %s": { - "one": "Ismeretlen argumentum: %s", - "other": "Ismeretlen argumentumok: %s" - }, - "Invalid values:": "Érvénytelen érték:", - "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", - "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", - "Implications failed:": "Implikációk sikertelenek:", - "Not enough arguments following: %s": "Nem elég argumentum követi: %s", - "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", - "Path to JSON config file": "JSON konfigurációs file helye", - "Show help": "Súgo megjelenítése", - "Show version number": "Verziószám megjelenítése", - "Did you mean %s?": "Erre gondoltál %s?" -} diff --git a/reverse_engineering/node_modules/yargs/locales/id.json b/reverse_engineering/node_modules/yargs/locales/id.json deleted file mode 100644 index 125867c..0000000 --- a/reverse_engineering/node_modules/yargs/locales/id.json +++ /dev/null @@ -1,50 +0,0 @@ - -{ - "Commands:": "Perintah:", - "Options:": "Pilihan:", - "Examples:": "Contoh:", - "boolean": "boolean", - "count": "jumlah", - "number": "nomor", - "string": "string", - "array": "larik", - "required": "diperlukan", - "default": "bawaan", - "default:": "bawaan:", - "aliases:": "istilah lain:", - "choices:": "pilihan:", - "generated-value": "nilai-yang-dihasilkan", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Argumen wajib kurang: hanya %s, minimal %s", - "other": "Argumen wajib kurang: hanya %s, minimal %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Terlalu banyak argumen wajib: ada %s, maksimal %s", - "other": "Terlalu banyak argumen wajib: ada %s, maksimal %s" - }, - "Missing argument value: %s": { - "one": "Kurang argumen: %s", - "other": "Kurang argumen: %s" - }, - "Missing required argument: %s": { - "one": "Kurang argumen wajib: %s", - "other": "Kurang argumen wajib: %s" - }, - "Unknown argument: %s": { - "one": "Argumen tak diketahui: %s", - "other": "Argumen tak diketahui: %s" - }, - "Invalid values:": "Nilai-nilai tidak valid:", - "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", - "Argument check failed: %s": "Pemeriksaan argument gagal: %s", - "Implications failed:": "Implikasi gagal:", - "Not enough arguments following: %s": "Kurang argumen untuk: %s", - "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", - "Path to JSON config file": "Alamat berkas konfigurasi JSON", - "Show help": "Lihat bantuan", - "Show version number": "Lihat nomor versi", - "Did you mean %s?": "Maksud Anda: %s?", - "Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif", - "Positionals:": "Posisional-posisional:", - "command": "perintah" -} diff --git a/reverse_engineering/node_modules/yargs/locales/it.json b/reverse_engineering/node_modules/yargs/locales/it.json deleted file mode 100644 index fde5756..0000000 --- a/reverse_engineering/node_modules/yargs/locales/it.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Commands:": "Comandi:", - "Options:": "Opzioni:", - "Examples:": "Esempi:", - "boolean": "booleano", - "count": "contatore", - "string": "stringa", - "number": "numero", - "array": "vettore", - "required": "richiesto", - "default": "predefinito", - "default:": "predefinito:", - "choices:": "scelte:", - "aliases:": "alias:", - "generated-value": "valore generato", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", - "other": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", - "other": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s" - }, - "Missing argument value: %s": { - "one": "Argomento mancante: %s", - "other": "Argomenti mancanti: %s" - }, - "Missing required argument: %s": { - "one": "Argomento richiesto mancante: %s", - "other": "Argomenti richiesti mancanti: %s" - }, - "Unknown argument: %s": { - "one": "Argomento sconosciuto: %s", - "other": "Argomenti sconosciuti: %s" - }, - "Invalid values:": "Valori non validi:", - "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", - "Argument check failed: %s": "Controllo dell'argomento fallito: %s", - "Implications failed:": "Argomenti dipendenti mancanti:", - "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", - "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", - "Path to JSON config file": "Percorso del file di configurazione JSON", - "Show help": "Mostra la schermata di aiuto", - "Show version number": "Mostra il numero di versione", - "Did you mean %s?": "Intendi forse %s?" -} diff --git a/reverse_engineering/node_modules/yargs/locales/ja.json b/reverse_engineering/node_modules/yargs/locales/ja.json deleted file mode 100644 index 3954ae6..0000000 --- a/reverse_engineering/node_modules/yargs/locales/ja.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "Commands:": "コマンド:", - "Options:": "オプション:", - "Examples:": "例:", - "boolean": "真偽", - "count": "カウント", - "string": "文字列", - "number": "数値", - "array": "配列", - "required": "必須", - "default": "デフォルト", - "default:": "デフォルト:", - "choices:": "選択してください:", - "aliases:": "エイリアス:", - "generated-value": "生成された値", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", - "other": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", - "other": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:" - }, - "Missing argument value: %s": { - "one": "引数の値が見つかりません: %s", - "other": "引数の値が見つかりません: %s" - }, - "Missing required argument: %s": { - "one": "必須の引数が見つかりません: %s", - "other": "必須の引数が見つかりません: %s" - }, - "Unknown argument: %s": { - "one": "未知の引数です: %s", - "other": "未知の引数です: %s" - }, - "Invalid values:": "不正な値です:", - "Argument: %s, Given: %s, Choices: %s": "引数は %s です。与えられた値: %s, 選択してください: %s", - "Argument check failed: %s": "引数のチェックに失敗しました: %s", - "Implications failed:": "オプションの組み合わせで不正が生じました:", - "Not enough arguments following: %s": "次の引数が不足しています。: %s", - "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", - "Path to JSON config file": "JSONの設定ファイルまでのpath", - "Show help": "ヘルプを表示", - "Show version number": "バージョンを表示", - "Did you mean %s?": "もしかして %s?", - "Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません", - "Positionals:": "位置:", - "command": "コマンド", - "deprecated": "非推奨", - "deprecated: %s": "非推奨: %s" -} diff --git a/reverse_engineering/node_modules/yargs/locales/ko.json b/reverse_engineering/node_modules/yargs/locales/ko.json deleted file mode 100644 index e3187ea..0000000 --- a/reverse_engineering/node_modules/yargs/locales/ko.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "Commands:": "명령:", - "Options:": "옵션:", - "Examples:": "예시:", - "boolean": "여부", - "count": "개수", - "string": "문자열", - "number": "숫자", - "array": "배열", - "required": "필수", - "default": "기본", - "default:": "기본:", - "choices:": "선택:", - "aliases:": "별칭:", - "generated-value": "생성된 값", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "옵션이 아닌 인자가 충분치 않습니다: %s개를 받았지만, 적어도 %s개는 필요합니다", - "other": "옵션이 아닌 인자가 충분치 않습니다: %s개를 받았지만, 적어도 %s개는 필요합니다" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "옵션이 아닌 인자가 너무 많습니다: %s개를 받았지만, %s개 이하여야 합니다", - "other": "옵션이 아닌 인자가 너무 많습니다: %s개를 받았지만, %s개 이하여야 합니다" - }, - "Missing argument value: %s": { - "one": "인자값을 받지 못했습니다: %s", - "other": "인자값들을 받지 못했습니다: %s" - }, - "Missing required argument: %s": { - "one": "필수 인자를 받지 못했습니다: %s", - "other": "필수 인자들을 받지 못했습니다: %s" - }, - "Unknown argument: %s": { - "one": "알 수 없는 인자입니다: %s", - "other": "알 수 없는 인자들입니다: %s" - }, - "Invalid values:": "잘못된 값입니다:", - "Argument: %s, Given: %s, Choices: %s": "인자: %s, 입력받은 값: %s, 선택지: %s", - "Argument check failed: %s": "유효하지 않은 인자입니다: %s", - "Implications failed:": "옵션의 조합이 잘못되었습니다:", - "Not enough arguments following: %s": "인자가 충분하게 주어지지 않았습니다: %s", - "Invalid JSON config file: %s": "유효하지 않은 JSON 설정파일입니다: %s", - "Path to JSON config file": "JSON 설정파일 경로", - "Show help": "도움말을 보여줍니다", - "Show version number": "버전 넘버를 보여줍니다", - "Did you mean %s?": "찾고계신게 %s입니까?", - "Arguments %s and %s are mutually exclusive" : "%s와 %s 인자는 같이 사용될 수 없습니다", - "Positionals:": "위치:", - "command": "명령" -} diff --git a/reverse_engineering/node_modules/yargs/locales/nb.json b/reverse_engineering/node_modules/yargs/locales/nb.json deleted file mode 100644 index 6f410ed..0000000 --- a/reverse_engineering/node_modules/yargs/locales/nb.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "Commands:": "Kommandoer:", - "Options:": "Alternativer:", - "Examples:": "Eksempler:", - "boolean": "boolsk", - "count": "antall", - "string": "streng", - "number": "nummer", - "array": "matrise", - "required": "obligatorisk", - "default": "standard", - "default:": "standard:", - "choices:": "valg:", - "generated-value": "generert-verdi", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", - "other": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", - "other": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s" - }, - "Missing argument value: %s": { - "one": "Mangler argument verdi: %s", - "other": "Mangler argument verdier: %s" - }, - "Missing required argument: %s": { - "one": "Mangler obligatorisk argument: %s", - "other": "Mangler obligatoriske argumenter: %s" - }, - "Unknown argument: %s": { - "one": "Ukjent argument: %s", - "other": "Ukjente argumenter: %s" - }, - "Invalid values:": "Ugyldige verdier:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", - "Argument check failed: %s": "Argumentsjekk mislyktes: %s", - "Implications failed:": "Konsekvensene mislyktes:", - "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", - "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", - "Path to JSON config file": "Bane til JSON konfigurasjonsfil", - "Show help": "Vis hjelp", - "Show version number": "Vis versjonsnummer" -} diff --git a/reverse_engineering/node_modules/yargs/locales/nl.json b/reverse_engineering/node_modules/yargs/locales/nl.json deleted file mode 100644 index 9ff95c5..0000000 --- a/reverse_engineering/node_modules/yargs/locales/nl.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "Commands:": "Commando's:", - "Options:": "Opties:", - "Examples:": "Voorbeelden:", - "boolean": "booleaans", - "count": "aantal", - "string": "string", - "number": "getal", - "array": "lijst", - "required": "verplicht", - "default": "standaard", - "default:": "standaard:", - "choices:": "keuzes:", - "aliases:": "aliassen:", - "generated-value": "gegenereerde waarde", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig", - "other": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s", - "other": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s" - }, - "Missing argument value: %s": { - "one": "Missende argumentwaarde: %s", - "other": "Missende argumentwaarden: %s" - }, - "Missing required argument: %s": { - "one": "Missend verplicht argument: %s", - "other": "Missende verplichte argumenten: %s" - }, - "Unknown argument: %s": { - "one": "Onbekend argument: %s", - "other": "Onbekende argumenten: %s" - }, - "Invalid values:": "Ongeldige waarden:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", - "Argument check failed: %s": "Argumentcontrole mislukt: %s", - "Implications failed:": "Ontbrekende afhankelijke argumenten:", - "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", - "Invalid JSON config file: %s": "Ongeldig JSON-config-bestand: %s", - "Path to JSON config file": "Pad naar JSON-config-bestand", - "Show help": "Toon help", - "Show version number": "Toon versienummer", - "Did you mean %s?": "Bedoelde u misschien %s?", - "Arguments %s and %s are mutually exclusive": "Argumenten %s en %s kunnen niet tegelijk gebruikt worden", - "Positionals:": "Positie-afhankelijke argumenten", - "command": "commando" -} diff --git a/reverse_engineering/node_modules/yargs/locales/nn.json b/reverse_engineering/node_modules/yargs/locales/nn.json deleted file mode 100644 index 24479ac..0000000 --- a/reverse_engineering/node_modules/yargs/locales/nn.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "Commands:": "Kommandoar:", - "Options:": "Alternativ:", - "Examples:": "Døme:", - "boolean": "boolsk", - "count": "mengd", - "string": "streng", - "number": "nummer", - "array": "matrise", - "required": "obligatorisk", - "default": "standard", - "default:": "standard:", - "choices:": "val:", - "generated-value": "generert-verdi", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s", - "other": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "For mange ikkje-alternativ argument: fekk %s, maksimum %s", - "other": "For mange ikkje-alternativ argument: fekk %s, maksimum %s" - }, - "Missing argument value: %s": { - "one": "Manglar argumentverdi: %s", - "other": "Manglar argumentverdiar: %s" - }, - "Missing required argument: %s": { - "one": "Manglar obligatorisk argument: %s", - "other": "Manglar obligatoriske argument: %s" - }, - "Unknown argument: %s": { - "one": "Ukjent argument: %s", - "other": "Ukjende argument: %s" - }, - "Invalid values:": "Ugyldige verdiar:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gjeve: %s, Val: %s", - "Argument check failed: %s": "Argumentsjekk mislukkast: %s", - "Implications failed:": "Konsekvensane mislukkast:", - "Not enough arguments following: %s": "Ikkje nok fylgjande argument: %s", - "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", - "Path to JSON config file": "Bane til JSON konfigurasjonsfil", - "Show help": "Vis hjelp", - "Show version number": "Vis versjonsnummer" -} diff --git a/reverse_engineering/node_modules/yargs/locales/pirate.json b/reverse_engineering/node_modules/yargs/locales/pirate.json deleted file mode 100644 index dcb5cb7..0000000 --- a/reverse_engineering/node_modules/yargs/locales/pirate.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "Commands:": "Choose yer command:", - "Options:": "Options for me hearties!", - "Examples:": "Ex. marks the spot:", - "required": "requi-yar-ed", - "Missing required argument: %s": { - "one": "Ye be havin' to set the followin' argument land lubber: %s", - "other": "Ye be havin' to set the followin' arguments land lubber: %s" - }, - "Show help": "Parlay this here code of conduct", - "Show version number": "'Tis the version ye be askin' fer", - "Arguments %s and %s are mutually exclusive" : "Yon scurvy dogs %s and %s be as bad as rum and a prudish wench" -} diff --git a/reverse_engineering/node_modules/yargs/locales/pl.json b/reverse_engineering/node_modules/yargs/locales/pl.json deleted file mode 100644 index a41d4bd..0000000 --- a/reverse_engineering/node_modules/yargs/locales/pl.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "Commands:": "Polecenia:", - "Options:": "Opcje:", - "Examples:": "Przykłady:", - "boolean": "boolean", - "count": "ilość", - "string": "ciąg znaków", - "number": "liczba", - "array": "tablica", - "required": "wymagany", - "default": "domyślny", - "default:": "domyślny:", - "choices:": "dostępne:", - "aliases:": "aliasy:", - "generated-value": "wygenerowana-wartość", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", - "other": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", - "other": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s" - }, - "Missing argument value: %s": { - "one": "Brak wartości dla argumentu: %s", - "other": "Brak wartości dla argumentów: %s" - }, - "Missing required argument: %s": { - "one": "Brak wymaganego argumentu: %s", - "other": "Brak wymaganych argumentów: %s" - }, - "Unknown argument: %s": { - "one": "Nieznany argument: %s", - "other": "Nieznane argumenty: %s" - }, - "Invalid values:": "Nieprawidłowe wartości:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", - "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", - "Implications failed:": "Założenia nie zostały spełnione:", - "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", - "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", - "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", - "Show help": "Pokaż pomoc", - "Show version number": "Pokaż numer wersji", - "Did you mean %s?": "Czy chodziło Ci o %s?", - "Arguments %s and %s are mutually exclusive": "Argumenty %s i %s wzajemnie się wykluczają", - "Positionals:": "Pozycyjne:", - "command": "polecenie" -} diff --git a/reverse_engineering/node_modules/yargs/locales/pt.json b/reverse_engineering/node_modules/yargs/locales/pt.json deleted file mode 100644 index 0c8ac99..0000000 --- a/reverse_engineering/node_modules/yargs/locales/pt.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "Commands:": "Comandos:", - "Options:": "Opções:", - "Examples:": "Exemplos:", - "boolean": "boolean", - "count": "contagem", - "string": "cadeia de caracteres", - "number": "número", - "array": "arranjo", - "required": "requerido", - "default": "padrão", - "default:": "padrão:", - "choices:": "escolhas:", - "generated-value": "valor-gerado", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", - "other": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", - "other": "Excesso de argumentos não opcionais: recebido %s, máximo de %s" - }, - "Missing argument value: %s": { - "one": "Falta valor de argumento: %s", - "other": "Falta valores de argumento: %s" - }, - "Missing required argument: %s": { - "one": "Falta argumento obrigatório: %s", - "other": "Faltando argumentos obrigatórios: %s" - }, - "Unknown argument: %s": { - "one": "Argumento desconhecido: %s", - "other": "Argumentos desconhecidos: %s" - }, - "Invalid values:": "Valores inválidos:", - "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", - "Argument check failed: %s": "Verificação de argumento falhou: %s", - "Implications failed:": "Implicações falharam:", - "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", - "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", - "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", - "Show help": "Mostra ajuda", - "Show version number": "Mostra número de versão", - "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" -} diff --git a/reverse_engineering/node_modules/yargs/locales/pt_BR.json b/reverse_engineering/node_modules/yargs/locales/pt_BR.json deleted file mode 100644 index eae1ec6..0000000 --- a/reverse_engineering/node_modules/yargs/locales/pt_BR.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "Commands:": "Comandos:", - "Options:": "Opções:", - "Examples:": "Exemplos:", - "boolean": "booleano", - "count": "contagem", - "string": "string", - "number": "número", - "array": "array", - "required": "obrigatório", - "default:": "padrão:", - "choices:": "opções:", - "aliases:": "sinônimos:", - "generated-value": "valor-gerado", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", - "other": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Excesso de argumentos: recebido %s, máximo de %s", - "other": "Excesso de argumentos: recebido %s, máximo de %s" - }, - "Missing argument value: %s": { - "one": "Falta valor de argumento: %s", - "other": "Falta valores de argumento: %s" - }, - "Missing required argument: %s": { - "one": "Falta argumento obrigatório: %s", - "other": "Faltando argumentos obrigatórios: %s" - }, - "Unknown argument: %s": { - "one": "Argumento desconhecido: %s", - "other": "Argumentos desconhecidos: %s" - }, - "Invalid values:": "Valores inválidos:", - "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", - "Argument check failed: %s": "Verificação de argumento falhou: %s", - "Implications failed:": "Implicações falharam:", - "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", - "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", - "Path to JSON config file": "Caminho para o arquivo JSON de configuração", - "Show help": "Exibe ajuda", - "Show version number": "Exibe a versão", - "Did you mean %s?": "Você quis dizer %s?", - "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos", - "Positionals:": "Posicionais:", - "command": "comando" -} diff --git a/reverse_engineering/node_modules/yargs/locales/ru.json b/reverse_engineering/node_modules/yargs/locales/ru.json deleted file mode 100644 index 5f7f768..0000000 --- a/reverse_engineering/node_modules/yargs/locales/ru.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Commands:": "Команды:", - "Options:": "Опции:", - "Examples:": "Примеры:", - "boolean": "булевый тип", - "count": "подсчет", - "string": "строковой тип", - "number": "число", - "array": "массив", - "required": "необходимо", - "default": "по умолчанию", - "default:": "по умолчанию:", - "choices:": "возможности:", - "aliases:": "алиасы:", - "generated-value": "генерированное значение", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", - "other": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", - "other": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s" - }, - "Missing argument value: %s": { - "one": "Не хватает значения аргумента: %s", - "other": "Не хватает значений аргументов: %s" - }, - "Missing required argument: %s": { - "one": "Не хватает необходимого аргумента: %s", - "other": "Не хватает необходимых аргументов: %s" - }, - "Unknown argument: %s": { - "one": "Неизвестный аргумент: %s", - "other": "Неизвестные аргументы: %s" - }, - "Invalid values:": "Недействительные значения:", - "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", - "Argument check failed: %s": "Проверка аргументов не удалась: %s", - "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", - "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", - "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", - "Path to JSON config file": "Путь к файлу конфигурации JSON", - "Show help": "Показать помощь", - "Show version number": "Показать номер версии", - "Did you mean %s?": "Вы имели в виду %s?" -} diff --git a/reverse_engineering/node_modules/yargs/locales/th.json b/reverse_engineering/node_modules/yargs/locales/th.json deleted file mode 100644 index 33b048e..0000000 --- a/reverse_engineering/node_modules/yargs/locales/th.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Commands:": "คอมมาน", - "Options:": "ออฟชั่น", - "Examples:": "ตัวอย่าง", - "boolean": "บูลีน", - "count": "นับ", - "string": "สตริง", - "number": "ตัวเลข", - "array": "อาเรย์", - "required": "จำเป็น", - "default": "ค่าเริ่มต้", - "default:": "ค่าเริ่มต้น", - "choices:": "ตัวเลือก", - "aliases:": "เอเลียส", - "generated-value": "ค่าที่ถูกสร้างขึ้น", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", - "other": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", - "other": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า" - }, - "Missing argument value: %s": { - "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", - "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" - }, - "Missing required argument: %s": { - "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", - "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" - }, - "Unknown argument: %s": { - "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", - "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" - }, - "Invalid values:": "ค่าไม่ถูกต้อง:", - "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", - "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", - "Implications failed:": "Implications ไม่สำเร็จ:", - "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", - "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", - "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", - "Show help": "ขอความช่วยเหลือ", - "Show version number": "แสดงตัวเลขเวอร์ชั่น", - "Did you mean %s?": "คุณหมายถึง %s?" -} diff --git a/reverse_engineering/node_modules/yargs/locales/tr.json b/reverse_engineering/node_modules/yargs/locales/tr.json deleted file mode 100644 index 0d0d2cc..0000000 --- a/reverse_engineering/node_modules/yargs/locales/tr.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "Commands:": "Komutlar:", - "Options:": "Seçenekler:", - "Examples:": "Örnekler:", - "boolean": "boolean", - "count": "sayı", - "string": "string", - "number": "numara", - "array": "array", - "required": "zorunlu", - "default": "varsayılan", - "default:": "varsayılan:", - "choices:": "seçimler:", - "aliases:": "takma adlar:", - "generated-value": "oluşturulan-değer", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", - "other": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", - "other": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s" - }, - "Missing argument value: %s": { - "one": "Eksik argüman değeri: %s", - "other": "Eksik argüman değerleri: %s" - }, - "Missing required argument: %s": { - "one": "Eksik zorunlu argüman: %s", - "other": "Eksik zorunlu argümanlar: %s" - }, - "Unknown argument: %s": { - "one": "Bilinmeyen argüman: %s", - "other": "Bilinmeyen argümanlar: %s" - }, - "Invalid values:": "Geçersiz değerler:", - "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", - "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", - "Implications failed:": "Sonuçlar başarısız oldu:", - "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", - "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", - "Path to JSON config file": "JSON yapılandırma dosya konumu", - "Show help": "Yardım detaylarını göster", - "Show version number": "Versiyon detaylarını göster", - "Did you mean %s?": "Bunu mu demek istediniz: %s?", - "Positionals:": "Sıralılar:", - "command": "komut" -} diff --git a/reverse_engineering/node_modules/yargs/locales/zh_CN.json b/reverse_engineering/node_modules/yargs/locales/zh_CN.json deleted file mode 100644 index 257d26b..0000000 --- a/reverse_engineering/node_modules/yargs/locales/zh_CN.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "Commands:": "命令:", - "Options:": "选项:", - "Examples:": "示例:", - "boolean": "布尔", - "count": "计数", - "string": "字符串", - "number": "数字", - "array": "数组", - "required": "必需", - "default": "默认值", - "default:": "默认值:", - "choices:": "可选值:", - "generated-value": "生成的值", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", - "other": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", - "other": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个" - }, - "Missing argument value: %s": { - "one": "没有给此选项指定值:%s", - "other": "没有给这些选项指定值:%s" - }, - "Missing required argument: %s": { - "one": "缺少必须的选项:%s", - "other": "缺少这些必须的选项:%s" - }, - "Unknown argument: %s": { - "one": "无法识别的选项:%s", - "other": "无法识别这些选项:%s" - }, - "Invalid values:": "无效的选项值:", - "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", - "Argument check failed: %s": "选项值验证失败:%s", - "Implications failed:": "缺少依赖的选项:", - "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", - "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", - "Path to JSON config file": "JSON 配置文件的路径", - "Show help": "显示帮助信息", - "Show version number": "显示版本号", - "Did you mean %s?": "是指 %s?", - "Arguments %s and %s are mutually exclusive" : "选项 %s 和 %s 是互斥的", - "Positionals:": "位置:", - "command": "命令" -} diff --git a/reverse_engineering/node_modules/yargs/locales/zh_TW.json b/reverse_engineering/node_modules/yargs/locales/zh_TW.json deleted file mode 100644 index e3c7bcf..0000000 --- a/reverse_engineering/node_modules/yargs/locales/zh_TW.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "Commands:": "命令:", - "Options:": "選項:", - "Examples:": "例:", - "boolean": "布林", - "count": "次數", - "string": "字串", - "number": "數字", - "array": "陣列", - "required": "必須", - "default": "預設值", - "default:": "預設值:", - "choices:": "可選值:", - "aliases:": "別名:", - "generated-value": "生成的值", - "Not enough non-option arguments: got %s, need at least %s": { - "one": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", - "other": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個" - }, - "Too many non-option arguments: got %s, maximum of %s": { - "one": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", - "other": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個" - }, - "Missing argument value: %s": { - "one": "此引數無指定值:%s", - "other": "這些引數無指定值:%s" - }, - "Missing required argument: %s": { - "one": "缺少必須的引數:%s", - "other": "缺少這些必須的引數:%s" - }, - "Unknown argument: %s": { - "one": "未知的引數:%s", - "other": "未知的這些引數:%s" - }, - "Invalid values:": "無效的選項值:", - "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", - "Argument check failed: %s": "引數驗證失敗:%s", - "Implications failed:": "缺少依賴的選項:", - "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", - "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", - "Path to JSON config file": "JSON 設置文件的路徑", - "Show help": "顯示說明", - "Show version number": "顯示版本", - "Did you mean %s?": "是指 %s?", - "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 是互斥的" -} diff --git a/reverse_engineering/node_modules/yargs/package.json b/reverse_engineering/node_modules/yargs/package.json deleted file mode 100644 index dc3018a..0000000 --- a/reverse_engineering/node_modules/yargs/package.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "name": "yargs", - "version": "15.4.1", - "description": "yargs the modern, pirate-themed, successor to optimist.", - "main": "./index.js", - "contributors": [ - { - "name": "Yargs Contributors", - "url": "https://github.com/yargs/yargs/graphs/contributors" - } - ], - "files": [ - "index.js", - "yargs.js", - "build", - "locales", - "LICENSE" - ], - "dependencies": { - "cliui": "^6.0.0", - "decamelize": "^1.2.0", - "find-up": "^4.1.0", - "get-caller-file": "^2.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^4.2.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^18.1.2" - }, - "devDependencies": { - "@types/chai": "^4.2.11", - "@types/decamelize": "^1.2.0", - "@types/mocha": "^7.0.2", - "@types/node": "^10.0.3", - "@typescript-eslint/eslint-plugin": "^3.0.0", - "@typescript-eslint/parser": "^3.0.0", - "c8": "^7.0.0", - "chai": "^4.2.0", - "chalk": "^4.0.0", - "coveralls": "^3.0.9", - "cpr": "^3.0.1", - "cross-spawn": "^7.0.0", - "es6-promise": "^4.2.5", - "eslint": "^6.8.0", - "eslint-plugin-import": "^2.20.1", - "eslint-plugin-node": "^11.0.0", - "gts": "^2.0.0-alpha.4", - "hashish": "0.0.4", - "mocha": "^7.0.0", - "rimraf": "^3.0.2", - "standardx": "^5.0.0", - "typescript": "^3.7.0", - "which": "^2.0.0", - "yargs-test-extends": "^1.0.1" - }, - "scripts": { - "fix": "standardx --fix && standardx --fix **/*.ts", - "posttest": "npm run check", - "test": "c8 mocha --require ./test/before.js --timeout=12000 --check-leaks", - "coverage": "c8 report --check-coverage", - "check": "standardx && standardx **/*.ts", - "compile": "rimraf build && tsc", - "prepare": "npm run compile", - "pretest": "npm run compile -- -p tsconfig.test.json" - }, - "repository": { - "type": "git", - "url": "https://github.com/yargs/yargs.git" - }, - "homepage": "https://yargs.js.org/", - "standardx": { - "ignore": [ - "build", - "**/example/**" - ] - }, - "keywords": [ - "argument", - "args", - "option", - "parser", - "parsing", - "cli", - "command" - ], - "license": "MIT", - "engines": { - "node": ">=8" - } -} diff --git a/reverse_engineering/node_modules/yargs/yargs.js b/reverse_engineering/node_modules/yargs/yargs.js deleted file mode 100644 index 93e8059..0000000 --- a/reverse_engineering/node_modules/yargs/yargs.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict' - -// an async function fails early in Node.js versions prior to 8. -async function requiresNode8OrGreater () {} -requiresNode8OrGreater() - -const { Yargs, rebase } = require('./build/lib/yargs') -const Parser = require('yargs-parser') - -exports = module.exports = Yargs -exports.rebase = rebase - -// allow consumers to directly use the version of yargs-parser used by yargs -exports.Parser = Parser diff --git a/reverse_engineering/package.json b/reverse_engineering/package.json deleted file mode 100644 index fea74ca..0000000 --- a/reverse_engineering/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "documentdb", - "version": "1.0.0", - "description": "", - "author": "Hackolade", - "dependencies": { - "bson": "^1.1.6", - "mongodb": "^3.7.3", - "mongodb-collection-sample": "^4.5.1", - "tunnel-ssh": "^4.1.6" - }, - "installed": true -} diff --git a/types/array.json b/types/array.json index cbd1ef4..f023a86 100644 --- a/types/array.json +++ b/types/array.json @@ -17,4 +17,4 @@ "maxItems": "", "uniqueItems": false } -} \ No newline at end of file +} diff --git a/types/binary.json b/types/binary.json index 3c091f2..377d3a3 100644 --- a/types/binary.json +++ b/types/binary.json @@ -15,4 +15,4 @@ "enum": [], "sample": "" } -} \ No newline at end of file +} diff --git a/types/boolean.json b/types/boolean.json index 8f49c25..fda702b 100644 --- a/types/boolean.json +++ b/types/boolean.json @@ -15,4 +15,4 @@ "foreignField": [], "sample": "" } -} \ No newline at end of file +} diff --git a/types/date.json b/types/date.json index 7ab2fc4..4a6a5e5 100644 --- a/types/date.json +++ b/types/date.json @@ -14,19 +14,27 @@ "default": "", "sample": "" }, - "descriptor": [{ - "format": "YYYY-MM-DD" - }, { - "format": "YYYY-MM-DD hh:mm:ss" - }, { - "format": "YYYY-MM-DD hh:mm:ss.nnn" - }, { - "format": "YYYY-MM-DD hh:mm:ss.nnnnnn" - }, { - "format": "YYYY-MM-DD hh:mm:ss.nnnnnnnnn" - }, { - "format": "YYYY-MM-DD hh:mm:ss.nnnZ" - }, { - "format": "YYYY-MM-DD hh:mm:ss.nnnnnnZ" - }] -} \ No newline at end of file + "descriptor": [ + { + "format": "YYYY-MM-DD" + }, + { + "format": "YYYY-MM-DD hh:mm:ss" + }, + { + "format": "YYYY-MM-DD hh:mm:ss.nnn" + }, + { + "format": "YYYY-MM-DD hh:mm:ss.nnnnnn" + }, + { + "format": "YYYY-MM-DD hh:mm:ss.nnnnnnnnn" + }, + { + "format": "YYYY-MM-DD hh:mm:ss.nnnZ" + }, + { + "format": "YYYY-MM-DD hh:mm:ss.nnnnnnZ" + } + ] +} diff --git a/types/document.json b/types/document.json index c6e8efa..de89bf0 100644 --- a/types/document.json +++ b/types/document.json @@ -16,4 +16,4 @@ "maxProperties": "", "additionalProperties": false } -} \ No newline at end of file +} diff --git a/types/maxKey.json b/types/maxKey.json index 2d42298..86bcd84 100644 --- a/types/maxKey.json +++ b/types/maxKey.json @@ -12,4 +12,4 @@ "foreignEntity": "", "foreignField": [] } -} \ No newline at end of file +} diff --git a/types/minKey.json b/types/minKey.json index 7ef3e2c..5bc145b 100644 --- a/types/minKey.json +++ b/types/minKey.json @@ -12,4 +12,4 @@ "foreignEntity": "", "foreignField": [] } -} \ No newline at end of file +} diff --git a/types/null.json b/types/null.json index d24d883..63ff4f1 100644 --- a/types/null.json +++ b/types/null.json @@ -12,4 +12,4 @@ "foreignField": [], "format": "" } -} \ No newline at end of file +} diff --git a/types/numeric.json b/types/numeric.json index 46463a5..7b1a2ad 100644 --- a/types/numeric.json +++ b/types/numeric.json @@ -1,75 +1,75 @@ { - "name": "numeric", - "erdAbbreviation": "", - "dtdAbbreviation": "{123}", - "useSample": true, - "defaultValues": { - "primaryKey": false, - "relationshipType": "", - "parentRelationship": "", - "childRelationships": [], - "foreignCollection": "", - "foreignField": [], - "default": "", - "mode": "", - "unit": "", - "minimum": "", - "exclusiveMinimum": false, - "maximum": "", - "exclusiveMaximum": false, - "multipleOf": "", - "divisibleBy": "", - "enum": [], - "sample": "" - }, - "descriptor": [ - { - "schema": { - "mode": "int32" - }, - "capacity": 4 - }, - { - "schema": { - "mode": "int32" - }, - "mode": "smallint" - }, - { - "schema": { - "mode": "int32" - }, - "mode": "integer" - }, - { - "schema": { - "mode": "int64" - }, - "capacity": 8 - }, - { - "schema": { - "mode": "double" - }, - "capacity": 8 - }, - { - "schema": { - "mode": "int64" - }, - "mode": "long" - }, - { - "schema": { - "mode": "double" - }, - "mode": "decimal" - }, - { - "schema": { - "mode": "double" - }, - "mode": "floating" - } - ] + "name": "numeric", + "erdAbbreviation": "", + "dtdAbbreviation": "{123}", + "useSample": true, + "defaultValues": { + "primaryKey": false, + "relationshipType": "", + "parentRelationship": "", + "childRelationships": [], + "foreignCollection": "", + "foreignField": [], + "default": "", + "mode": "", + "unit": "", + "minimum": "", + "exclusiveMinimum": false, + "maximum": "", + "exclusiveMaximum": false, + "multipleOf": "", + "divisibleBy": "", + "enum": [], + "sample": "" + }, + "descriptor": [ + { + "schema": { + "mode": "int32" + }, + "capacity": 4 + }, + { + "schema": { + "mode": "int32" + }, + "mode": "smallint" + }, + { + "schema": { + "mode": "int32" + }, + "mode": "integer" + }, + { + "schema": { + "mode": "int64" + }, + "capacity": 8 + }, + { + "schema": { + "mode": "double" + }, + "capacity": 8 + }, + { + "schema": { + "mode": "int64" + }, + "mode": "long" + }, + { + "schema": { + "mode": "double" + }, + "mode": "decimal" + }, + { + "schema": { + "mode": "double" + }, + "mode": "floating" + } + ] } diff --git a/types/object.json b/types/object.json index c6e8efa..de89bf0 100644 --- a/types/object.json +++ b/types/object.json @@ -16,4 +16,4 @@ "maxProperties": "", "additionalProperties": false } -} \ No newline at end of file +} diff --git a/types/objectId.json b/types/objectId.json index 508d33e..04738d0 100644 --- a/types/objectId.json +++ b/types/objectId.json @@ -15,4 +15,4 @@ "default": "", "sample": "" } -} \ No newline at end of file +} diff --git a/types/regex.json b/types/regex.json index 6a1cec8..d250f57 100644 --- a/types/regex.json +++ b/types/regex.json @@ -14,4 +14,4 @@ "default": "", "sample": "" } -} \ No newline at end of file +} diff --git a/types/string.json b/types/string.json index 5d5bdad..169c679 100644 --- a/types/string.json +++ b/types/string.json @@ -15,7 +15,7 @@ "maxLength": "", "pattern": "", "enum": [], - "sample":"", - "comments":"" + "sample": "", + "comments": "" } -} \ No newline at end of file +} diff --git a/types/timestamp.json b/types/timestamp.json index 1c28b4e..cf128a7 100644 --- a/types/timestamp.json +++ b/types/timestamp.json @@ -15,4 +15,4 @@ "default": "", "sample": "" } -} \ No newline at end of file +} diff --git a/validation/validationRegularExpressions.json b/validation/validationRegularExpressions.json index ba4b132..c7c3b47 100644 --- a/validation/validationRegularExpressions.json +++ b/validation/validationRegularExpressions.json @@ -1,12 +1,10 @@ /* -* Copyright © 2016-2017 by IntegrIT S.A. dba Hackolade. All rights reserved. -* -* The copyright to the computer software herein is the property of IntegrIT S.A. -* The software may be used and/or copied only with the written permission of -* IntegrIT S.A. or in accordance with the terms and conditions stipulated in -* the agreement/contract under which the software has been supplied. -* -*/ -{ - -} \ No newline at end of file + * Copyright © 2016-2017 by IntegrIT S.A. dba Hackolade. All rights reserved. + * + * The copyright to the computer software herein is the property of IntegrIT S.A. + * The software may be used and/or copied only with the written permission of + * IntegrIT S.A. or in accordance with the terms and conditions stipulated in + * the agreement/contract under which the software has been supplied. + * + */ +{}
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-